aoptx86.pas 684 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892
  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) : 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. case getsupreg(reg) of
  861. { RS_EAX = RS_RAX on x86-64 }
  862. RS_EAX:
  863. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  864. RS_ECX:
  865. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  866. RS_EDX:
  867. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  868. RS_EBX:
  869. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  870. RS_ESP:
  871. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  872. RS_EBP:
  873. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  874. RS_ESI:
  875. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  876. RS_EDI:
  877. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  878. else
  879. ;
  880. end;
  881. if result then
  882. exit;
  883. end
  884. else if getregtype(reg)=R_MMREGISTER then
  885. begin
  886. case getsupreg(reg) of
  887. RS_XMM0:
  888. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  889. else
  890. ;
  891. end;
  892. if result then
  893. exit;
  894. end
  895. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  896. begin
  897. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  898. exit(true);
  899. case getsubreg(reg) of
  900. R_SUBFLAGCARRY:
  901. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  902. R_SUBFLAGPARITY:
  903. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  904. R_SUBFLAGAUXILIARY:
  905. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  906. R_SUBFLAGZERO:
  907. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  908. R_SUBFLAGSIGN:
  909. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  910. R_SUBFLAGOVERFLOW:
  911. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  912. R_SUBFLAGINTERRUPT:
  913. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  914. R_SUBFLAGDIRECTION:
  915. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  916. R_SUBW,R_SUBD,R_SUBQ:
  917. { Everything except the direction bits }
  918. Result:=
  919. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  920. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  921. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  922. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  923. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  924. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  925. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  926. else
  927. ;
  928. end;
  929. if result then
  930. exit;
  931. end
  932. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  933. exit(true);
  934. Result:=inherited RegInInstruction(Reg, p1);
  935. end;
  936. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  937. const
  938. WriteOps: array[0..3] of set of TInsChange =
  939. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  940. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  941. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  942. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  943. var
  944. OperIdx: Integer;
  945. begin
  946. Result := False;
  947. if p1.typ <> ait_instruction then
  948. exit;
  949. with insprop[taicpu(p1).opcode] do
  950. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  951. begin
  952. case getsubreg(reg) of
  953. R_SUBW,R_SUBD,R_SUBQ:
  954. Result :=
  955. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  956. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  957. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  958. R_SUBFLAGCARRY:
  959. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  960. R_SUBFLAGPARITY:
  961. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  962. R_SUBFLAGAUXILIARY:
  963. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  964. R_SUBFLAGZERO:
  965. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  966. R_SUBFLAGSIGN:
  967. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  968. R_SUBFLAGOVERFLOW:
  969. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  970. R_SUBFLAGINTERRUPT:
  971. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  972. R_SUBFLAGDIRECTION:
  973. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  974. else
  975. internalerror(2017042602);
  976. end;
  977. exit;
  978. end;
  979. case taicpu(p1).opcode of
  980. A_CALL:
  981. { We could potentially set Result to False if the register in
  982. question is non-volatile for the subroutine's calling convention,
  983. but this would require detecting the calling convention in use and
  984. also assuming that the routine doesn't contain malformed assembly
  985. language, for example... so it could only be done under -O4 as it
  986. would be considered a side-effect. [Kit] }
  987. Result := True;
  988. A_MOVSD:
  989. { special handling for SSE MOVSD }
  990. if (taicpu(p1).ops>0) then
  991. begin
  992. if taicpu(p1).ops<>2 then
  993. internalerror(2017042703);
  994. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  995. end;
  996. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  997. so fix it here (FK)
  998. }
  999. A_VMOVSS,
  1000. A_VMOVSD:
  1001. begin
  1002. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1003. exit;
  1004. end;
  1005. A_IMUL:
  1006. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1007. else
  1008. ;
  1009. end;
  1010. if Result then
  1011. exit;
  1012. with insprop[taicpu(p1).opcode] do
  1013. begin
  1014. if getregtype(reg)=R_INTREGISTER then
  1015. begin
  1016. case getsupreg(reg) of
  1017. RS_EAX:
  1018. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1019. begin
  1020. Result := True;
  1021. exit
  1022. end;
  1023. RS_ECX:
  1024. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1025. begin
  1026. Result := True;
  1027. exit
  1028. end;
  1029. RS_EDX:
  1030. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1031. begin
  1032. Result := True;
  1033. exit
  1034. end;
  1035. RS_EBX:
  1036. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1037. begin
  1038. Result := True;
  1039. exit
  1040. end;
  1041. RS_ESP:
  1042. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1043. begin
  1044. Result := True;
  1045. exit
  1046. end;
  1047. RS_EBP:
  1048. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1049. begin
  1050. Result := True;
  1051. exit
  1052. end;
  1053. RS_ESI:
  1054. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1055. begin
  1056. Result := True;
  1057. exit
  1058. end;
  1059. RS_EDI:
  1060. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1061. begin
  1062. Result := True;
  1063. exit
  1064. end;
  1065. end;
  1066. end;
  1067. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1068. if (WriteOps[OperIdx]*Ch<>[]) and
  1069. { The register doesn't get modified inside a reference }
  1070. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1071. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1072. begin
  1073. Result := true;
  1074. exit
  1075. end;
  1076. end;
  1077. end;
  1078. {$ifdef DEBUG_AOPTCPU}
  1079. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1080. begin
  1081. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1082. end;
  1083. function debug_tostr(i: tcgint): string; inline;
  1084. begin
  1085. Result := tostr(i);
  1086. end;
  1087. function debug_hexstr(i: tcgint): string;
  1088. begin
  1089. Result := '0x';
  1090. case i of
  1091. 0..$FF:
  1092. Result := Result + hexstr(i, 2);
  1093. $100..$FFFF:
  1094. Result := Result + hexstr(i, 4);
  1095. $10000..$FFFFFF:
  1096. Result := Result + hexstr(i, 6);
  1097. $1000000..$FFFFFFFF:
  1098. Result := Result + hexstr(i, 8);
  1099. else
  1100. Result := Result + hexstr(i, 16);
  1101. end;
  1102. end;
  1103. function debug_regname(r: TRegister): string; inline;
  1104. begin
  1105. Result := '%' + std_regname(r);
  1106. end;
  1107. { Debug output function - creates a string representation of an operator }
  1108. function debug_operstr(oper: TOper): string;
  1109. begin
  1110. case oper.typ of
  1111. top_const:
  1112. Result := '$' + debug_tostr(oper.val);
  1113. top_reg:
  1114. Result := debug_regname(oper.reg);
  1115. top_ref:
  1116. begin
  1117. if oper.ref^.offset <> 0 then
  1118. Result := debug_tostr(oper.ref^.offset) + '('
  1119. else
  1120. Result := '(';
  1121. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1122. begin
  1123. Result := Result + debug_regname(oper.ref^.base);
  1124. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1125. Result := Result + ',' + debug_regname(oper.ref^.index);
  1126. end
  1127. else
  1128. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1129. Result := Result + debug_regname(oper.ref^.index);
  1130. if (oper.ref^.scalefactor > 1) then
  1131. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1132. else
  1133. Result := Result + ')';
  1134. end;
  1135. else
  1136. Result := '[UNKNOWN]';
  1137. end;
  1138. end;
  1139. function debug_op2str(opcode: tasmop): string; inline;
  1140. begin
  1141. Result := std_op2str[opcode];
  1142. end;
  1143. function debug_opsize2str(opsize: topsize): string; inline;
  1144. begin
  1145. Result := gas_opsize2str[opsize];
  1146. end;
  1147. {$else DEBUG_AOPTCPU}
  1148. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1149. begin
  1150. end;
  1151. function debug_tostr(i: tcgint): string; inline;
  1152. begin
  1153. Result := '';
  1154. end;
  1155. function debug_hexstr(i: tcgint): string; inline;
  1156. begin
  1157. Result := '';
  1158. end;
  1159. function debug_regname(r: TRegister): string; inline;
  1160. begin
  1161. Result := '';
  1162. end;
  1163. function debug_operstr(oper: TOper): string; inline;
  1164. begin
  1165. Result := '';
  1166. end;
  1167. function debug_op2str(opcode: tasmop): string; inline;
  1168. begin
  1169. Result := '';
  1170. end;
  1171. function debug_opsize2str(opsize: topsize): string; inline;
  1172. begin
  1173. Result := '';
  1174. end;
  1175. {$endif DEBUG_AOPTCPU}
  1176. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1177. begin
  1178. {$ifdef x86_64}
  1179. { Always fine on x86-64 }
  1180. Result := True;
  1181. {$else x86_64}
  1182. Result :=
  1183. {$ifdef i8086}
  1184. (current_settings.cputype >= cpu_386) and
  1185. {$endif i8086}
  1186. (
  1187. { Always accept if optimising for size }
  1188. (cs_opt_size in current_settings.optimizerswitches) or
  1189. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1190. (current_settings.optimizecputype >= cpu_Pentium2)
  1191. );
  1192. {$endif x86_64}
  1193. end;
  1194. { Attempts to allocate a volatile integer register for use between p and hp,
  1195. using AUsedRegs for the current register usage information. Returns NR_NO
  1196. if no free register could be found }
  1197. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1198. var
  1199. RegSet: TCPURegisterSet;
  1200. CurrentSuperReg: Integer;
  1201. CurrentReg: TRegister;
  1202. Currentp: tai;
  1203. Breakout: Boolean;
  1204. begin
  1205. Result := NR_NO;
  1206. RegSet :=
  1207. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1208. current_procinfo.saved_regs_int;
  1209. (*
  1210. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1211. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1212. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1213. *)
  1214. for CurrentSuperReg in RegSet do
  1215. begin
  1216. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1217. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1218. {$if defined(i386) or defined(i8086)}
  1219. { If the target size is 8-bit, make sure we can actually encode it }
  1220. and (
  1221. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1222. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1223. )
  1224. {$endif i386 or i8086}
  1225. then
  1226. begin
  1227. Currentp := p;
  1228. Breakout := False;
  1229. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1230. begin
  1231. case Currentp.typ of
  1232. ait_instruction:
  1233. begin
  1234. if RegInInstruction(CurrentReg, Currentp) then
  1235. begin
  1236. Breakout := True;
  1237. Break;
  1238. end;
  1239. { Cannot allocate across an unconditional jump }
  1240. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1241. Exit;
  1242. end;
  1243. ait_marker:
  1244. { Don't try anything more if a marker is hit }
  1245. Exit;
  1246. ait_regalloc:
  1247. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1248. begin
  1249. Breakout := True;
  1250. Break;
  1251. end;
  1252. else
  1253. ;
  1254. end;
  1255. end;
  1256. if Breakout then
  1257. { Try the next register }
  1258. Continue;
  1259. { We have a free register available }
  1260. Result := CurrentReg;
  1261. if not DontAlloc then
  1262. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1263. Exit;
  1264. end;
  1265. end;
  1266. end;
  1267. { Attempts to allocate a volatile MM register for use between p and hp,
  1268. using AUsedRegs for the current register usage information. Returns NR_NO
  1269. if no free register could be found }
  1270. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1271. var
  1272. RegSet: TCPURegisterSet;
  1273. CurrentSuperReg: Integer;
  1274. CurrentReg: TRegister;
  1275. Currentp: tai;
  1276. Breakout: Boolean;
  1277. begin
  1278. Result := NR_NO;
  1279. RegSet :=
  1280. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1281. current_procinfo.saved_regs_mm;
  1282. for CurrentSuperReg in RegSet do
  1283. begin
  1284. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1285. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1286. begin
  1287. Currentp := p;
  1288. Breakout := False;
  1289. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1290. begin
  1291. case Currentp.typ of
  1292. ait_instruction:
  1293. begin
  1294. if RegInInstruction(CurrentReg, Currentp) then
  1295. begin
  1296. Breakout := True;
  1297. Break;
  1298. end;
  1299. { Cannot allocate across an unconditional jump }
  1300. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1301. Exit;
  1302. end;
  1303. ait_marker:
  1304. { Don't try anything more if a marker is hit }
  1305. Exit;
  1306. ait_regalloc:
  1307. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1308. begin
  1309. Breakout := True;
  1310. Break;
  1311. end;
  1312. else
  1313. ;
  1314. end;
  1315. end;
  1316. if Breakout then
  1317. { Try the next register }
  1318. Continue;
  1319. { We have a free register available }
  1320. Result := CurrentReg;
  1321. if not DontAlloc then
  1322. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1323. Exit;
  1324. end;
  1325. end;
  1326. end;
  1327. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1328. begin
  1329. if not SuperRegistersEqual(reg1,reg2) then
  1330. exit(false);
  1331. if getregtype(reg1)<>R_INTREGISTER then
  1332. exit(true); {because SuperRegisterEqual is true}
  1333. case getsubreg(reg1) of
  1334. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1335. higher, it preserves the high bits, so the new value depends on
  1336. reg2's previous value. In other words, it is equivalent to doing:
  1337. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1338. R_SUBL:
  1339. exit(getsubreg(reg2)=R_SUBL);
  1340. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1341. higher, it actually does a:
  1342. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1343. R_SUBH:
  1344. exit(getsubreg(reg2)=R_SUBH);
  1345. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1346. bits of reg2:
  1347. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1348. R_SUBW:
  1349. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1350. { a write to R_SUBD always overwrites every other subregister,
  1351. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1352. R_SUBD,
  1353. R_SUBQ:
  1354. exit(true);
  1355. else
  1356. internalerror(2017042801);
  1357. end;
  1358. end;
  1359. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1360. begin
  1361. if not SuperRegistersEqual(reg1,reg2) then
  1362. exit(false);
  1363. if getregtype(reg1)<>R_INTREGISTER then
  1364. exit(true); {because SuperRegisterEqual is true}
  1365. case getsubreg(reg1) of
  1366. R_SUBL:
  1367. exit(getsubreg(reg2)<>R_SUBH);
  1368. R_SUBH:
  1369. exit(getsubreg(reg2)<>R_SUBL);
  1370. R_SUBW,
  1371. R_SUBD,
  1372. R_SUBQ:
  1373. exit(true);
  1374. else
  1375. internalerror(2017042802);
  1376. end;
  1377. end;
  1378. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1379. var
  1380. hp1 : tai;
  1381. l : TCGInt;
  1382. begin
  1383. result:=false;
  1384. if not(GetNextInstruction(p, hp1)) then
  1385. exit;
  1386. { changes the code sequence
  1387. shr/sar const1, x
  1388. shl const2, x
  1389. to
  1390. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1391. if (taicpu(p).oper[0]^.typ = top_const) and
  1392. MatchInstruction(hp1,A_SHL,[]) and
  1393. (taicpu(hp1).oper[0]^.typ = top_const) and
  1394. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1395. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1396. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1397. begin
  1398. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1399. not(cs_opt_size in current_settings.optimizerswitches) then
  1400. begin
  1401. { shr/sar const1, %reg
  1402. shl const2, %reg
  1403. with const1 > const2 }
  1404. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1405. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1406. taicpu(hp1).opcode := A_AND;
  1407. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1408. case taicpu(p).opsize Of
  1409. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1410. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1411. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1412. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1413. else
  1414. Internalerror(2017050703)
  1415. end;
  1416. end
  1417. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1418. not(cs_opt_size in current_settings.optimizerswitches) then
  1419. begin
  1420. { shr/sar const1, %reg
  1421. shl const2, %reg
  1422. with const1 < const2 }
  1423. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1424. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1425. taicpu(p).opcode := A_AND;
  1426. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1427. case taicpu(p).opsize Of
  1428. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1429. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1430. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1431. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1432. else
  1433. Internalerror(2017050702)
  1434. end;
  1435. end
  1436. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1437. begin
  1438. { shr/sar const1, %reg
  1439. shl const2, %reg
  1440. with const1 = const2 }
  1441. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1442. taicpu(p).opcode := A_AND;
  1443. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1444. case taicpu(p).opsize Of
  1445. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1446. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1447. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1448. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1449. else
  1450. Internalerror(2017050701)
  1451. end;
  1452. RemoveInstruction(hp1);
  1453. end;
  1454. end;
  1455. end;
  1456. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1457. var
  1458. opsize : topsize;
  1459. hp1, hp2 : tai;
  1460. tmpref : treference;
  1461. ShiftValue : Cardinal;
  1462. BaseValue : TCGInt;
  1463. begin
  1464. result:=false;
  1465. opsize:=taicpu(p).opsize;
  1466. { changes certain "imul const, %reg"'s to lea sequences }
  1467. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1468. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1469. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1470. if (taicpu(p).oper[0]^.val = 1) then
  1471. if (taicpu(p).ops = 2) then
  1472. { remove "imul $1, reg" }
  1473. begin
  1474. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1475. Result := RemoveCurrentP(p);
  1476. end
  1477. else
  1478. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1479. begin
  1480. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1481. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1482. asml.InsertAfter(hp1, p);
  1483. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1484. RemoveCurrentP(p, hp1);
  1485. Result := True;
  1486. end
  1487. else if ((taicpu(p).ops <= 2) or
  1488. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1489. not(cs_opt_size in current_settings.optimizerswitches) and
  1490. (not(GetNextInstruction(p, hp1)) or
  1491. not((tai(hp1).typ = ait_instruction) and
  1492. ((taicpu(hp1).opcode=A_Jcc) and
  1493. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1494. begin
  1495. {
  1496. imul X, reg1, reg2 to
  1497. lea (reg1,reg1,Y), reg2
  1498. shl ZZ,reg2
  1499. imul XX, reg1 to
  1500. lea (reg1,reg1,YY), reg1
  1501. shl ZZ,reg2
  1502. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1503. it does not exist as a separate optimization target in FPC though.
  1504. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1505. at most two zeros
  1506. }
  1507. reference_reset(tmpref,1,[]);
  1508. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1509. begin
  1510. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1511. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1512. TmpRef.base := taicpu(p).oper[1]^.reg;
  1513. TmpRef.index := taicpu(p).oper[1]^.reg;
  1514. if not(BaseValue in [3,5,9]) then
  1515. Internalerror(2018110101);
  1516. TmpRef.ScaleFactor := BaseValue-1;
  1517. if (taicpu(p).ops = 2) then
  1518. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1519. else
  1520. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1521. AsmL.InsertAfter(hp1,p);
  1522. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1523. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1524. RemoveCurrentP(p, hp1);
  1525. if ShiftValue>0 then
  1526. begin
  1527. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1528. AsmL.InsertAfter(hp2,hp1);
  1529. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1530. end;
  1531. Result := True;
  1532. end;
  1533. end;
  1534. end;
  1535. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1536. begin
  1537. Result := False;
  1538. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1539. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1540. begin
  1541. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1542. taicpu(p).opcode := A_MOV;
  1543. Result := True;
  1544. end;
  1545. end;
  1546. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1547. var
  1548. p: taicpu absolute hp; { Implicit typecast }
  1549. i: Integer;
  1550. begin
  1551. Result := False;
  1552. if not assigned(hp) or
  1553. (hp.typ <> ait_instruction) then
  1554. Exit;
  1555. Prefetch(insprop[p.opcode]);
  1556. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1557. with insprop[p.opcode] do
  1558. begin
  1559. case getsubreg(reg) of
  1560. R_SUBW,R_SUBD,R_SUBQ:
  1561. Result:=
  1562. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1563. uncommon flags are checked first }
  1564. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1565. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1566. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1567. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1568. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1569. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1570. R_SUBFLAGCARRY:
  1571. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1572. R_SUBFLAGPARITY:
  1573. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1574. R_SUBFLAGAUXILIARY:
  1575. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1576. R_SUBFLAGZERO:
  1577. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1578. R_SUBFLAGSIGN:
  1579. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1580. R_SUBFLAGOVERFLOW:
  1581. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1582. R_SUBFLAGINTERRUPT:
  1583. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1584. R_SUBFLAGDIRECTION:
  1585. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1586. else
  1587. internalerror(2017050501);
  1588. end;
  1589. exit;
  1590. end;
  1591. { Handle special cases first }
  1592. case p.opcode of
  1593. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1594. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1595. begin
  1596. Result :=
  1597. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1598. (p.oper[1]^.typ = top_reg) and
  1599. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1600. (
  1601. (p.oper[0]^.typ = top_const) or
  1602. (
  1603. (p.oper[0]^.typ = top_reg) and
  1604. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1605. ) or (
  1606. (p.oper[0]^.typ = top_ref) and
  1607. not RegInRef(reg,p.oper[0]^.ref^)
  1608. )
  1609. );
  1610. end;
  1611. A_MUL, A_IMUL:
  1612. Result :=
  1613. (
  1614. (p.ops=3) and { IMUL only }
  1615. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1616. (
  1617. (
  1618. (p.oper[1]^.typ=top_reg) and
  1619. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1620. ) or (
  1621. (p.oper[1]^.typ=top_ref) and
  1622. not RegInRef(reg,p.oper[1]^.ref^)
  1623. )
  1624. )
  1625. ) or (
  1626. (
  1627. (p.ops=1) and
  1628. (
  1629. (
  1630. (
  1631. (p.oper[0]^.typ=top_reg) and
  1632. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1633. )
  1634. ) or (
  1635. (p.oper[0]^.typ=top_ref) and
  1636. not RegInRef(reg,p.oper[0]^.ref^)
  1637. )
  1638. ) and (
  1639. (
  1640. (p.opsize=S_B) and
  1641. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1642. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1643. ) or (
  1644. (p.opsize=S_W) and
  1645. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1646. ) or (
  1647. (p.opsize=S_L) and
  1648. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1649. {$ifdef x86_64}
  1650. ) or (
  1651. (p.opsize=S_Q) and
  1652. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1653. {$endif x86_64}
  1654. )
  1655. )
  1656. )
  1657. );
  1658. A_CBW:
  1659. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1660. {$ifndef x86_64}
  1661. A_LDS:
  1662. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1663. A_LES:
  1664. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1665. {$endif not x86_64}
  1666. A_LFS:
  1667. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1668. A_LGS:
  1669. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1670. A_LSS:
  1671. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1672. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1673. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1674. A_LODSB:
  1675. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1676. A_LODSW:
  1677. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1678. {$ifdef x86_64}
  1679. A_LODSQ:
  1680. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1681. {$endif x86_64}
  1682. A_LODSD:
  1683. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1684. A_FSTSW, A_FNSTSW:
  1685. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1686. else
  1687. begin
  1688. with insprop[p.opcode] do
  1689. begin
  1690. if (
  1691. { xor %reg,%reg etc. is classed as a new value }
  1692. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1693. MatchOpType(p, top_reg, top_reg) and
  1694. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1695. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1696. ) then
  1697. begin
  1698. Result := True;
  1699. Exit;
  1700. end;
  1701. { Make sure the entire register is overwritten }
  1702. if (getregtype(reg) = R_INTREGISTER) then
  1703. begin
  1704. if (p.ops > 0) then
  1705. begin
  1706. if RegInOp(reg, p.oper[0]^) then
  1707. begin
  1708. if (p.oper[0]^.typ = top_ref) then
  1709. begin
  1710. if RegInRef(reg, p.oper[0]^.ref^) then
  1711. begin
  1712. Result := False;
  1713. Exit;
  1714. end;
  1715. end
  1716. else if (p.oper[0]^.typ = top_reg) then
  1717. begin
  1718. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1719. begin
  1720. Result := False;
  1721. Exit;
  1722. end
  1723. else if ([Ch_WOp1]*Ch<>[]) then
  1724. begin
  1725. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1726. Result := True
  1727. else
  1728. begin
  1729. Result := False;
  1730. Exit;
  1731. end;
  1732. end;
  1733. end;
  1734. end;
  1735. if (p.ops > 1) then
  1736. begin
  1737. if RegInOp(reg, p.oper[1]^) then
  1738. begin
  1739. if (p.oper[1]^.typ = top_ref) then
  1740. begin
  1741. if RegInRef(reg, p.oper[1]^.ref^) then
  1742. begin
  1743. Result := False;
  1744. Exit;
  1745. end;
  1746. end
  1747. else if (p.oper[1]^.typ = top_reg) then
  1748. begin
  1749. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1750. begin
  1751. Result := False;
  1752. Exit;
  1753. end
  1754. else if ([Ch_WOp2]*Ch<>[]) then
  1755. begin
  1756. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1757. Result := True
  1758. else
  1759. begin
  1760. Result := False;
  1761. Exit;
  1762. end;
  1763. end;
  1764. end;
  1765. end;
  1766. if (p.ops > 2) then
  1767. begin
  1768. if RegInOp(reg, p.oper[2]^) then
  1769. begin
  1770. if (p.oper[2]^.typ = top_ref) then
  1771. begin
  1772. if RegInRef(reg, p.oper[2]^.ref^) then
  1773. begin
  1774. Result := False;
  1775. Exit;
  1776. end;
  1777. end
  1778. else if (p.oper[2]^.typ = top_reg) then
  1779. begin
  1780. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1781. begin
  1782. Result := False;
  1783. Exit;
  1784. end
  1785. else if ([Ch_WOp3]*Ch<>[]) then
  1786. begin
  1787. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1788. Result := True
  1789. else
  1790. begin
  1791. Result := False;
  1792. Exit;
  1793. end;
  1794. end;
  1795. end;
  1796. end;
  1797. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1798. begin
  1799. if (p.oper[3]^.typ = top_ref) then
  1800. begin
  1801. if RegInRef(reg, p.oper[3]^.ref^) then
  1802. begin
  1803. Result := False;
  1804. Exit;
  1805. end;
  1806. end
  1807. else if (p.oper[3]^.typ = top_reg) then
  1808. begin
  1809. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1810. begin
  1811. Result := False;
  1812. Exit;
  1813. end
  1814. else if ([Ch_WOp4]*Ch<>[]) then
  1815. begin
  1816. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1817. Result := True
  1818. else
  1819. begin
  1820. Result := False;
  1821. Exit;
  1822. end;
  1823. end;
  1824. end;
  1825. end;
  1826. end;
  1827. end;
  1828. end;
  1829. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1830. case getsupreg(reg) of
  1831. RS_EAX:
  1832. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1833. begin
  1834. Result := True;
  1835. Exit;
  1836. end;
  1837. RS_ECX:
  1838. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1839. begin
  1840. Result := True;
  1841. Exit;
  1842. end;
  1843. RS_EDX:
  1844. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1845. begin
  1846. Result := True;
  1847. Exit;
  1848. end;
  1849. RS_EBX:
  1850. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1851. begin
  1852. Result := True;
  1853. Exit;
  1854. end;
  1855. RS_ESP:
  1856. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1857. begin
  1858. Result := True;
  1859. Exit;
  1860. end;
  1861. RS_EBP:
  1862. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1863. begin
  1864. Result := True;
  1865. Exit;
  1866. end;
  1867. RS_ESI:
  1868. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1869. begin
  1870. Result := True;
  1871. Exit;
  1872. end;
  1873. RS_EDI:
  1874. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1875. begin
  1876. Result := True;
  1877. Exit;
  1878. end;
  1879. else
  1880. ;
  1881. end;
  1882. end;
  1883. end;
  1884. end;
  1885. end;
  1886. end;
  1887. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1888. var
  1889. hp2,hp3 : tai;
  1890. begin
  1891. { some x86-64 issue a NOP before the real exit code }
  1892. if MatchInstruction(p,A_NOP,[]) then
  1893. GetNextInstruction(p,p);
  1894. result:=assigned(p) and (p.typ=ait_instruction) and
  1895. ((taicpu(p).opcode = A_RET) or
  1896. ((taicpu(p).opcode=A_LEAVE) and
  1897. GetNextInstruction(p,hp2) and
  1898. MatchInstruction(hp2,A_RET,[S_NO])
  1899. ) or
  1900. (((taicpu(p).opcode=A_LEA) and
  1901. MatchOpType(taicpu(p),top_ref,top_reg) and
  1902. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1903. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1904. ) and
  1905. GetNextInstruction(p,hp2) and
  1906. MatchInstruction(hp2,A_RET,[S_NO])
  1907. ) or
  1908. ((((taicpu(p).opcode=A_MOV) and
  1909. MatchOpType(taicpu(p),top_reg,top_reg) and
  1910. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1911. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1912. ((taicpu(p).opcode=A_LEA) and
  1913. MatchOpType(taicpu(p),top_ref,top_reg) and
  1914. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1915. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1916. )
  1917. ) and
  1918. GetNextInstruction(p,hp2) and
  1919. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1920. MatchOpType(taicpu(hp2),top_reg) and
  1921. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1922. GetNextInstruction(hp2,hp3) and
  1923. MatchInstruction(hp3,A_RET,[S_NO])
  1924. )
  1925. );
  1926. end;
  1927. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1928. begin
  1929. isFoldableArithOp := False;
  1930. case hp1.opcode of
  1931. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1932. isFoldableArithOp :=
  1933. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1934. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1935. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1936. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1937. (taicpu(hp1).oper[1]^.reg = reg);
  1938. A_INC,A_DEC,A_NEG,A_NOT:
  1939. isFoldableArithOp :=
  1940. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1941. (taicpu(hp1).oper[0]^.reg = reg);
  1942. else
  1943. ;
  1944. end;
  1945. end;
  1946. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1947. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1948. var
  1949. hp2: tai;
  1950. begin
  1951. hp2 := p;
  1952. repeat
  1953. hp2 := tai(hp2.previous);
  1954. if assigned(hp2) and
  1955. (hp2.typ = ait_regalloc) and
  1956. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1957. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1958. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1959. begin
  1960. RemoveInstruction(hp2);
  1961. break;
  1962. end;
  1963. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1964. end;
  1965. begin
  1966. case current_procinfo.procdef.returndef.typ of
  1967. arraydef,recorddef,pointerdef,
  1968. stringdef,enumdef,procdef,objectdef,errordef,
  1969. filedef,setdef,procvardef,
  1970. classrefdef,forwarddef:
  1971. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1972. orddef:
  1973. if current_procinfo.procdef.returndef.size <> 0 then
  1974. begin
  1975. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1976. { for int64/qword }
  1977. if current_procinfo.procdef.returndef.size = 8 then
  1978. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1979. end;
  1980. else
  1981. ;
  1982. end;
  1983. end;
  1984. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1985. var
  1986. hp1,hp2 : tai;
  1987. begin
  1988. result:=false;
  1989. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1990. begin
  1991. { vmova* reg1,reg1
  1992. =>
  1993. <nop> }
  1994. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  1995. begin
  1996. RemoveCurrentP(p);
  1997. result:=true;
  1998. exit;
  1999. end;
  2000. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2001. begin
  2002. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2003. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2004. begin
  2005. { vmova* reg1,reg2
  2006. vmova* reg2,reg3
  2007. dealloc reg2
  2008. =>
  2009. vmova* reg1,reg3 }
  2010. TransferUsedRegs(TmpUsedRegs);
  2011. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2012. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2013. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2014. begin
  2015. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2016. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2017. RemoveInstruction(hp1);
  2018. result:=true;
  2019. exit;
  2020. end;
  2021. { special case:
  2022. vmova* reg1,<op>
  2023. vmova* <op>,reg1
  2024. =>
  2025. vmova* reg1,<op> }
  2026. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2027. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2028. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2029. ) then
  2030. begin
  2031. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2032. RemoveInstruction(hp1);
  2033. result:=true;
  2034. exit;
  2035. end
  2036. end
  2037. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2038. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2039. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2040. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2041. ) and
  2042. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2043. begin
  2044. { vmova* reg1,reg2
  2045. vmovs* reg2,<op>
  2046. dealloc reg2
  2047. =>
  2048. vmovs* reg1,reg3 }
  2049. TransferUsedRegs(TmpUsedRegs);
  2050. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2051. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2052. begin
  2053. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2054. taicpu(p).opcode:=taicpu(hp1).opcode;
  2055. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2056. RemoveInstruction(hp1);
  2057. result:=true;
  2058. exit;
  2059. end
  2060. end;
  2061. end;
  2062. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2063. begin
  2064. if MatchInstruction(hp1,[A_VFMADDPD,
  2065. A_VFMADD132PD,
  2066. A_VFMADD132PS,
  2067. A_VFMADD132SD,
  2068. A_VFMADD132SS,
  2069. A_VFMADD213PD,
  2070. A_VFMADD213PS,
  2071. A_VFMADD213SD,
  2072. A_VFMADD213SS,
  2073. A_VFMADD231PD,
  2074. A_VFMADD231PS,
  2075. A_VFMADD231SD,
  2076. A_VFMADD231SS,
  2077. A_VFMADDSUB132PD,
  2078. A_VFMADDSUB132PS,
  2079. A_VFMADDSUB213PD,
  2080. A_VFMADDSUB213PS,
  2081. A_VFMADDSUB231PD,
  2082. A_VFMADDSUB231PS,
  2083. A_VFMSUB132PD,
  2084. A_VFMSUB132PS,
  2085. A_VFMSUB132SD,
  2086. A_VFMSUB132SS,
  2087. A_VFMSUB213PD,
  2088. A_VFMSUB213PS,
  2089. A_VFMSUB213SD,
  2090. A_VFMSUB213SS,
  2091. A_VFMSUB231PD,
  2092. A_VFMSUB231PS,
  2093. A_VFMSUB231SD,
  2094. A_VFMSUB231SS,
  2095. A_VFMSUBADD132PD,
  2096. A_VFMSUBADD132PS,
  2097. A_VFMSUBADD213PD,
  2098. A_VFMSUBADD213PS,
  2099. A_VFMSUBADD231PD,
  2100. A_VFMSUBADD231PS,
  2101. A_VFNMADD132PD,
  2102. A_VFNMADD132PS,
  2103. A_VFNMADD132SD,
  2104. A_VFNMADD132SS,
  2105. A_VFNMADD213PD,
  2106. A_VFNMADD213PS,
  2107. A_VFNMADD213SD,
  2108. A_VFNMADD213SS,
  2109. A_VFNMADD231PD,
  2110. A_VFNMADD231PS,
  2111. A_VFNMADD231SD,
  2112. A_VFNMADD231SS,
  2113. A_VFNMSUB132PD,
  2114. A_VFNMSUB132PS,
  2115. A_VFNMSUB132SD,
  2116. A_VFNMSUB132SS,
  2117. A_VFNMSUB213PD,
  2118. A_VFNMSUB213PS,
  2119. A_VFNMSUB213SD,
  2120. A_VFNMSUB213SS,
  2121. A_VFNMSUB231PD,
  2122. A_VFNMSUB231PS,
  2123. A_VFNMSUB231SD,
  2124. A_VFNMSUB231SS],[S_NO]) and
  2125. { we mix single and double opperations here because we assume that the compiler
  2126. generates vmovapd only after double operations and vmovaps only after single operations }
  2127. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2128. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2129. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2130. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2131. begin
  2132. TransferUsedRegs(TmpUsedRegs);
  2133. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2134. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2135. begin
  2136. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2137. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2138. RemoveCurrentP(p)
  2139. else
  2140. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2141. RemoveInstruction(hp2);
  2142. end;
  2143. end
  2144. else if (hp1.typ = ait_instruction) and
  2145. (((taicpu(p).opcode=A_MOVAPS) and
  2146. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2147. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2148. ((taicpu(p).opcode=A_MOVAPD) and
  2149. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2150. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2151. ) and
  2152. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2153. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2154. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2155. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2156. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2157. { change
  2158. movapX reg,reg2
  2159. addsX/subsX/... reg3, reg2
  2160. movapX reg2,reg
  2161. to
  2162. addsX/subsX/... reg3,reg
  2163. }
  2164. begin
  2165. TransferUsedRegs(TmpUsedRegs);
  2166. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2167. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2168. begin
  2169. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2170. debug_op2str(taicpu(p).opcode)+' '+
  2171. debug_op2str(taicpu(hp1).opcode)+' '+
  2172. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2173. { we cannot eliminate the first move if
  2174. the operations uses the same register for source and dest }
  2175. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2176. { Remember that hp1 is not necessarily the immediate
  2177. next instruction }
  2178. RemoveCurrentP(p);
  2179. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2180. RemoveInstruction(hp2);
  2181. result:=true;
  2182. end;
  2183. end
  2184. else if (hp1.typ = ait_instruction) and
  2185. (((taicpu(p).opcode=A_VMOVAPD) and
  2186. (taicpu(hp1).opcode=A_VCOMISD)) or
  2187. ((taicpu(p).opcode=A_VMOVAPS) and
  2188. ((taicpu(hp1).opcode=A_VCOMISS))
  2189. )
  2190. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2191. { change
  2192. movapX reg,reg1
  2193. vcomisX reg1,reg1
  2194. to
  2195. vcomisX reg,reg
  2196. }
  2197. begin
  2198. TransferUsedRegs(TmpUsedRegs);
  2199. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2200. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2201. begin
  2202. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2203. debug_op2str(taicpu(p).opcode)+' '+
  2204. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2205. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2206. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2207. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2208. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2209. RemoveCurrentP(p);
  2210. result:=true;
  2211. exit;
  2212. end;
  2213. end
  2214. end;
  2215. end;
  2216. end;
  2217. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2218. var
  2219. hp1 : tai;
  2220. begin
  2221. result:=false;
  2222. { replace
  2223. V<Op>X %mreg1,%mreg2,%mreg3
  2224. VMovX %mreg3,%mreg4
  2225. dealloc %mreg3
  2226. by
  2227. V<Op>X %mreg1,%mreg2,%mreg4
  2228. ?
  2229. }
  2230. if GetNextInstruction(p,hp1) and
  2231. { we mix single and double operations here because we assume that the compiler
  2232. generates vmovapd only after double operations and vmovaps only after single operations }
  2233. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2234. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2235. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2236. begin
  2237. TransferUsedRegs(TmpUsedRegs);
  2238. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2239. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2240. begin
  2241. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2242. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2243. RemoveInstruction(hp1);
  2244. result:=true;
  2245. end;
  2246. end;
  2247. end;
  2248. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2249. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2250. begin
  2251. Result := False;
  2252. { For safety reasons, only check for exact register matches }
  2253. { Check base register }
  2254. if (ref.base = AOldReg) then
  2255. begin
  2256. ref.base := ANewReg;
  2257. Result := True;
  2258. end;
  2259. { Check index register }
  2260. if (ref.index = AOldReg) then
  2261. begin
  2262. ref.index := ANewReg;
  2263. Result := True;
  2264. end;
  2265. end;
  2266. { Replaces all references to AOldReg in an operand to ANewReg }
  2267. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2268. var
  2269. OldSupReg, NewSupReg: TSuperRegister;
  2270. OldSubReg, NewSubReg: TSubRegister;
  2271. OldRegType: TRegisterType;
  2272. ThisOper: POper;
  2273. begin
  2274. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2275. Result := False;
  2276. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2277. InternalError(2020011801);
  2278. OldSupReg := getsupreg(AOldReg);
  2279. OldSubReg := getsubreg(AOldReg);
  2280. OldRegType := getregtype(AOldReg);
  2281. NewSupReg := getsupreg(ANewReg);
  2282. NewSubReg := getsubreg(ANewReg);
  2283. if OldRegType <> getregtype(ANewReg) then
  2284. InternalError(2020011802);
  2285. if OldSubReg <> NewSubReg then
  2286. InternalError(2020011803);
  2287. case ThisOper^.typ of
  2288. top_reg:
  2289. if (
  2290. (ThisOper^.reg = AOldReg) or
  2291. (
  2292. (OldRegType = R_INTREGISTER) and
  2293. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2294. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2295. (
  2296. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2297. {$ifndef x86_64}
  2298. and (
  2299. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2300. don't have an 8-bit representation }
  2301. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2302. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2303. )
  2304. {$endif x86_64}
  2305. )
  2306. )
  2307. ) then
  2308. begin
  2309. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2310. Result := True;
  2311. end;
  2312. top_ref:
  2313. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2314. Result := True;
  2315. else
  2316. ;
  2317. end;
  2318. end;
  2319. { Replaces all references to AOldReg in an instruction to ANewReg }
  2320. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2321. const
  2322. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2323. var
  2324. OperIdx: Integer;
  2325. begin
  2326. Result := False;
  2327. for OperIdx := 0 to p.ops - 1 do
  2328. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2329. begin
  2330. { The shift and rotate instructions can only use CL }
  2331. if not (
  2332. (OperIdx = 0) and
  2333. { This second condition just helps to avoid unnecessarily
  2334. calling MatchInstruction for 10 different opcodes }
  2335. (p.oper[0]^.reg = NR_CL) and
  2336. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2337. ) then
  2338. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2339. end
  2340. else if p.oper[OperIdx]^.typ = top_ref then
  2341. { It's okay to replace registers in references that get written to }
  2342. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2343. end;
  2344. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2345. begin
  2346. Result :=
  2347. (ref^.index = NR_NO) and
  2348. (
  2349. {$ifdef x86_64}
  2350. (
  2351. (ref^.base = NR_RIP) and
  2352. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2353. ) or
  2354. {$endif x86_64}
  2355. (ref^.refaddr = addr_full) or
  2356. (ref^.base = NR_STACK_POINTER_REG) or
  2357. (ref^.base = current_procinfo.framepointer)
  2358. );
  2359. end;
  2360. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2361. var
  2362. l: asizeint;
  2363. begin
  2364. Result := False;
  2365. { Should have been checked previously }
  2366. if p.opcode <> A_LEA then
  2367. InternalError(2020072501);
  2368. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2369. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2370. not(cs_opt_size in current_settings.optimizerswitches) then
  2371. exit;
  2372. with p.oper[0]^.ref^ do
  2373. begin
  2374. if (base <> p.oper[1]^.reg) or
  2375. (index <> NR_NO) or
  2376. assigned(symbol) then
  2377. exit;
  2378. l:=offset;
  2379. if (l=1) and UseIncDec then
  2380. begin
  2381. p.opcode:=A_INC;
  2382. p.loadreg(0,p.oper[1]^.reg);
  2383. p.ops:=1;
  2384. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2385. end
  2386. else if (l=-1) and UseIncDec then
  2387. begin
  2388. p.opcode:=A_DEC;
  2389. p.loadreg(0,p.oper[1]^.reg);
  2390. p.ops:=1;
  2391. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2392. end
  2393. else
  2394. begin
  2395. if (l<0) and (l<>-2147483648) then
  2396. begin
  2397. p.opcode:=A_SUB;
  2398. p.loadConst(0,-l);
  2399. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2400. end
  2401. else
  2402. begin
  2403. p.opcode:=A_ADD;
  2404. p.loadConst(0,l);
  2405. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2406. end;
  2407. end;
  2408. end;
  2409. Result := True;
  2410. end;
  2411. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2412. var
  2413. CurrentReg, ReplaceReg: TRegister;
  2414. begin
  2415. Result := False;
  2416. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2417. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2418. case hp.opcode of
  2419. A_FSTSW, A_FNSTSW,
  2420. A_IN, A_INS, A_OUT, A_OUTS,
  2421. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2422. { These routines have explicit operands, but they are restricted in
  2423. what they can be (e.g. IN and OUT can only read from AL, AX or
  2424. EAX. }
  2425. Exit;
  2426. A_IMUL:
  2427. begin
  2428. { The 1-operand version writes to implicit registers
  2429. The 2-operand version reads from the first operator, and reads
  2430. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2431. the 3-operand version reads from a register that it doesn't write to
  2432. }
  2433. case hp.ops of
  2434. 1:
  2435. if (
  2436. (
  2437. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2438. ) or
  2439. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2440. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2441. begin
  2442. Result := True;
  2443. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2444. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2445. end;
  2446. 2:
  2447. { Only modify the first parameter }
  2448. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2449. begin
  2450. Result := True;
  2451. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2452. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2453. end;
  2454. 3:
  2455. { Only modify the second parameter }
  2456. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2457. begin
  2458. Result := True;
  2459. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2460. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2461. end;
  2462. else
  2463. InternalError(2020012901);
  2464. end;
  2465. end;
  2466. else
  2467. if (hp.ops > 0) and
  2468. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2469. begin
  2470. Result := True;
  2471. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2472. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2473. end;
  2474. end;
  2475. end;
  2476. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2477. var
  2478. hp2: tai;
  2479. p_SourceReg, p_TargetReg: TRegister;
  2480. begin
  2481. Result := False;
  2482. { Backward optimisation. If we have:
  2483. func. %reg1,%reg2
  2484. mov %reg2,%reg3
  2485. (dealloc %reg2)
  2486. Change to:
  2487. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2488. Perform similar optimisations with 1, 3 and 4-operand instructions
  2489. that only have one output.
  2490. }
  2491. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2492. begin
  2493. p_SourceReg := taicpu(p).oper[0]^.reg;
  2494. p_TargetReg := taicpu(p).oper[1]^.reg;
  2495. TransferUsedRegs(TmpUsedRegs);
  2496. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2497. GetLastInstruction(p, hp2) and
  2498. (hp2.typ = ait_instruction) and
  2499. { Have to make sure it's an instruction that only reads from
  2500. the first operands and only writes (not reads or modifies) to
  2501. the last one; in essence, a pure function such as BSR, POPCNT
  2502. or ANDN }
  2503. (
  2504. (
  2505. (taicpu(hp2).ops = 1) and
  2506. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2507. ) or
  2508. (
  2509. (taicpu(hp2).ops = 2) and
  2510. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2511. ) or
  2512. (
  2513. (taicpu(hp2).ops = 3) and
  2514. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2515. ) or
  2516. (
  2517. (taicpu(hp2).ops = 4) and
  2518. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2519. )
  2520. ) and
  2521. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2522. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2523. begin
  2524. case taicpu(hp2).opcode of
  2525. A_FSTSW, A_FNSTSW,
  2526. A_IN, A_INS, A_OUT, A_OUTS,
  2527. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2528. { These routines have explicit operands, but they are restricted in
  2529. what they can be (e.g. IN and OUT can only read from AL, AX or
  2530. EAX. }
  2531. ;
  2532. else
  2533. begin
  2534. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2535. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2536. if not RegInInstruction(p_TargetReg, hp2) then
  2537. begin
  2538. { Since we're allocating from an earlier point, we
  2539. need to remove the register from the tracking }
  2540. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2541. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2542. end;
  2543. RemoveCurrentp(p, hp1);
  2544. { If the Func was another MOV instruction, we might get
  2545. "mov %reg,%reg" that doesn't get removed in Pass 2
  2546. otherwise, so deal with it here (also do something
  2547. similar with lea (%reg),%reg}
  2548. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2549. begin
  2550. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2551. if p = hp2 then
  2552. RemoveCurrentp(p)
  2553. else
  2554. RemoveInstruction(hp2);
  2555. end;
  2556. Result := True;
  2557. Exit;
  2558. end;
  2559. end;
  2560. end;
  2561. end;
  2562. end;
  2563. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2564. var
  2565. hp1, hp2, hp3: tai;
  2566. DoOptimisation, TempBool: Boolean;
  2567. {$ifdef x86_64}
  2568. NewConst: TCGInt;
  2569. {$endif x86_64}
  2570. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2571. begin
  2572. if taicpu(hp1).opcode = signed_movop then
  2573. begin
  2574. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2575. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2576. end
  2577. else
  2578. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2579. end;
  2580. function TryConstMerge(var p1, p2: tai): Boolean;
  2581. var
  2582. ThisRef: TReference;
  2583. begin
  2584. Result := False;
  2585. ThisRef := taicpu(p2).oper[1]^.ref^;
  2586. { Only permit writes to the stack, since we can guarantee alignment with that }
  2587. if (ThisRef.index = NR_NO) and
  2588. (
  2589. (ThisRef.base = NR_STACK_POINTER_REG) or
  2590. (ThisRef.base = current_procinfo.framepointer)
  2591. ) then
  2592. begin
  2593. case taicpu(p).opsize of
  2594. S_B:
  2595. begin
  2596. { Word writes must be on a 2-byte boundary }
  2597. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2598. begin
  2599. { Reduce offset of second reference to see if it is sequential with the first }
  2600. Dec(ThisRef.offset, 1);
  2601. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2602. begin
  2603. { Make sure the constants aren't represented as a
  2604. negative number, as these won't merge properly }
  2605. taicpu(p1).opsize := S_W;
  2606. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2607. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2608. RemoveInstruction(p2);
  2609. Result := True;
  2610. end;
  2611. end;
  2612. end;
  2613. S_W:
  2614. begin
  2615. { Longword writes must be on a 4-byte boundary }
  2616. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2617. begin
  2618. { Reduce offset of second reference to see if it is sequential with the first }
  2619. Dec(ThisRef.offset, 2);
  2620. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2621. begin
  2622. { Make sure the constants aren't represented as a
  2623. negative number, as these won't merge properly }
  2624. taicpu(p1).opsize := S_L;
  2625. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2626. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2627. RemoveInstruction(p2);
  2628. Result := True;
  2629. end;
  2630. end;
  2631. end;
  2632. {$ifdef x86_64}
  2633. S_L:
  2634. begin
  2635. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2636. see if the constants can be encoded this way. }
  2637. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2638. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2639. { Quadword writes must be on an 8-byte boundary }
  2640. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2641. begin
  2642. { Reduce offset of second reference to see if it is sequential with the first }
  2643. Dec(ThisRef.offset, 4);
  2644. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2645. begin
  2646. { Make sure the constants aren't represented as a
  2647. negative number, as these won't merge properly }
  2648. taicpu(p1).opsize := S_Q;
  2649. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2650. taicpu(p1).oper[0]^.val := NewConst;
  2651. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2652. RemoveInstruction(p2);
  2653. Result := True;
  2654. end;
  2655. end;
  2656. end;
  2657. {$endif x86_64}
  2658. else
  2659. ;
  2660. end;
  2661. end;
  2662. end;
  2663. var
  2664. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2665. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2666. NewSize: topsize; NewOffset: asizeint;
  2667. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2668. SourceRef, TargetRef: TReference;
  2669. MovAligned, MovUnaligned: TAsmOp;
  2670. ThisRef: TReference;
  2671. JumpTracking: TLinkedList;
  2672. begin
  2673. Result:=false;
  2674. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2675. { remove mov reg1,reg1? }
  2676. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2677. then
  2678. begin
  2679. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2680. { take care of the register (de)allocs following p }
  2681. RemoveCurrentP(p, hp1);
  2682. Result:=true;
  2683. exit;
  2684. end;
  2685. { All the next optimisations require a next instruction }
  2686. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2687. Exit;
  2688. { Prevent compiler warnings }
  2689. p_TargetReg := NR_NO;
  2690. if taicpu(p).oper[1]^.typ = top_reg then
  2691. begin
  2692. { Saves on a large number of dereferences }
  2693. p_TargetReg := taicpu(p).oper[1]^.reg;
  2694. { Look for:
  2695. mov %reg1,%reg2
  2696. ??? %reg2,r/m
  2697. Change to:
  2698. mov %reg1,%reg2
  2699. ??? %reg1,r/m
  2700. }
  2701. if taicpu(p).oper[0]^.typ = top_reg then
  2702. begin
  2703. if RegReadByInstruction(p_TargetReg, hp1) and
  2704. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2705. begin
  2706. { A change has occurred, just not in p }
  2707. Result := True;
  2708. TransferUsedRegs(TmpUsedRegs);
  2709. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2710. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2711. { Just in case something didn't get modified (e.g. an
  2712. implicit register) }
  2713. not RegReadByInstruction(p_TargetReg, hp1) then
  2714. begin
  2715. { We can remove the original MOV }
  2716. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2717. RemoveCurrentp(p, hp1);
  2718. { UsedRegs got updated by RemoveCurrentp }
  2719. Result := True;
  2720. Exit;
  2721. end;
  2722. { If we know a MOV instruction has become a null operation, we might as well
  2723. get rid of it now to save time. }
  2724. if (taicpu(hp1).opcode = A_MOV) and
  2725. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2726. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2727. { Just being a register is enough to confirm it's a null operation }
  2728. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2729. begin
  2730. Result := True;
  2731. { Speed-up to reduce a pipeline stall... if we had something like...
  2732. movl %eax,%edx
  2733. movw %dx,%ax
  2734. ... the second instruction would change to movw %ax,%ax, but
  2735. given that it is now %ax that's active rather than %eax,
  2736. penalties might occur due to a partial register write, so instead,
  2737. change it to a MOVZX instruction when optimising for speed.
  2738. }
  2739. if not (cs_opt_size in current_settings.optimizerswitches) and
  2740. IsMOVZXAcceptable and
  2741. (taicpu(hp1).opsize < taicpu(p).opsize)
  2742. {$ifdef x86_64}
  2743. { operations already implicitly set the upper 64 bits to zero }
  2744. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2745. {$endif x86_64}
  2746. then
  2747. begin
  2748. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2749. case taicpu(p).opsize of
  2750. S_W:
  2751. if taicpu(hp1).opsize = S_B then
  2752. taicpu(hp1).opsize := S_BL
  2753. else
  2754. InternalError(2020012911);
  2755. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2756. case taicpu(hp1).opsize of
  2757. S_B:
  2758. taicpu(hp1).opsize := S_BL;
  2759. S_W:
  2760. taicpu(hp1).opsize := S_WL;
  2761. else
  2762. InternalError(2020012912);
  2763. end;
  2764. else
  2765. InternalError(2020012910);
  2766. end;
  2767. taicpu(hp1).opcode := A_MOVZX;
  2768. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2769. end
  2770. else
  2771. begin
  2772. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2773. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2774. RemoveInstruction(hp1);
  2775. { The instruction after what was hp1 is now the immediate next instruction,
  2776. so we can continue to make optimisations if it's present }
  2777. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2778. Exit;
  2779. hp1 := hp2;
  2780. end;
  2781. end;
  2782. end;
  2783. end;
  2784. end;
  2785. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2786. overwrites the original destination register. e.g.
  2787. movl ###,%reg2d
  2788. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2789. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2790. }
  2791. if (taicpu(p).oper[1]^.typ = top_reg) and
  2792. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2793. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2794. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2795. begin
  2796. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2797. begin
  2798. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2799. case taicpu(p).oper[0]^.typ of
  2800. top_const:
  2801. { We have something like:
  2802. movb $x, %regb
  2803. movzbl %regb,%regd
  2804. Change to:
  2805. movl $x, %regd
  2806. }
  2807. begin
  2808. case taicpu(hp1).opsize of
  2809. S_BW:
  2810. begin
  2811. convert_mov_value(A_MOVSX, $FF);
  2812. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2813. taicpu(p).opsize := S_W;
  2814. end;
  2815. S_BL:
  2816. begin
  2817. convert_mov_value(A_MOVSX, $FF);
  2818. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2819. taicpu(p).opsize := S_L;
  2820. end;
  2821. S_WL:
  2822. begin
  2823. convert_mov_value(A_MOVSX, $FFFF);
  2824. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2825. taicpu(p).opsize := S_L;
  2826. end;
  2827. {$ifdef x86_64}
  2828. S_BQ:
  2829. begin
  2830. convert_mov_value(A_MOVSX, $FF);
  2831. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2832. taicpu(p).opsize := S_Q;
  2833. end;
  2834. S_WQ:
  2835. begin
  2836. convert_mov_value(A_MOVSX, $FFFF);
  2837. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2838. taicpu(p).opsize := S_Q;
  2839. end;
  2840. S_LQ:
  2841. begin
  2842. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2843. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2844. taicpu(p).opsize := S_Q;
  2845. end;
  2846. {$endif x86_64}
  2847. else
  2848. { If hp1 was a MOV instruction, it should have been
  2849. optimised already }
  2850. InternalError(2020021001);
  2851. end;
  2852. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2853. RemoveInstruction(hp1);
  2854. Result := True;
  2855. Exit;
  2856. end;
  2857. top_ref:
  2858. begin
  2859. { We have something like:
  2860. movb mem, %regb
  2861. movzbl %regb,%regd
  2862. Change to:
  2863. movzbl mem, %regd
  2864. }
  2865. ThisRef := taicpu(p).oper[0]^.ref^;
  2866. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2867. begin
  2868. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2869. taicpu(hp1).loadref(0, ThisRef);
  2870. { Make sure any registers in the references are properly tracked }
  2871. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2872. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2873. if (ThisRef.index <> NR_NO) then
  2874. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2875. RemoveCurrentP(p, hp1);
  2876. Result := True;
  2877. Exit;
  2878. end;
  2879. end;
  2880. else
  2881. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2882. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2883. Exit;
  2884. end;
  2885. end
  2886. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2887. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2888. optimised }
  2889. else
  2890. begin
  2891. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2892. RemoveCurrentP(p, hp1);
  2893. Result := True;
  2894. Exit;
  2895. end;
  2896. end;
  2897. if (taicpu(hp1).opcode = A_AND) and
  2898. (taicpu(p).oper[1]^.typ = top_reg) and
  2899. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2900. begin
  2901. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2902. begin
  2903. case taicpu(p).opsize of
  2904. S_L:
  2905. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2906. begin
  2907. { Optimize out:
  2908. mov x, %reg
  2909. and ffffffffh, %reg
  2910. }
  2911. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2912. RemoveInstruction(hp1);
  2913. Result:=true;
  2914. exit;
  2915. end;
  2916. S_Q: { TODO: Confirm if this is even possible }
  2917. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2918. begin
  2919. { Optimize out:
  2920. mov x, %reg
  2921. and ffffffffffffffffh, %reg
  2922. }
  2923. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2924. RemoveInstruction(hp1);
  2925. Result:=true;
  2926. exit;
  2927. end;
  2928. else
  2929. ;
  2930. end;
  2931. if (
  2932. (taicpu(p).oper[0]^.typ=top_reg) or
  2933. (
  2934. (taicpu(p).oper[0]^.typ=top_ref) and
  2935. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2936. )
  2937. ) and
  2938. GetNextInstruction(hp1,hp2) and
  2939. MatchInstruction(hp2,A_TEST,[]) and
  2940. (
  2941. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2942. (
  2943. { If the register being tested is smaller than the one
  2944. that received a bitwise AND, permit it if the constant
  2945. fits into the smaller size }
  2946. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2947. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2948. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2949. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2950. (
  2951. (
  2952. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2953. (taicpu(hp1).oper[0]^.val <= $FF)
  2954. ) or
  2955. (
  2956. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2957. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2958. {$ifdef x86_64}
  2959. ) or
  2960. (
  2961. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2962. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2963. {$endif x86_64}
  2964. )
  2965. )
  2966. )
  2967. ) and
  2968. (
  2969. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2970. MatchOperand(taicpu(hp2).oper[0]^,-1)
  2971. ) and
  2972. GetNextInstruction(hp2,hp3) and
  2973. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2974. (taicpu(hp3).condition in [C_E,C_NE]) then
  2975. begin
  2976. TransferUsedRegs(TmpUsedRegs);
  2977. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2978. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2979. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2980. begin
  2981. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2982. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2983. taicpu(hp1).opcode:=A_TEST;
  2984. { Shrink the TEST instruction down to the smallest possible size }
  2985. case taicpu(hp1).oper[0]^.val of
  2986. 0..255:
  2987. if (taicpu(hp1).opsize <> S_B)
  2988. {$ifndef x86_64}
  2989. and (
  2990. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  2991. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  2992. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  2993. )
  2994. {$endif x86_64}
  2995. then
  2996. begin
  2997. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2998. { Only print debug message if the TEST instruction
  2999. is a different size before and after }
  3000. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3001. taicpu(hp1).opsize := S_B;
  3002. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3003. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3004. end;
  3005. 256..65535:
  3006. if (taicpu(hp1).opsize <> S_W) then
  3007. begin
  3008. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3009. { Only print debug message if the TEST instruction
  3010. is a different size before and after }
  3011. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3012. taicpu(hp1).opsize := S_W;
  3013. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3014. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3015. end;
  3016. {$ifdef x86_64}
  3017. 65536..$7FFFFFFF:
  3018. if (taicpu(hp1).opsize <> S_L) then
  3019. begin
  3020. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3021. { Only print debug message if the TEST instruction
  3022. is a different size before and after }
  3023. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3024. taicpu(hp1).opsize := S_L;
  3025. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3026. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3027. end;
  3028. {$endif x86_64}
  3029. else
  3030. ;
  3031. end;
  3032. RemoveInstruction(hp2);
  3033. RemoveCurrentP(p, hp1);
  3034. Result:=true;
  3035. exit;
  3036. end;
  3037. end;
  3038. end
  3039. else if IsMOVZXAcceptable and
  3040. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3041. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3042. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3043. then
  3044. begin
  3045. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3046. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3047. case taicpu(p).opsize of
  3048. S_B:
  3049. if (taicpu(hp1).oper[0]^.val = $ff) then
  3050. begin
  3051. { Convert:
  3052. movb x, %regl movb x, %regl
  3053. andw ffh, %regw andl ffh, %regd
  3054. To:
  3055. movzbw x, %regd movzbl x, %regd
  3056. (Identical registers, just different sizes)
  3057. }
  3058. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3059. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3060. case taicpu(hp1).opsize of
  3061. S_W: NewSize := S_BW;
  3062. S_L: NewSize := S_BL;
  3063. {$ifdef x86_64}
  3064. S_Q: NewSize := S_BQ;
  3065. {$endif x86_64}
  3066. else
  3067. InternalError(2018011510);
  3068. end;
  3069. end
  3070. else
  3071. NewSize := S_NO;
  3072. S_W:
  3073. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3074. begin
  3075. { Convert:
  3076. movw x, %regw
  3077. andl ffffh, %regd
  3078. To:
  3079. movzwl x, %regd
  3080. (Identical registers, just different sizes)
  3081. }
  3082. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3083. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3084. case taicpu(hp1).opsize of
  3085. S_L: NewSize := S_WL;
  3086. {$ifdef x86_64}
  3087. S_Q: NewSize := S_WQ;
  3088. {$endif x86_64}
  3089. else
  3090. InternalError(2018011511);
  3091. end;
  3092. end
  3093. else
  3094. NewSize := S_NO;
  3095. else
  3096. NewSize := S_NO;
  3097. end;
  3098. if NewSize <> S_NO then
  3099. begin
  3100. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3101. { The actual optimization }
  3102. taicpu(p).opcode := A_MOVZX;
  3103. taicpu(p).changeopsize(NewSize);
  3104. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3105. { Safeguard if "and" is followed by a conditional command }
  3106. TransferUsedRegs(TmpUsedRegs);
  3107. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3108. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3109. begin
  3110. { At this point, the "and" command is effectively equivalent to
  3111. "test %reg,%reg". This will be handled separately by the
  3112. Peephole Optimizer. [Kit] }
  3113. DebugMsg(SPeepholeOptimization + PreMessage +
  3114. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3115. end
  3116. else
  3117. begin
  3118. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3119. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3120. RemoveInstruction(hp1);
  3121. end;
  3122. Result := True;
  3123. Exit;
  3124. end;
  3125. end;
  3126. end;
  3127. if (taicpu(hp1).opcode = A_OR) and
  3128. (taicpu(p).oper[1]^.typ = top_reg) and
  3129. MatchOperand(taicpu(p).oper[0]^, 0) and
  3130. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3131. begin
  3132. { mov 0, %reg
  3133. or ###,%reg
  3134. Change to (only if the flags are not used):
  3135. mov ###,%reg
  3136. }
  3137. TransferUsedRegs(TmpUsedRegs);
  3138. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3139. DoOptimisation := True;
  3140. { Even if the flags are used, we might be able to do the optimisation
  3141. if the conditions are predictable }
  3142. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3143. begin
  3144. { Only perform if ### = %reg (the same register) or equal to 0,
  3145. so %reg is guaranteed to still have a value of zero }
  3146. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3147. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3148. begin
  3149. hp2 := hp1;
  3150. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3151. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3152. GetNextInstruction(hp2, hp3) do
  3153. begin
  3154. { Don't continue modifying if the flags state is getting changed }
  3155. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3156. Break;
  3157. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3158. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3159. begin
  3160. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3161. begin
  3162. { Condition is always true }
  3163. case taicpu(hp3).opcode of
  3164. A_Jcc:
  3165. begin
  3166. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3167. { Check for jump shortcuts before we destroy the condition }
  3168. DoJumpOptimizations(hp3, TempBool);
  3169. MakeUnconditional(taicpu(hp3));
  3170. Result := True;
  3171. end;
  3172. A_CMOVcc:
  3173. begin
  3174. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3175. taicpu(hp3).opcode := A_MOV;
  3176. taicpu(hp3).condition := C_None;
  3177. Result := True;
  3178. end;
  3179. A_SETcc:
  3180. begin
  3181. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3182. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3183. taicpu(hp3).opcode := A_MOV;
  3184. taicpu(hp3).ops := 2;
  3185. taicpu(hp3).condition := C_None;
  3186. taicpu(hp3).opsize := S_B;
  3187. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3188. taicpu(hp3).loadconst(0, 1);
  3189. Result := True;
  3190. end;
  3191. else
  3192. InternalError(2021090701);
  3193. end;
  3194. end
  3195. 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
  3196. begin
  3197. { Condition is always false }
  3198. case taicpu(hp3).opcode of
  3199. A_Jcc:
  3200. begin
  3201. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3202. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3203. RemoveInstruction(hp3);
  3204. Result := True;
  3205. { Since hp3 was deleted, hp2 must not be updated }
  3206. Continue;
  3207. end;
  3208. A_CMOVcc:
  3209. begin
  3210. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3211. RemoveInstruction(hp3);
  3212. Result := True;
  3213. { Since hp3 was deleted, hp2 must not be updated }
  3214. Continue;
  3215. end;
  3216. A_SETcc:
  3217. begin
  3218. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3219. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3220. taicpu(hp3).opcode := A_MOV;
  3221. taicpu(hp3).ops := 2;
  3222. taicpu(hp3).condition := C_None;
  3223. taicpu(hp3).opsize := S_B;
  3224. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3225. taicpu(hp3).loadconst(0, 0);
  3226. Result := True;
  3227. end;
  3228. else
  3229. InternalError(2021090702);
  3230. end;
  3231. end
  3232. else
  3233. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3234. DoOptimisation := False;
  3235. end;
  3236. hp2 := hp3;
  3237. end;
  3238. { Flags are still in use - don't optimise }
  3239. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3240. DoOptimisation := False;
  3241. end
  3242. else
  3243. DoOptimisation := False;
  3244. end;
  3245. if DoOptimisation then
  3246. begin
  3247. {$ifdef x86_64}
  3248. { OR only supports 32-bit sign-extended constants for 64-bit
  3249. instructions, so compensate for this if the constant is
  3250. encoded as a value greater than or equal to 2^31 }
  3251. if (taicpu(hp1).opsize = S_Q) and
  3252. (taicpu(hp1).oper[0]^.typ = top_const) and
  3253. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3254. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3255. {$endif x86_64}
  3256. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3257. taicpu(hp1).opcode := A_MOV;
  3258. RemoveCurrentP(p, hp1);
  3259. Result := True;
  3260. Exit;
  3261. end;
  3262. end;
  3263. { Next instruction is also a MOV ? }
  3264. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3265. begin
  3266. if MatchOpType(taicpu(p), top_const, top_ref) and
  3267. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3268. TryConstMerge(p, hp1) then
  3269. begin
  3270. Result := True;
  3271. { In case we have four byte writes in a row, check for 2 more
  3272. right now so we don't have to wait for another iteration of
  3273. pass 1
  3274. }
  3275. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3276. case taicpu(p).opsize of
  3277. S_W:
  3278. begin
  3279. if GetNextInstruction(p, hp1) and
  3280. MatchInstruction(hp1, A_MOV, [S_B]) and
  3281. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3282. GetNextInstruction(hp1, hp2) and
  3283. MatchInstruction(hp2, A_MOV, [S_B]) and
  3284. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3285. { Try to merge the two bytes }
  3286. TryConstMerge(hp1, hp2) then
  3287. { Now try to merge the two words (hp2 will get deleted) }
  3288. TryConstMerge(p, hp1);
  3289. end;
  3290. S_L:
  3291. begin
  3292. { Though this only really benefits x86_64 and not i386, it
  3293. gets a potential optimisation done faster and hence
  3294. reduces the number of times OptPass1MOV is entered }
  3295. if GetNextInstruction(p, hp1) and
  3296. MatchInstruction(hp1, A_MOV, [S_W]) and
  3297. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3298. GetNextInstruction(hp1, hp2) and
  3299. MatchInstruction(hp2, A_MOV, [S_W]) and
  3300. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3301. { Try to merge the two words }
  3302. TryConstMerge(hp1, hp2) then
  3303. { This will always fail on i386, so don't bother
  3304. calling it unless we're doing x86_64 }
  3305. {$ifdef x86_64}
  3306. { Now try to merge the two longwords (hp2 will get deleted) }
  3307. TryConstMerge(p, hp1)
  3308. {$endif x86_64}
  3309. ;
  3310. end;
  3311. else
  3312. ;
  3313. end;
  3314. Exit;
  3315. end;
  3316. if (taicpu(p).oper[1]^.typ = top_reg) and
  3317. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3318. begin
  3319. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3320. TransferUsedRegs(TmpUsedRegs);
  3321. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3322. { we have
  3323. mov x, %treg
  3324. mov %treg, y
  3325. }
  3326. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3327. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3328. { we've got
  3329. mov x, %treg
  3330. mov %treg, y
  3331. with %treg is not used after }
  3332. case taicpu(p).oper[0]^.typ Of
  3333. { top_reg is covered by DeepMOVOpt }
  3334. top_const:
  3335. begin
  3336. { change
  3337. mov const, %treg
  3338. mov %treg, y
  3339. to
  3340. mov const, y
  3341. }
  3342. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3343. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3344. begin
  3345. if taicpu(hp1).oper[1]^.typ=top_reg then
  3346. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3347. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3348. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3349. RemoveInstruction(hp1);
  3350. Result:=true;
  3351. Exit;
  3352. end;
  3353. end;
  3354. top_ref:
  3355. case taicpu(hp1).oper[1]^.typ of
  3356. top_reg:
  3357. begin
  3358. { change
  3359. mov mem, %treg
  3360. mov %treg, %reg
  3361. to
  3362. mov mem, %reg"
  3363. }
  3364. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3365. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3366. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3367. RemoveInstruction(hp1);
  3368. Result:=true;
  3369. Exit;
  3370. end;
  3371. top_ref:
  3372. begin
  3373. {$ifdef x86_64}
  3374. { Look for the following to simplify:
  3375. mov x(mem1), %reg
  3376. mov %reg, y(mem2)
  3377. mov x+8(mem1), %reg
  3378. mov %reg, y+8(mem2)
  3379. Change to:
  3380. movdqu x(mem1), %xmmreg
  3381. movdqu %xmmreg, y(mem2)
  3382. ...but only as long as the memory blocks don't overlap
  3383. }
  3384. SourceRef := taicpu(p).oper[0]^.ref^;
  3385. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3386. if (taicpu(p).opsize = S_Q) and
  3387. GetNextInstruction(hp1, hp2) and
  3388. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3389. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3390. begin
  3391. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3392. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3393. Inc(SourceRef.offset, 8);
  3394. if UseAVX then
  3395. begin
  3396. MovAligned := A_VMOVDQA;
  3397. MovUnaligned := A_VMOVDQU;
  3398. end
  3399. else
  3400. begin
  3401. MovAligned := A_MOVDQA;
  3402. MovUnaligned := A_MOVDQU;
  3403. end;
  3404. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3405. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3406. begin
  3407. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3408. Inc(TargetRef.offset, 8);
  3409. if GetNextInstruction(hp2, hp3) and
  3410. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3411. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3412. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3413. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3414. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3415. begin
  3416. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3417. if NewMMReg <> NR_NO then
  3418. begin
  3419. { Remember that the offsets are 8 ahead }
  3420. if ((SourceRef.offset mod 16) = 8) and
  3421. (
  3422. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3423. (SourceRef.base = current_procinfo.framepointer) or
  3424. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3425. ) then
  3426. taicpu(p).opcode := MovAligned
  3427. else
  3428. taicpu(p).opcode := MovUnaligned;
  3429. taicpu(p).opsize := S_XMM;
  3430. taicpu(p).oper[1]^.reg := NewMMReg;
  3431. if ((TargetRef.offset mod 16) = 8) and
  3432. (
  3433. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3434. (TargetRef.base = current_procinfo.framepointer) or
  3435. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3436. ) then
  3437. taicpu(hp1).opcode := MovAligned
  3438. else
  3439. taicpu(hp1).opcode := MovUnaligned;
  3440. taicpu(hp1).opsize := S_XMM;
  3441. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3442. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3443. RemoveInstruction(hp2);
  3444. RemoveInstruction(hp3);
  3445. Result := True;
  3446. Exit;
  3447. end;
  3448. end;
  3449. end
  3450. else
  3451. begin
  3452. { See if the next references are 8 less rather than 8 greater }
  3453. Dec(SourceRef.offset, 16); { -8 the other way }
  3454. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3455. begin
  3456. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3457. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3458. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3459. GetNextInstruction(hp2, hp3) and
  3460. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3461. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3462. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3463. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3464. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3465. begin
  3466. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3467. if NewMMReg <> NR_NO then
  3468. begin
  3469. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3470. if ((SourceRef.offset mod 16) = 0) and
  3471. (
  3472. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3473. (SourceRef.base = current_procinfo.framepointer) or
  3474. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3475. ) then
  3476. taicpu(hp2).opcode := MovAligned
  3477. else
  3478. taicpu(hp2).opcode := MovUnaligned;
  3479. taicpu(hp2).opsize := S_XMM;
  3480. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3481. if ((TargetRef.offset mod 16) = 0) and
  3482. (
  3483. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3484. (TargetRef.base = current_procinfo.framepointer) or
  3485. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3486. ) then
  3487. taicpu(hp3).opcode := MovAligned
  3488. else
  3489. taicpu(hp3).opcode := MovUnaligned;
  3490. taicpu(hp3).opsize := S_XMM;
  3491. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3492. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3493. RemoveInstruction(hp1);
  3494. RemoveCurrentP(p, hp2);
  3495. Result := True;
  3496. Exit;
  3497. end;
  3498. end;
  3499. end;
  3500. end;
  3501. end;
  3502. {$endif x86_64}
  3503. end;
  3504. else
  3505. { The write target should be a reg or a ref }
  3506. InternalError(2021091601);
  3507. end;
  3508. else
  3509. ;
  3510. end
  3511. else
  3512. { %treg is used afterwards, but all eventualities
  3513. other than the first MOV instruction being a constant
  3514. are covered by DeepMOVOpt, so only check for that }
  3515. if (taicpu(p).oper[0]^.typ = top_const) and
  3516. (
  3517. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3518. not (cs_opt_size in current_settings.optimizerswitches) or
  3519. (taicpu(hp1).opsize = S_B)
  3520. ) and
  3521. (
  3522. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3523. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3524. ) then
  3525. begin
  3526. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3527. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3528. end;
  3529. end;
  3530. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3531. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3532. { mov reg1, mem1 or mov mem1, reg1
  3533. mov mem2, reg2 mov reg2, mem2}
  3534. begin
  3535. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3536. { mov reg1, mem1 or mov mem1, reg1
  3537. mov mem2, reg1 mov reg2, mem1}
  3538. begin
  3539. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3540. { Removes the second statement from
  3541. mov reg1, mem1/reg2
  3542. mov mem1/reg2, reg1 }
  3543. begin
  3544. if taicpu(p).oper[0]^.typ=top_reg then
  3545. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3546. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3547. RemoveInstruction(hp1);
  3548. Result:=true;
  3549. exit;
  3550. end
  3551. else
  3552. begin
  3553. TransferUsedRegs(TmpUsedRegs);
  3554. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3555. if (taicpu(p).oper[1]^.typ = top_ref) and
  3556. { mov reg1, mem1
  3557. mov mem2, reg1 }
  3558. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3559. GetNextInstruction(hp1, hp2) and
  3560. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3561. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3562. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3563. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3564. { change to
  3565. mov reg1, mem1 mov reg1, mem1
  3566. mov mem2, reg1 cmp reg1, mem2
  3567. cmp mem1, reg1
  3568. }
  3569. begin
  3570. RemoveInstruction(hp2);
  3571. taicpu(hp1).opcode := A_CMP;
  3572. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3573. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3574. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3575. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3576. end;
  3577. end;
  3578. end
  3579. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3580. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3581. begin
  3582. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3583. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3584. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3585. end
  3586. else
  3587. begin
  3588. TransferUsedRegs(TmpUsedRegs);
  3589. if GetNextInstruction(hp1, hp2) and
  3590. MatchOpType(taicpu(p),top_ref,top_reg) and
  3591. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3592. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3593. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3594. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3595. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3596. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3597. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3598. { mov mem1, %reg1
  3599. mov %reg1, mem2
  3600. mov mem2, reg2
  3601. to:
  3602. mov mem1, reg2
  3603. mov reg2, mem2}
  3604. begin
  3605. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3606. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3607. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3608. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3609. RemoveInstruction(hp2);
  3610. Result := True;
  3611. end
  3612. {$ifdef i386}
  3613. { this is enabled for i386 only, as the rules to create the reg sets below
  3614. are too complicated for x86-64, so this makes this code too error prone
  3615. on x86-64
  3616. }
  3617. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3618. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3619. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3620. { mov mem1, reg1 mov mem1, reg1
  3621. mov reg1, mem2 mov reg1, mem2
  3622. mov mem2, reg2 mov mem2, reg1
  3623. to: to:
  3624. mov mem1, reg1 mov mem1, reg1
  3625. mov mem1, reg2 mov reg1, mem2
  3626. mov reg1, mem2
  3627. or (if mem1 depends on reg1
  3628. and/or if mem2 depends on reg2)
  3629. to:
  3630. mov mem1, reg1
  3631. mov reg1, mem2
  3632. mov reg1, reg2
  3633. }
  3634. begin
  3635. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3636. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3637. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3638. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3639. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3640. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3641. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3642. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3643. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3644. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3645. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3646. end
  3647. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3648. begin
  3649. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3650. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3651. end
  3652. else
  3653. begin
  3654. RemoveInstruction(hp2);
  3655. end
  3656. {$endif i386}
  3657. ;
  3658. end;
  3659. end
  3660. { movl [mem1],reg1
  3661. movl [mem1],reg2
  3662. to
  3663. movl [mem1],reg1
  3664. movl reg1,reg2
  3665. }
  3666. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3667. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3668. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3669. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3670. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3671. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3672. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3673. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3674. begin
  3675. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3676. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3677. end;
  3678. { movl const1,[mem1]
  3679. movl [mem1],reg1
  3680. to
  3681. movl const1,reg1
  3682. movl reg1,[mem1]
  3683. }
  3684. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3685. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3686. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3687. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3688. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3689. begin
  3690. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3691. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3692. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3693. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3694. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3695. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3696. Result:=true;
  3697. exit;
  3698. end;
  3699. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3700. { Change:
  3701. movl %reg1,%reg2
  3702. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3703. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3704. To:
  3705. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3706. movl x(%reg1),%reg1
  3707. movl %reg1,%regX
  3708. }
  3709. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3710. begin
  3711. p_SourceReg := taicpu(p).oper[0]^.reg;
  3712. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3713. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3714. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3715. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3716. GetNextInstruction(hp1, hp2) and
  3717. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3718. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3719. begin
  3720. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3721. if RegInRef(p_TargetReg, SourceRef) and
  3722. { If %reg1 also appears in the second reference, then it will
  3723. not refer to the same memory block as the first reference }
  3724. not RegInRef(p_SourceReg, SourceRef) then
  3725. begin
  3726. { Check to see if the references match if %reg2 is changed to %reg1 }
  3727. if SourceRef.base = p_TargetReg then
  3728. SourceRef.base := p_SourceReg;
  3729. if SourceRef.index = p_TargetReg then
  3730. SourceRef.index := p_SourceReg;
  3731. { RefsEqual also checks to ensure both references are non-volatile }
  3732. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3733. begin
  3734. taicpu(hp2).loadreg(0, p_SourceReg);
  3735. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3736. Result := True;
  3737. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3738. begin
  3739. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3740. RemoveCurrentP(p, hp1);
  3741. Exit;
  3742. end
  3743. else
  3744. begin
  3745. { Check to see if %reg2 is no longer in use }
  3746. TransferUsedRegs(TmpUsedRegs);
  3747. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3748. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3749. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3750. begin
  3751. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3752. RemoveCurrentP(p, hp1);
  3753. Exit;
  3754. end;
  3755. end;
  3756. { If we reach this point, p and hp1 weren't actually modified,
  3757. so we can do a bit more work on this pass }
  3758. end;
  3759. end;
  3760. end;
  3761. end;
  3762. end;
  3763. {$ifdef x86_64}
  3764. { Change:
  3765. movl %reg1l,%reg2l
  3766. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3767. To:
  3768. movl %reg1l,%reg2l
  3769. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3770. If %reg1 = %reg3, convert to:
  3771. movl %reg1l,%reg2l
  3772. andl %reg1l,%reg1l
  3773. }
  3774. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3775. MatchOpType(taicpu(p), top_reg, top_reg) and
  3776. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3777. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3778. begin
  3779. TransferUsedRegs(TmpUsedRegs);
  3780. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3781. taicpu(hp1).opsize := S_L;
  3782. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3783. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3784. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3785. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3786. begin
  3787. { %reg1 = %reg3 }
  3788. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3789. taicpu(hp1).opcode := A_AND;
  3790. end
  3791. else
  3792. begin
  3793. { %reg1 <> %reg3 }
  3794. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3795. end;
  3796. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3797. begin
  3798. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3799. RemoveCurrentP(p, hp1);
  3800. Result := True;
  3801. Exit;
  3802. end
  3803. else
  3804. begin
  3805. { Initial instruction wasn't actually changed }
  3806. Include(OptsToCheck, aoc_ForceNewIteration);
  3807. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3808. appears below since %reg1 has technically changed }
  3809. if taicpu(hp1).opcode = A_AND then
  3810. Exit;
  3811. end;
  3812. end;
  3813. {$endif x86_64}
  3814. { search further than the next instruction for a mov (as long as it's not a jump) }
  3815. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3816. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3817. (taicpu(p).oper[1]^.typ = top_reg) and
  3818. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3819. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3820. begin
  3821. { we work with hp2 here, so hp1 can be still used later on when
  3822. checking for GetNextInstruction_p }
  3823. hp3 := hp1;
  3824. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3825. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3826. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3827. TransferUsedRegs(TmpUsedRegs);
  3828. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3829. if NotFirstIteration then
  3830. JumpTracking := TLinkedList.Create
  3831. else
  3832. JumpTracking := nil;
  3833. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3834. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3835. (hp2.typ=ait_instruction) do
  3836. begin
  3837. case taicpu(hp2).opcode of
  3838. A_POP:
  3839. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3840. begin
  3841. if not CrossJump and
  3842. not RegUsedBetween(p_TargetReg, p, hp2) then
  3843. begin
  3844. { We can remove the original MOV since the register
  3845. wasn't used between it and its popping from the stack }
  3846. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3847. RemoveCurrentp(p, hp1);
  3848. Result := True;
  3849. JumpTracking.Free;
  3850. Exit;
  3851. end;
  3852. { Can't go any further }
  3853. Break;
  3854. end;
  3855. A_MOV:
  3856. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3857. ((taicpu(p).oper[0]^.typ=top_const) or
  3858. ((taicpu(p).oper[0]^.typ=top_reg) and
  3859. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3860. )
  3861. ) then
  3862. begin
  3863. { we have
  3864. mov x, %treg
  3865. mov %treg, y
  3866. }
  3867. { We don't need to call UpdateUsedRegs for every instruction between
  3868. p and hp2 because the register we're concerned about will not
  3869. become deallocated (otherwise GetNextInstructionUsingReg would
  3870. have stopped at an earlier instruction). [Kit] }
  3871. TempRegUsed :=
  3872. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3873. RegReadByInstruction(p_TargetReg, hp3) or
  3874. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3875. case taicpu(p).oper[0]^.typ Of
  3876. top_reg:
  3877. begin
  3878. { change
  3879. mov %reg, %treg
  3880. mov %treg, y
  3881. to
  3882. mov %reg, y
  3883. }
  3884. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3885. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3886. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3887. begin
  3888. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3889. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3890. if TempRegUsed then
  3891. begin
  3892. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3893. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3894. { Set the start of the next GetNextInstructionUsingRegCond search
  3895. to start at the entry right before hp2 (which is about to be removed) }
  3896. hp3 := tai(hp2.Previous);
  3897. RemoveInstruction(hp2);
  3898. Include(OptsToCheck, aoc_ForceNewIteration);
  3899. { See if there's more we can optimise }
  3900. Continue;
  3901. end
  3902. else
  3903. begin
  3904. RemoveInstruction(hp2);
  3905. { We can remove the original MOV too }
  3906. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3907. RemoveCurrentP(p, hp1);
  3908. Result:=true;
  3909. JumpTracking.Free;
  3910. Exit;
  3911. end;
  3912. end
  3913. else
  3914. begin
  3915. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3916. taicpu(hp2).loadReg(0, p_SourceReg);
  3917. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3918. { Check to see if the register also appears in the reference }
  3919. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3920. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3921. { Don't remove the first instruction if the temporary register is in use }
  3922. if not TempRegUsed and
  3923. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3924. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3925. begin
  3926. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3927. RemoveCurrentP(p, hp1);
  3928. Result:=true;
  3929. JumpTracking.Free;
  3930. Exit;
  3931. end;
  3932. { No need to set Result to True here. If there's another instruction later
  3933. on that can be optimised, it will be detected when the main Pass 1 loop
  3934. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3935. end;
  3936. end;
  3937. top_const:
  3938. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3939. begin
  3940. { change
  3941. mov const, %treg
  3942. mov %treg, y
  3943. to
  3944. mov const, y
  3945. }
  3946. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3947. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3948. begin
  3949. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3950. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3951. if TempRegUsed then
  3952. begin
  3953. { Don't remove the first instruction if the temporary register is in use }
  3954. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3955. { No need to set Result to True. If there's another instruction later on
  3956. that can be optimised, it will be detected when the main Pass 1 loop
  3957. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3958. end
  3959. else
  3960. begin
  3961. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3962. RemoveCurrentP(p, hp1);
  3963. Result:=true;
  3964. Exit;
  3965. end;
  3966. end;
  3967. end;
  3968. else
  3969. Internalerror(2019103001);
  3970. end;
  3971. end
  3972. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3973. begin
  3974. if not CrossJump and
  3975. not RegUsedBetween(p_TargetReg, p, hp2) and
  3976. not RegReadByInstruction(p_TargetReg, hp2) then
  3977. begin
  3978. { Register is not used before it is overwritten }
  3979. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3980. RemoveCurrentp(p, hp1);
  3981. Result := True;
  3982. Exit;
  3983. end;
  3984. if (taicpu(p).oper[0]^.typ = top_const) and
  3985. (taicpu(hp2).oper[0]^.typ = top_const) then
  3986. begin
  3987. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3988. begin
  3989. { Same value - register hasn't changed }
  3990. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3991. RemoveInstruction(hp2);
  3992. Include(OptsToCheck, aoc_ForceNewIteration);
  3993. { See if there's more we can optimise }
  3994. Continue;
  3995. end;
  3996. end;
  3997. {$ifdef x86_64}
  3998. end
  3999. { Change:
  4000. movl %reg1l,%reg2l
  4001. ...
  4002. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4003. To:
  4004. movl %reg1l,%reg2l
  4005. ...
  4006. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4007. If %reg1 = %reg3, convert to:
  4008. movl %reg1l,%reg2l
  4009. ...
  4010. andl %reg1l,%reg1l
  4011. }
  4012. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4013. (taicpu(p).oper[0]^.typ = top_reg) and
  4014. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4015. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4016. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4017. begin
  4018. TempRegUsed :=
  4019. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4020. RegReadByInstruction(p_TargetReg, hp3) or
  4021. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4022. taicpu(hp2).opsize := S_L;
  4023. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4024. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4025. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4026. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4027. begin
  4028. { %reg1 = %reg3 }
  4029. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4030. taicpu(hp2).opcode := A_AND;
  4031. end
  4032. else
  4033. begin
  4034. { %reg1 <> %reg3 }
  4035. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4036. end;
  4037. if not TempRegUsed then
  4038. begin
  4039. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4040. RemoveCurrentP(p, hp1);
  4041. Result := True;
  4042. Exit;
  4043. end
  4044. else
  4045. begin
  4046. { Initial instruction wasn't actually changed }
  4047. Include(OptsToCheck, aoc_ForceNewIteration);
  4048. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4049. appears below since %reg1 has technically changed }
  4050. if taicpu(hp2).opcode = A_AND then
  4051. Break;
  4052. end;
  4053. {$endif x86_64}
  4054. end;
  4055. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4056. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4057. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4058. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4059. begin
  4060. {
  4061. Change from:
  4062. mov ###, %reg
  4063. ...
  4064. movs/z %reg,%reg (Same register, just different sizes)
  4065. To:
  4066. movs/z ###, %reg (Longer version)
  4067. ...
  4068. (remove)
  4069. }
  4070. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4071. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4072. { Keep the first instruction as mov if ### is a constant }
  4073. if taicpu(p).oper[0]^.typ = top_const then
  4074. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4075. else
  4076. begin
  4077. taicpu(p).opcode := taicpu(hp2).opcode;
  4078. taicpu(p).opsize := taicpu(hp2).opsize;
  4079. end;
  4080. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4081. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4082. RemoveInstruction(hp2);
  4083. Result := True;
  4084. JumpTracking.Free;
  4085. Exit;
  4086. end;
  4087. else
  4088. { Move down to the if-block below };
  4089. end;
  4090. { Also catches MOV/S/Z instructions that aren't modified }
  4091. if taicpu(p).oper[0]^.typ = top_reg then
  4092. begin
  4093. p_SourceReg := taicpu(p).oper[0]^.reg;
  4094. if
  4095. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4096. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4097. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4098. begin
  4099. Result := True;
  4100. { Just in case something didn't get modified (e.g. an
  4101. implicit register). Also, if it does read from this
  4102. register, then there's no longer an advantage to
  4103. changing the register on subsequent instructions.}
  4104. if not RegReadByInstruction(p_TargetReg, hp2) then
  4105. begin
  4106. { If a conditional jump was crossed, do not delete
  4107. the original MOV no matter what }
  4108. if not CrossJump and
  4109. { RegEndOfLife returns True if the register is
  4110. deallocated before the next instruction or has
  4111. been loaded with a new value }
  4112. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4113. begin
  4114. { We can remove the original MOV }
  4115. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4116. RemoveCurrentp(p, hp1);
  4117. JumpTracking.Free;
  4118. Result := True;
  4119. Exit;
  4120. end;
  4121. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4122. begin
  4123. { See if there's more we can optimise }
  4124. hp3 := hp2;
  4125. Continue;
  4126. end;
  4127. end;
  4128. end;
  4129. end;
  4130. { Break out of the while loop under normal circumstances }
  4131. Break;
  4132. end;
  4133. JumpTracking.Free;
  4134. end;
  4135. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4136. (taicpu(p).oper[1]^.typ = top_reg) and
  4137. (taicpu(p).opsize = S_L) and
  4138. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4139. (hp2.typ = ait_instruction) and
  4140. (taicpu(hp2).opcode = A_AND) and
  4141. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4142. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4143. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4144. ) then
  4145. begin
  4146. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4147. begin
  4148. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4149. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4150. begin
  4151. { Optimize out:
  4152. mov x, %reg
  4153. and ffffffffh, %reg
  4154. }
  4155. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4156. RemoveInstruction(hp2);
  4157. Result:=true;
  4158. exit;
  4159. end;
  4160. end;
  4161. end;
  4162. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4163. x >= RetOffset) as it doesn't do anything (it writes either to a
  4164. parameter or to the temporary storage room for the function
  4165. result)
  4166. }
  4167. if IsExitCode(hp1) and
  4168. (taicpu(p).oper[1]^.typ = top_ref) and
  4169. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4170. (
  4171. (
  4172. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4173. not (
  4174. assigned(current_procinfo.procdef.funcretsym) and
  4175. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4176. )
  4177. ) or
  4178. { Also discard writes to the stack that are below the base pointer,
  4179. as this is temporary storage rather than a function result on the
  4180. stack, say. }
  4181. (
  4182. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4183. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4184. )
  4185. ) then
  4186. begin
  4187. RemoveCurrentp(p, hp1);
  4188. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4189. RemoveLastDeallocForFuncRes(p);
  4190. Result:=true;
  4191. exit;
  4192. end;
  4193. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4194. begin
  4195. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4196. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4197. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4198. begin
  4199. { change
  4200. mov reg1, mem1
  4201. test/cmp x, mem1
  4202. to
  4203. mov reg1, mem1
  4204. test/cmp x, reg1
  4205. }
  4206. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4207. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4208. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4209. Result := True;
  4210. Exit;
  4211. end;
  4212. if DoMovCmpMemOpt(p, hp1) then
  4213. begin
  4214. Result := True;
  4215. Exit;
  4216. end;
  4217. end;
  4218. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4219. { If the flags register is in use, don't change the instruction to an
  4220. ADD otherwise this will scramble the flags. [Kit] }
  4221. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4222. begin
  4223. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4224. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4225. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4226. ) or
  4227. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4228. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4229. )
  4230. ) then
  4231. { mov reg1,ref
  4232. lea reg2,[reg1,reg2]
  4233. to
  4234. add reg2,ref}
  4235. begin
  4236. TransferUsedRegs(TmpUsedRegs);
  4237. { reg1 may not be used afterwards }
  4238. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4239. begin
  4240. Taicpu(hp1).opcode:=A_ADD;
  4241. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4242. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4243. RemoveCurrentp(p, hp1);
  4244. result:=true;
  4245. exit;
  4246. end;
  4247. end;
  4248. { If the LEA instruction can be converted into an arithmetic instruction,
  4249. it may be possible to then fold it in the next optimisation, otherwise
  4250. there's nothing more that can be optimised here. }
  4251. if not ConvertLEA(taicpu(hp1)) then
  4252. Exit;
  4253. end;
  4254. if (taicpu(p).oper[1]^.typ = top_reg) and
  4255. (hp1.typ = ait_instruction) and
  4256. GetNextInstruction(hp1, hp2) and
  4257. MatchInstruction(hp2,A_MOV,[]) and
  4258. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4259. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4260. (
  4261. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4262. {$ifdef x86_64}
  4263. or
  4264. (
  4265. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4266. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4267. )
  4268. {$endif x86_64}
  4269. ) then
  4270. begin
  4271. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4272. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4273. { change movsX/movzX reg/ref, reg2
  4274. add/sub/or/... reg3/$const, reg2
  4275. mov reg2 reg/ref
  4276. dealloc reg2
  4277. to
  4278. add/sub/or/... reg3/$const, reg/ref }
  4279. begin
  4280. TransferUsedRegs(TmpUsedRegs);
  4281. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4282. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4283. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4284. begin
  4285. { by example:
  4286. movswl %si,%eax movswl %si,%eax p
  4287. decl %eax addl %edx,%eax hp1
  4288. movw %ax,%si movw %ax,%si hp2
  4289. ->
  4290. movswl %si,%eax movswl %si,%eax p
  4291. decw %eax addw %edx,%eax hp1
  4292. movw %ax,%si movw %ax,%si hp2
  4293. }
  4294. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4295. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4296. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4297. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4298. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4299. {
  4300. ->
  4301. movswl %si,%eax movswl %si,%eax p
  4302. decw %si addw %dx,%si hp1
  4303. movw %ax,%si movw %ax,%si hp2
  4304. }
  4305. case taicpu(hp1).ops of
  4306. 1:
  4307. begin
  4308. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4309. if taicpu(hp1).oper[0]^.typ=top_reg then
  4310. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4311. end;
  4312. 2:
  4313. begin
  4314. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4315. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4316. (taicpu(hp1).opcode<>A_SHL) and
  4317. (taicpu(hp1).opcode<>A_SHR) and
  4318. (taicpu(hp1).opcode<>A_SAR) then
  4319. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4320. end;
  4321. else
  4322. internalerror(2008042701);
  4323. end;
  4324. {
  4325. ->
  4326. decw %si addw %dx,%si p
  4327. }
  4328. RemoveInstruction(hp2);
  4329. RemoveCurrentP(p, hp1);
  4330. Result:=True;
  4331. Exit;
  4332. end;
  4333. end;
  4334. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4335. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4336. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4337. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4338. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4339. )
  4340. {$ifdef i386}
  4341. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4342. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4343. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4344. {$endif i386}
  4345. then
  4346. { change movsX/movzX reg/ref, reg2
  4347. add/sub/or/... regX/$const, reg2
  4348. mov reg2, reg3
  4349. dealloc reg2
  4350. to
  4351. movsX/movzX reg/ref, reg3
  4352. add/sub/or/... reg3/$const, reg3
  4353. }
  4354. begin
  4355. TransferUsedRegs(TmpUsedRegs);
  4356. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4357. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4358. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4359. begin
  4360. { by example:
  4361. movswl %si,%eax movswl %si,%eax p
  4362. decl %eax addl %edx,%eax hp1
  4363. movw %ax,%si movw %ax,%si hp2
  4364. ->
  4365. movswl %si,%eax movswl %si,%eax p
  4366. decw %eax addw %edx,%eax hp1
  4367. movw %ax,%si movw %ax,%si hp2
  4368. }
  4369. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4370. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4371. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4372. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4373. { limit size of constants as well to avoid assembler errors, but
  4374. check opsize to avoid overflow when left shifting the 1 }
  4375. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4376. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4377. {$ifdef x86_64}
  4378. { Be careful of, for example:
  4379. movl %reg1,%reg2
  4380. addl %reg3,%reg2
  4381. movq %reg2,%reg4
  4382. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4383. }
  4384. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4385. begin
  4386. taicpu(hp2).changeopsize(S_L);
  4387. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4388. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4389. end;
  4390. {$endif x86_64}
  4391. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4392. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4393. if taicpu(p).oper[0]^.typ=top_reg then
  4394. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4395. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4396. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4397. {
  4398. ->
  4399. movswl %si,%eax movswl %si,%eax p
  4400. decw %si addw %dx,%si hp1
  4401. movw %ax,%si movw %ax,%si hp2
  4402. }
  4403. case taicpu(hp1).ops of
  4404. 1:
  4405. begin
  4406. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4407. if taicpu(hp1).oper[0]^.typ=top_reg then
  4408. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4409. end;
  4410. 2:
  4411. begin
  4412. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4413. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4414. (taicpu(hp1).opcode<>A_SHL) and
  4415. (taicpu(hp1).opcode<>A_SHR) and
  4416. (taicpu(hp1).opcode<>A_SAR) then
  4417. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4418. end;
  4419. else
  4420. internalerror(2018111801);
  4421. end;
  4422. {
  4423. ->
  4424. decw %si addw %dx,%si p
  4425. }
  4426. RemoveInstruction(hp2);
  4427. end;
  4428. end;
  4429. end;
  4430. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4431. GetNextInstruction(hp1, hp2) and
  4432. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4433. MatchOperand(Taicpu(p).oper[0]^,0) and
  4434. (Taicpu(p).oper[1]^.typ = top_reg) and
  4435. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4436. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4437. { mov reg1,0
  4438. bts reg1,operand1 --> mov reg1,operand2
  4439. or reg1,operand2 bts reg1,operand1}
  4440. begin
  4441. Taicpu(hp2).opcode:=A_MOV;
  4442. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4443. asml.remove(hp1);
  4444. insertllitem(hp2,hp2.next,hp1);
  4445. RemoveCurrentp(p, hp1);
  4446. Result:=true;
  4447. exit;
  4448. end;
  4449. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4450. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4451. GetNextInstruction(hp1, hp2) and
  4452. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4453. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4454. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4455. { change
  4456. mov reg1,reg2
  4457. sub reg3,reg2
  4458. cmp reg3,reg1
  4459. into
  4460. mov reg1,reg2
  4461. sub reg3,reg2
  4462. }
  4463. begin
  4464. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4465. RemoveInstruction(hp2);
  4466. Result:=true;
  4467. exit;
  4468. end;
  4469. {
  4470. mov ref,reg0
  4471. <op> reg0,reg1
  4472. dealloc reg0
  4473. to
  4474. <op> ref,reg1
  4475. }
  4476. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4477. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4478. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4479. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4480. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4481. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4482. begin
  4483. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4484. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4485. RemoveCurrentp(p, hp1);
  4486. Result:=true;
  4487. exit;
  4488. end;
  4489. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4490. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4491. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4492. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4493. begin
  4494. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4495. {$ifdef x86_64}
  4496. { Convert:
  4497. movq x(ref),%reg64
  4498. shrq y,%reg64
  4499. To:
  4500. movl x+4(ref),%reg32
  4501. shrl y-32,%reg32 (Remove if y = 32)
  4502. }
  4503. if (taicpu(p).opsize = S_Q) and
  4504. (taicpu(hp1).opcode = A_SHR) and
  4505. (taicpu(hp1).oper[0]^.val >= 32) then
  4506. begin
  4507. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4508. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4509. { Convert to 32-bit }
  4510. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4511. taicpu(p).opsize := S_L;
  4512. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4513. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4514. if (taicpu(hp1).oper[0]^.val = 32) then
  4515. begin
  4516. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4517. RemoveInstruction(hp1);
  4518. end
  4519. else
  4520. begin
  4521. { This will potentially open up more arithmetic operations since
  4522. the peephole optimizer now has a big hint that only the lower
  4523. 32 bits are currently in use (and opcodes are smaller in size) }
  4524. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4525. taicpu(hp1).opsize := S_L;
  4526. Dec(taicpu(hp1).oper[0]^.val, 32);
  4527. DebugMsg(SPeepholeOptimization + PreMessage +
  4528. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4529. end;
  4530. Result := True;
  4531. Exit;
  4532. end;
  4533. {$endif x86_64}
  4534. { Convert:
  4535. movl x(ref),%reg
  4536. shrl $24,%reg
  4537. To:
  4538. movzbl x+3(ref),%reg
  4539. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4540. Also accept sar instead of shr, but convert to movsx instead of movzx
  4541. }
  4542. if taicpu(hp1).opcode = A_SHR then
  4543. MovUnaligned := A_MOVZX
  4544. else
  4545. MovUnaligned := A_MOVSX;
  4546. NewSize := S_NO;
  4547. NewOffset := 0;
  4548. case taicpu(p).opsize of
  4549. S_B:
  4550. { No valid combinations };
  4551. S_W:
  4552. if (taicpu(hp1).oper[0]^.val = 8) then
  4553. begin
  4554. NewSize := S_BW;
  4555. NewOffset := 1;
  4556. end;
  4557. S_L:
  4558. case taicpu(hp1).oper[0]^.val of
  4559. 16:
  4560. begin
  4561. NewSize := S_WL;
  4562. NewOffset := 2;
  4563. end;
  4564. 24:
  4565. begin
  4566. NewSize := S_BL;
  4567. NewOffset := 3;
  4568. end;
  4569. else
  4570. ;
  4571. end;
  4572. {$ifdef x86_64}
  4573. S_Q:
  4574. case taicpu(hp1).oper[0]^.val of
  4575. 32:
  4576. begin
  4577. if taicpu(hp1).opcode = A_SAR then
  4578. begin
  4579. { 32-bit to 64-bit is a distinct instruction }
  4580. MovUnaligned := A_MOVSXD;
  4581. NewSize := S_LQ;
  4582. NewOffset := 4;
  4583. end
  4584. else
  4585. { Should have been handled by MovShr2Mov above }
  4586. InternalError(2022081811);
  4587. end;
  4588. 48:
  4589. begin
  4590. NewSize := S_WQ;
  4591. NewOffset := 6;
  4592. end;
  4593. 56:
  4594. begin
  4595. NewSize := S_BQ;
  4596. NewOffset := 7;
  4597. end;
  4598. else
  4599. ;
  4600. end;
  4601. {$endif x86_64}
  4602. else
  4603. InternalError(2022081810);
  4604. end;
  4605. if (NewSize <> S_NO) and
  4606. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4607. begin
  4608. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4609. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4610. debug_op2str(MovUnaligned);
  4611. {$ifdef x86_64}
  4612. if MovUnaligned <> A_MOVSXD then
  4613. { Don't add size suffix for MOVSXD }
  4614. {$endif x86_64}
  4615. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4616. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4617. taicpu(p).opcode := MovUnaligned;
  4618. taicpu(p).opsize := NewSize;
  4619. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4620. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4621. RemoveInstruction(hp1);
  4622. Result := True;
  4623. Exit;
  4624. end;
  4625. end;
  4626. { Backward optimisation shared with OptPass2MOV }
  4627. if FuncMov2Func(p, hp1) then
  4628. begin
  4629. Result := True;
  4630. Exit;
  4631. end;
  4632. end;
  4633. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4634. var
  4635. hp1 : tai;
  4636. begin
  4637. Result:=false;
  4638. if taicpu(p).ops <> 2 then
  4639. exit;
  4640. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4641. GetNextInstruction(p,hp1) then
  4642. begin
  4643. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4644. (taicpu(hp1).ops = 2) then
  4645. begin
  4646. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4647. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4648. { movXX reg1, mem1 or movXX mem1, reg1
  4649. movXX mem2, reg2 movXX reg2, mem2}
  4650. begin
  4651. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4652. { movXX reg1, mem1 or movXX mem1, reg1
  4653. movXX mem2, reg1 movXX reg2, mem1}
  4654. begin
  4655. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4656. begin
  4657. { Removes the second statement from
  4658. movXX reg1, mem1/reg2
  4659. movXX mem1/reg2, reg1
  4660. }
  4661. if taicpu(p).oper[0]^.typ=top_reg then
  4662. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4663. { Removes the second statement from
  4664. movXX mem1/reg1, reg2
  4665. movXX reg2, mem1/reg1
  4666. }
  4667. if (taicpu(p).oper[1]^.typ=top_reg) and
  4668. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4669. begin
  4670. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4671. RemoveInstruction(hp1);
  4672. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4673. Result:=true;
  4674. exit;
  4675. end
  4676. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4677. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4678. begin
  4679. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4680. RemoveInstruction(hp1);
  4681. Result:=true;
  4682. exit;
  4683. end;
  4684. end
  4685. end;
  4686. end;
  4687. end;
  4688. end;
  4689. end;
  4690. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4691. var
  4692. hp1 : tai;
  4693. begin
  4694. result:=false;
  4695. { replace
  4696. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4697. MovX %mreg2,%mreg1
  4698. dealloc %mreg2
  4699. by
  4700. <Op>X %mreg2,%mreg1
  4701. ?
  4702. }
  4703. if GetNextInstruction(p,hp1) and
  4704. { we mix single and double opperations here because we assume that the compiler
  4705. generates vmovapd only after double operations and vmovaps only after single operations }
  4706. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4707. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4708. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4709. (taicpu(p).oper[0]^.typ=top_reg) then
  4710. begin
  4711. TransferUsedRegs(TmpUsedRegs);
  4712. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4713. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4714. begin
  4715. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4716. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4717. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4718. RemoveInstruction(hp1);
  4719. result:=true;
  4720. end;
  4721. end;
  4722. end;
  4723. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4724. var
  4725. hp1, p_label, p_dist, hp1_dist: tai;
  4726. JumpLabel, JumpLabel_dist: TAsmLabel;
  4727. FirstValue, SecondValue: TCGInt;
  4728. TempBool: Boolean;
  4729. begin
  4730. Result := False;
  4731. if (taicpu(p).oper[0]^.typ = top_const) and
  4732. (taicpu(p).oper[0]^.val <> -1) then
  4733. begin
  4734. { Convert unsigned maximum constants to -1 to aid optimisation }
  4735. case taicpu(p).opsize of
  4736. S_B:
  4737. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4738. begin
  4739. taicpu(p).oper[0]^.val := -1;
  4740. Result := True;
  4741. Exit;
  4742. end;
  4743. S_W:
  4744. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4745. begin
  4746. taicpu(p).oper[0]^.val := -1;
  4747. Result := True;
  4748. Exit;
  4749. end;
  4750. S_L:
  4751. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4752. begin
  4753. taicpu(p).oper[0]^.val := -1;
  4754. Result := True;
  4755. Exit;
  4756. end;
  4757. {$ifdef x86_64}
  4758. S_Q:
  4759. { Storing anything greater than $7FFFFFFF is not possible so do
  4760. nothing };
  4761. {$endif x86_64}
  4762. else
  4763. InternalError(2021121001);
  4764. end;
  4765. end;
  4766. if GetNextInstruction(p, hp1) and
  4767. TrySwapMovCmp(p, hp1) then
  4768. begin
  4769. Result := True;
  4770. Exit;
  4771. end;
  4772. if MatchInstruction(hp1, A_Jcc, []) then
  4773. begin
  4774. TempBool := True;
  4775. if DoJumpOptimizations(hp1, TempBool) or
  4776. not TempBool then
  4777. begin
  4778. Result := True;
  4779. if Assigned(hp1) then
  4780. begin
  4781. if (hp1.typ in [ait_align]) then
  4782. SkipAligns(hp1, hp1);
  4783. { CollapseZeroDistJump will be set to the label after the
  4784. jump if it optimises, whether or not it's live or dead }
  4785. if (hp1.typ in [ait_label]) and
  4786. not (tai_label(hp1).labsym.is_used) then
  4787. GetNextInstruction(hp1, hp1);
  4788. end;
  4789. TransferUsedRegs(TmpUsedRegs);
  4790. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4791. if not Assigned(hp1) or
  4792. (
  4793. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4794. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4795. ) then
  4796. begin
  4797. { No more conditional jumps; conditional statement is no longer required }
  4798. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4799. RemoveCurrentP(p);
  4800. end;
  4801. Exit;
  4802. end;
  4803. end;
  4804. { Search for:
  4805. test $x,(reg/ref)
  4806. jne @lbl1
  4807. test $y,(reg/ref) (same register or reference)
  4808. jne @lbl1
  4809. Change to:
  4810. test $(x or y),(reg/ref)
  4811. jne @lbl1
  4812. (Note, this doesn't work with je instead of jne)
  4813. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4814. Also search for:
  4815. test $x,(reg/ref)
  4816. je @lbl1
  4817. test $y,(reg/ref)
  4818. je/jne @lbl2
  4819. If (x or y) = x, then the second jump is deterministic
  4820. }
  4821. if (
  4822. (
  4823. (taicpu(p).oper[0]^.typ = top_const) or
  4824. (
  4825. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4826. (taicpu(p).oper[0]^.typ = top_reg) and
  4827. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4828. )
  4829. ) and
  4830. MatchInstruction(hp1, A_JCC, [])
  4831. ) then
  4832. begin
  4833. if (taicpu(p).oper[0]^.typ = top_reg) and
  4834. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4835. FirstValue := -1
  4836. else
  4837. FirstValue := taicpu(p).oper[0]^.val;
  4838. { If we have several test/jne's in a row, it might be the case that
  4839. the second label doesn't go to the same location, but the one
  4840. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4841. so accommodate for this with a while loop.
  4842. }
  4843. hp1_dist := hp1;
  4844. if GetNextInstruction(hp1, p_dist) and
  4845. (p_dist.typ = ait_instruction) and
  4846. (
  4847. (
  4848. (taicpu(p_dist).opcode = A_TEST) and
  4849. (
  4850. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4851. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4852. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4853. )
  4854. ) or
  4855. (
  4856. { cmp 0,%reg = test %reg,%reg }
  4857. (taicpu(p_dist).opcode = A_CMP) and
  4858. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4859. )
  4860. ) and
  4861. { Make sure the destination operands are actually the same }
  4862. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4863. GetNextInstruction(p_dist, hp1_dist) and
  4864. MatchInstruction(hp1_dist, A_JCC, []) then
  4865. begin
  4866. if
  4867. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4868. (
  4869. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4870. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4871. ) then
  4872. SecondValue := -1
  4873. else
  4874. SecondValue := taicpu(p_dist).oper[0]^.val;
  4875. { If both of the TEST constants are identical, delete the second
  4876. TEST that is unnecessary. }
  4877. if (FirstValue = SecondValue) then
  4878. begin
  4879. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4880. RemoveInstruction(p_dist);
  4881. { Don't let the flags register become deallocated and reallocated between the jumps }
  4882. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4883. Result := True;
  4884. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4885. begin
  4886. { Since the second jump's condition is a subset of the first, we
  4887. know it will never branch because the first jump dominates it.
  4888. Get it out of the way now rather than wait for the jump
  4889. optimisations for a speed boost. }
  4890. if IsJumpToLabel(taicpu(hp1_dist)) then
  4891. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4892. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4893. RemoveInstruction(hp1_dist);
  4894. end
  4895. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4896. begin
  4897. { If the inverse of the first condition is a subset of the second,
  4898. the second one will definitely branch if the first one doesn't }
  4899. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4900. MakeUnconditional(taicpu(hp1_dist));
  4901. RemoveDeadCodeAfterJump(hp1_dist);
  4902. end;
  4903. Exit;
  4904. end;
  4905. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4906. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4907. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4908. then the second jump will never branch, so it can also be
  4909. removed regardless of where it goes }
  4910. (
  4911. (FirstValue = -1) or
  4912. (SecondValue = -1) or
  4913. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4914. ) then
  4915. begin
  4916. { Same jump location... can be a register since nothing's changed }
  4917. { If any of the entries are equivalent to test %reg,%reg, then the
  4918. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4919. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4920. if IsJumpToLabel(taicpu(hp1_dist)) then
  4921. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4922. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4923. RemoveInstruction(hp1_dist);
  4924. { Only remove the second test if no jumps or other conditional instructions follow }
  4925. TransferUsedRegs(TmpUsedRegs);
  4926. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4927. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4928. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4929. RemoveInstruction(p_dist);
  4930. Result := True;
  4931. Exit;
  4932. end;
  4933. end;
  4934. end;
  4935. { Search for:
  4936. test %reg,%reg
  4937. j(c1) @lbl1
  4938. ...
  4939. @lbl:
  4940. test %reg,%reg (same register)
  4941. j(c2) @lbl2
  4942. If c2 is a subset of c1, change to:
  4943. test %reg,%reg
  4944. j(c1) @lbl2
  4945. (@lbl1 may become a dead label as a result)
  4946. }
  4947. if (taicpu(p).oper[1]^.typ = top_reg) and
  4948. (taicpu(p).oper[0]^.typ = top_reg) and
  4949. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4950. MatchInstruction(hp1, A_JCC, []) and
  4951. IsJumpToLabel(taicpu(hp1)) then
  4952. begin
  4953. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4954. p_label := nil;
  4955. if Assigned(JumpLabel) then
  4956. p_label := getlabelwithsym(JumpLabel);
  4957. if Assigned(p_label) and
  4958. GetNextInstruction(p_label, p_dist) and
  4959. MatchInstruction(p_dist, A_TEST, []) and
  4960. { It's fine if the second test uses smaller sub-registers }
  4961. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4962. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4963. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4964. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4965. GetNextInstruction(p_dist, hp1_dist) and
  4966. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4967. begin
  4968. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4969. if JumpLabel = JumpLabel_dist then
  4970. { This is an infinite loop }
  4971. Exit;
  4972. { Best optimisation when the first condition is a subset (or equal) of the second }
  4973. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4974. begin
  4975. { Any registers used here will already be allocated }
  4976. if Assigned(JumpLabel) then
  4977. JumpLabel.DecRefs;
  4978. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4979. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4980. Result := True;
  4981. Exit;
  4982. end;
  4983. end;
  4984. end;
  4985. end;
  4986. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4987. var
  4988. hp1, hp2: tai;
  4989. ActiveReg: TRegister;
  4990. OldOffset: asizeint;
  4991. ThisConst: TCGInt;
  4992. function RegDeallocated: Boolean;
  4993. begin
  4994. TransferUsedRegs(TmpUsedRegs);
  4995. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4996. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4997. end;
  4998. begin
  4999. result:=false;
  5000. hp1 := nil;
  5001. { replace
  5002. addX const,%reg1
  5003. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5004. dealloc %reg1
  5005. by
  5006. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5007. }
  5008. if MatchOpType(taicpu(p),top_const,top_reg) then
  5009. begin
  5010. ActiveReg := taicpu(p).oper[1]^.reg;
  5011. { Ensures the entire register was updated }
  5012. if (taicpu(p).opsize >= S_L) and
  5013. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5014. MatchInstruction(hp1,A_LEA,[]) and
  5015. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5016. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5017. (
  5018. { Cover the case where the register in the reference is also the destination register }
  5019. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5020. (
  5021. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5022. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5023. RegDeallocated
  5024. )
  5025. ) then
  5026. begin
  5027. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5028. {$push}
  5029. {$R-}{$Q-}
  5030. { Explicitly disable overflow checking for these offset calculation
  5031. as those do not matter for the final result }
  5032. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5033. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5034. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5035. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5036. {$pop}
  5037. {$ifdef x86_64}
  5038. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5039. begin
  5040. { Overflow; abort }
  5041. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5042. end
  5043. else
  5044. {$endif x86_64}
  5045. begin
  5046. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5047. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5048. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5049. RemoveCurrentP(p, hp1)
  5050. else
  5051. RemoveCurrentP(p);
  5052. result:=true;
  5053. Exit;
  5054. end;
  5055. end;
  5056. if (
  5057. { Save calling GetNextInstructionUsingReg again }
  5058. Assigned(hp1) or
  5059. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5060. ) and
  5061. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5062. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5063. begin
  5064. if taicpu(hp1).oper[0]^.typ = top_const then
  5065. begin
  5066. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5067. if taicpu(hp1).opcode = A_ADD then
  5068. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5069. else
  5070. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5071. Result := True;
  5072. { Handle any overflows }
  5073. case taicpu(p).opsize of
  5074. S_B:
  5075. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5076. S_W:
  5077. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5078. S_L:
  5079. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5080. {$ifdef x86_64}
  5081. S_Q:
  5082. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5083. { Overflow; abort }
  5084. Result := False
  5085. else
  5086. taicpu(p).oper[0]^.val := ThisConst;
  5087. {$endif x86_64}
  5088. else
  5089. InternalError(2021102610);
  5090. end;
  5091. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5092. if Result then
  5093. begin
  5094. if (taicpu(p).oper[0]^.val < 0) and
  5095. (
  5096. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5097. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5098. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5099. ) then
  5100. begin
  5101. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5102. taicpu(p).opcode := A_SUB;
  5103. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5104. end
  5105. else
  5106. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5107. RemoveInstruction(hp1);
  5108. end;
  5109. end
  5110. else
  5111. begin
  5112. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5113. TransferUsedRegs(TmpUsedRegs);
  5114. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5115. hp2 := p;
  5116. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5117. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5118. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5119. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5120. begin
  5121. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5122. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5123. Asml.Remove(p);
  5124. Asml.InsertAfter(p, hp1);
  5125. p := hp1;
  5126. Result := True;
  5127. Exit;
  5128. end;
  5129. end;
  5130. end;
  5131. if DoArithCombineOpt(p) then
  5132. Result:=true;
  5133. end;
  5134. end;
  5135. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5136. var
  5137. hp1, hp2: tai;
  5138. ref: Integer;
  5139. saveref: treference;
  5140. offsetcalc: Int64;
  5141. TempReg: TRegister;
  5142. Multiple: TCGInt;
  5143. Adjacent, IntermediateRegDiscarded: Boolean;
  5144. begin
  5145. Result:=false;
  5146. { play save and throw an error if LEA uses a seg register prefix,
  5147. this is most likely an error somewhere else }
  5148. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5149. internalerror(2022022001);
  5150. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5151. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5152. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5153. (
  5154. { do not mess with leas accessing the stack pointer
  5155. unless it's a null operation }
  5156. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5157. (
  5158. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5159. (taicpu(p).oper[0]^.ref^.offset = 0)
  5160. )
  5161. ) and
  5162. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5163. begin
  5164. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5165. begin
  5166. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5167. begin
  5168. taicpu(p).opcode := A_MOV;
  5169. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5170. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5171. end
  5172. else
  5173. begin
  5174. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5175. RemoveCurrentP(p);
  5176. end;
  5177. Result:=true;
  5178. exit;
  5179. end
  5180. else if (
  5181. { continue to use lea to adjust the stack pointer,
  5182. it is the recommended way, but only if not optimizing for size }
  5183. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5184. (cs_opt_size in current_settings.optimizerswitches)
  5185. ) and
  5186. { If the flags register is in use, don't change the instruction
  5187. to an ADD otherwise this will scramble the flags. [Kit] }
  5188. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5189. ConvertLEA(taicpu(p)) then
  5190. begin
  5191. Result:=true;
  5192. exit;
  5193. end;
  5194. end;
  5195. { Don't optimise if the stack or frame pointer is the destination register }
  5196. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5197. Exit;
  5198. if GetNextInstruction(p,hp1) and
  5199. (hp1.typ=ait_instruction) then
  5200. begin
  5201. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5202. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5203. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5204. begin
  5205. TransferUsedRegs(TmpUsedRegs);
  5206. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5207. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5208. begin
  5209. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5210. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5211. RemoveInstruction(hp1);
  5212. result:=true;
  5213. exit;
  5214. end;
  5215. end;
  5216. { changes
  5217. lea <ref1>, reg1
  5218. <op> ...,<ref. with reg1>,...
  5219. to
  5220. <op> ...,<ref1>,... }
  5221. { find a reference which uses reg1 }
  5222. 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
  5223. ref:=0
  5224. 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
  5225. ref:=1
  5226. else
  5227. ref:=-1;
  5228. if (ref<>-1) and
  5229. { reg1 must be either the base or the index }
  5230. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5231. begin
  5232. { reg1 can be removed from the reference }
  5233. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5234. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5235. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5236. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5237. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5238. else
  5239. Internalerror(2019111201);
  5240. { check if the can insert all data of the lea into the second instruction }
  5241. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5242. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5243. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5244. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5245. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5246. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5247. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5248. {$ifdef x86_64}
  5249. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5250. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5251. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5252. )
  5253. {$endif x86_64}
  5254. then
  5255. begin
  5256. { reg1 might not used by the second instruction after it is remove from the reference }
  5257. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5258. begin
  5259. TransferUsedRegs(TmpUsedRegs);
  5260. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5261. { reg1 is not updated so it might not be used afterwards }
  5262. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5263. begin
  5264. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5265. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5266. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5267. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5268. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5269. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5270. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5271. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5272. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5273. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5274. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5275. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5276. RemoveCurrentP(p, hp1);
  5277. result:=true;
  5278. exit;
  5279. end
  5280. end;
  5281. end;
  5282. { recover }
  5283. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5284. end;
  5285. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5286. if Adjacent or
  5287. { Check further ahead (up to 2 instructions ahead for -O2) }
  5288. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5289. begin
  5290. { Check common LEA/LEA conditions }
  5291. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5292. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5293. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5294. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5295. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5296. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5297. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5298. (
  5299. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5300. calling it (since it calls GetNextInstruction) }
  5301. Adjacent or
  5302. (
  5303. (
  5304. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5305. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5306. ) and (
  5307. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5308. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5309. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5310. )
  5311. )
  5312. ) then
  5313. begin
  5314. TransferUsedRegs(TmpUsedRegs);
  5315. hp2 := p;
  5316. repeat
  5317. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5318. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5319. IntermediateRegDiscarded :=
  5320. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5321. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5322. { changes
  5323. lea offset1(regX,scale), reg1
  5324. lea offset2(reg1,reg1), reg2
  5325. to
  5326. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5327. and
  5328. lea offset1(regX,scale1), reg1
  5329. lea offset2(reg1,scale2), reg2
  5330. to
  5331. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5332. and
  5333. lea offset1(regX,scale1), reg1
  5334. lea offset2(reg3,reg1,scale2), reg2
  5335. to
  5336. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5337. ... so long as the final scale does not exceed 8
  5338. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5339. }
  5340. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5341. (
  5342. { Don't optimise if size is a concern and the intermediate register remains in use }
  5343. IntermediateRegDiscarded or
  5344. not (cs_opt_size in current_settings.optimizerswitches)
  5345. ) and
  5346. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5347. (
  5348. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5349. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5350. ) and (
  5351. (
  5352. { lea (reg1,scale2), reg2 variant }
  5353. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5354. (
  5355. Adjacent or
  5356. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5357. ) and
  5358. (
  5359. (
  5360. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5361. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5362. ) or (
  5363. { lea (regX,regX), reg1 variant }
  5364. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5365. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5366. )
  5367. )
  5368. ) or (
  5369. { lea (reg1,reg1), reg1 variant }
  5370. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5371. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5372. )
  5373. ) then
  5374. begin
  5375. { Make everything homogeneous to make calculations easier }
  5376. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5377. begin
  5378. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5379. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5380. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5381. else
  5382. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5383. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5384. end;
  5385. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5386. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5387. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5388. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5389. begin
  5390. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5391. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5392. begin
  5393. { Put the register to change in the index register }
  5394. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5395. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5396. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5397. end;
  5398. if (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5399. begin
  5400. { Just to prevent miscalculations }
  5401. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5402. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5403. else
  5404. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5405. end
  5406. else
  5407. begin
  5408. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5409. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5410. end;
  5411. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5412. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(p).oper[0]^.ref^.scalefactor, 1));
  5413. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5414. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5415. if IntermediateRegDiscarded then
  5416. begin
  5417. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5418. RemoveCurrentP(p);
  5419. end
  5420. else
  5421. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5422. result:=true;
  5423. exit;
  5424. end;
  5425. end;
  5426. { changes
  5427. lea offset1(regX), reg1
  5428. lea offset2(reg1), reg2
  5429. to
  5430. lea offset1+offset2(regX), reg2 }
  5431. if (
  5432. { Don't optimise if size is a concern and the intermediate register remains in use }
  5433. IntermediateRegDiscarded or
  5434. not (cs_opt_size in current_settings.optimizerswitches)
  5435. ) and
  5436. (
  5437. (
  5438. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5439. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5440. ) or (
  5441. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5442. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5443. (
  5444. (
  5445. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5446. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5447. ) or (
  5448. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5449. (
  5450. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5451. (
  5452. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5453. (
  5454. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5455. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5456. )
  5457. )
  5458. )
  5459. )
  5460. )
  5461. )
  5462. ) then
  5463. begin
  5464. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5465. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5466. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5467. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5468. begin
  5469. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5470. begin
  5471. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5472. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5473. { if the register is used as index and base, we have to increase for base as well
  5474. and adapt base }
  5475. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5476. begin
  5477. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5478. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5479. end;
  5480. end
  5481. else
  5482. begin
  5483. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5484. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5485. end;
  5486. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5487. begin
  5488. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5489. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5490. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5491. end;
  5492. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5493. if IntermediateRegDiscarded then
  5494. begin
  5495. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5496. RemoveCurrentP(p);
  5497. end
  5498. else
  5499. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5500. result:=true;
  5501. exit;
  5502. end;
  5503. end;
  5504. end;
  5505. { Change:
  5506. leal/q $x(%reg1),%reg2
  5507. ...
  5508. shll/q $y,%reg2
  5509. To:
  5510. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5511. }
  5512. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5513. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5514. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5515. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5516. (taicpu(hp1).oper[0]^.val <= 3) then
  5517. begin
  5518. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5519. TransferUsedRegs(TmpUsedRegs);
  5520. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5521. if
  5522. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5523. (this works even if scalefactor is zero) }
  5524. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5525. { Ensure offset doesn't go out of bounds }
  5526. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5527. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5528. (
  5529. (
  5530. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5531. (
  5532. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5533. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5534. (
  5535. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5536. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5537. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5538. )
  5539. )
  5540. ) or (
  5541. (
  5542. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5543. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5544. ) and
  5545. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5546. )
  5547. ) then
  5548. begin
  5549. repeat
  5550. with taicpu(p).oper[0]^.ref^ do
  5551. begin
  5552. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5553. if index = base then
  5554. begin
  5555. if Multiple > 4 then
  5556. { Optimisation will no longer work because resultant
  5557. scale factor will exceed 8 }
  5558. Break;
  5559. base := NR_NO;
  5560. scalefactor := 2;
  5561. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5562. end
  5563. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5564. begin
  5565. { Scale factor only works on the index register }
  5566. index := base;
  5567. base := NR_NO;
  5568. end;
  5569. { For safety }
  5570. if scalefactor <= 1 then
  5571. begin
  5572. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5573. scalefactor := Multiple;
  5574. end
  5575. else
  5576. begin
  5577. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5578. scalefactor := scalefactor * Multiple;
  5579. end;
  5580. offset := offset * Multiple;
  5581. end;
  5582. RemoveInstruction(hp1);
  5583. Result := True;
  5584. Exit;
  5585. { This repeat..until loop exists for the benefit of Break }
  5586. until True;
  5587. end;
  5588. end;
  5589. end;
  5590. end;
  5591. end;
  5592. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5593. var
  5594. hp1 : tai;
  5595. SubInstr: Boolean;
  5596. ThisConst: TCGInt;
  5597. const
  5598. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5599. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5600. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5601. begin
  5602. Result := False;
  5603. if taicpu(p).oper[0]^.typ <> top_const then
  5604. { Should have been confirmed before calling }
  5605. InternalError(2021102601);
  5606. SubInstr := (taicpu(p).opcode = A_SUB);
  5607. if GetLastInstruction(p, hp1) and
  5608. (hp1.typ = ait_instruction) and
  5609. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5610. begin
  5611. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5612. { Bad size }
  5613. InternalError(2022042001);
  5614. case taicpu(hp1).opcode Of
  5615. A_INC:
  5616. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5617. begin
  5618. if SubInstr then
  5619. ThisConst := taicpu(p).oper[0]^.val - 1
  5620. else
  5621. ThisConst := taicpu(p).oper[0]^.val + 1;
  5622. end
  5623. else
  5624. Exit;
  5625. A_DEC:
  5626. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5627. begin
  5628. if SubInstr then
  5629. ThisConst := taicpu(p).oper[0]^.val + 1
  5630. else
  5631. ThisConst := taicpu(p).oper[0]^.val - 1;
  5632. end
  5633. else
  5634. Exit;
  5635. A_SUB:
  5636. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5637. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5638. begin
  5639. if SubInstr then
  5640. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5641. else
  5642. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5643. end
  5644. else
  5645. Exit;
  5646. A_ADD:
  5647. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5648. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5649. begin
  5650. if SubInstr then
  5651. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5652. else
  5653. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5654. end
  5655. else
  5656. Exit;
  5657. else
  5658. Exit;
  5659. end;
  5660. { Check that the values are in range }
  5661. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5662. { Overflow; abort }
  5663. Exit;
  5664. if (ThisConst = 0) then
  5665. begin
  5666. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5667. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5668. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5669. RemoveInstruction(hp1);
  5670. hp1 := tai(p.next);
  5671. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5672. if not GetLastInstruction(hp1, p) then
  5673. p := hp1;
  5674. end
  5675. else
  5676. begin
  5677. if taicpu(hp1).opercnt=1 then
  5678. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5679. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5680. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5681. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5682. else
  5683. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5684. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5685. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5686. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5687. RemoveInstruction(hp1);
  5688. taicpu(p).loadconst(0, ThisConst);
  5689. end;
  5690. Result := True;
  5691. end;
  5692. end;
  5693. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5694. var
  5695. hp2: tai;
  5696. begin
  5697. Result := False;
  5698. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5699. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5700. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5701. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5702. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5703. (
  5704. (
  5705. (taicpu(hp1).opcode = A_TEST)
  5706. ) or (
  5707. (taicpu(hp1).opcode = A_CMP) and
  5708. { A sanity check more than anything }
  5709. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5710. )
  5711. ) then
  5712. begin
  5713. { change
  5714. mov mem, %reg
  5715. ...
  5716. cmp/test x, %reg / test %reg,%reg
  5717. (reg deallocated)
  5718. to
  5719. cmp/test x, mem / cmp 0, mem
  5720. }
  5721. TransferUsedRegs(TmpUsedRegs);
  5722. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5723. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5724. begin
  5725. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5726. if (taicpu(hp1).opcode = A_TEST) and
  5727. (
  5728. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5729. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5730. ) then
  5731. begin
  5732. taicpu(hp1).opcode := A_CMP;
  5733. taicpu(hp1).loadconst(0, 0);
  5734. end;
  5735. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5736. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5737. RemoveCurrentP(p);
  5738. if (p <> hp1) then
  5739. begin
  5740. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5741. hp2 := p;
  5742. repeat
  5743. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5744. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5745. end;
  5746. { Make sure the flags are allocated across the CMP instruction }
  5747. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5748. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  5749. Result := True;
  5750. Exit;
  5751. end;
  5752. end;
  5753. end;
  5754. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5755. var
  5756. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5757. ThisReg, SecondReg: TRegister;
  5758. JumpLoc: TAsmLabel;
  5759. NewSize: TOpSize;
  5760. begin
  5761. Result := False;
  5762. {
  5763. Convert:
  5764. j<c> .L1
  5765. .L2:
  5766. mov 1,reg
  5767. jmp .L3 (or ret, although it might not be a RET yet)
  5768. .L1:
  5769. mov 0,reg
  5770. jmp .L3 (or ret)
  5771. ( As long as .L3 <> .L1 or .L2)
  5772. To:
  5773. mov 0,reg
  5774. set<not(c)> reg
  5775. jmp .L3 (or ret)
  5776. .L2:
  5777. mov 1,reg
  5778. jmp .L3 (or ret)
  5779. .L1:
  5780. mov 0,reg
  5781. jmp .L3 (or ret)
  5782. }
  5783. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5784. Exit;
  5785. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5786. if GetNextInstruction(hp_label, hp2) and
  5787. MatchInstruction(hp2,A_MOV,[]) and
  5788. (taicpu(hp2).oper[0]^.typ = top_const) and
  5789. (
  5790. (
  5791. (taicpu(hp2).oper[1]^.typ = top_reg)
  5792. {$ifdef i386}
  5793. { Under i386, ESI, EDI, EBP and ESP
  5794. don't have an 8-bit representation }
  5795. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5796. {$endif i386}
  5797. ) or (
  5798. {$ifdef i386}
  5799. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5800. {$endif i386}
  5801. (taicpu(hp2).opsize = S_B)
  5802. )
  5803. ) and
  5804. GetNextInstruction(hp2, hp3) and
  5805. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5806. (
  5807. (taicpu(hp3).opcode=A_RET) or
  5808. (
  5809. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5810. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5811. )
  5812. ) and
  5813. GetNextInstruction(hp3, hp4) and
  5814. SkipAligns(hp4, hp4) and
  5815. (hp4.typ=ait_label) and
  5816. (tai_label(hp4).labsym=JumpLoc) and
  5817. (
  5818. not (cs_opt_size in current_settings.optimizerswitches) or
  5819. { If the initial jump is the label's only reference, then it will
  5820. become a dead label if the other conditions are met and hence
  5821. remove at least 2 instructions, including a jump }
  5822. (JumpLoc.getrefs = 1)
  5823. ) and
  5824. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5825. that will be optimised out }
  5826. GetNextInstruction(hp4, hp5) and
  5827. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5828. (taicpu(hp5).oper[0]^.typ = top_const) and
  5829. (
  5830. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5831. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5832. ) and
  5833. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5834. GetNextInstruction(hp5,hp6) and
  5835. (
  5836. (hp6.typ<>ait_label) or
  5837. SkipLabels(hp6, hp6)
  5838. ) and
  5839. (hp6.typ=ait_instruction) then
  5840. begin
  5841. { First, let's look at the two jumps that are hp3 and hp6 }
  5842. if not
  5843. (
  5844. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5845. (
  5846. (taicpu(hp6).opcode=A_RET) or
  5847. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5848. )
  5849. ) then
  5850. { If condition is False, then the JMP/RET instructions matched conventionally }
  5851. begin
  5852. { See if one of the jumps can be instantly converted into a RET }
  5853. if (taicpu(hp3).opcode=A_JMP) then
  5854. begin
  5855. { Reuse hp5 }
  5856. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5857. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5858. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5859. Exit;
  5860. if MatchInstruction(hp5, A_RET, []) then
  5861. begin
  5862. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5863. ConvertJumpToRET(hp3, hp5);
  5864. Result := True;
  5865. end
  5866. else
  5867. Exit;
  5868. end;
  5869. if (taicpu(hp6).opcode=A_JMP) then
  5870. begin
  5871. { Reuse hp5 }
  5872. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5873. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5874. Exit;
  5875. if MatchInstruction(hp5, A_RET, []) then
  5876. begin
  5877. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5878. ConvertJumpToRET(hp6, hp5);
  5879. Result := True;
  5880. end
  5881. else
  5882. Exit;
  5883. end;
  5884. if not
  5885. (
  5886. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5887. (
  5888. (taicpu(hp6).opcode=A_RET) or
  5889. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5890. )
  5891. ) then
  5892. { Still doesn't match }
  5893. Exit;
  5894. end;
  5895. if (taicpu(hp2).oper[0]^.val = 1) then
  5896. begin
  5897. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5898. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5899. end
  5900. else
  5901. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5902. if taicpu(hp2).opsize=S_B then
  5903. begin
  5904. if taicpu(hp2).oper[1]^.typ = top_reg then
  5905. begin
  5906. SecondReg := taicpu(hp2).oper[1]^.reg;
  5907. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5908. end
  5909. else
  5910. begin
  5911. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5912. SecondReg := NR_NO;
  5913. end;
  5914. hp_pos := p;
  5915. hp_allocstart := hp4;
  5916. end
  5917. else
  5918. begin
  5919. { Will be a register because the size can't be S_B otherwise }
  5920. SecondReg:=taicpu(hp2).oper[1]^.reg;
  5921. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  5922. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5923. if (cs_opt_size in current_settings.optimizerswitches) then
  5924. begin
  5925. { Favour using MOVZX when optimising for size }
  5926. case taicpu(hp2).opsize of
  5927. S_W:
  5928. NewSize := S_BW;
  5929. S_L:
  5930. NewSize := S_BL;
  5931. {$ifdef x86_64}
  5932. S_Q:
  5933. begin
  5934. NewSize := S_BL;
  5935. { Will implicitly zero-extend to 64-bit }
  5936. setsubreg(SecondReg, R_SUBD);
  5937. end;
  5938. {$endif x86_64}
  5939. else
  5940. InternalError(2022101301);
  5941. end;
  5942. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  5943. { Inserting it right before p will guarantee that the flags are also tracked }
  5944. Asml.InsertBefore(hp5, p);
  5945. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  5946. hp_pos := hp5;
  5947. hp_allocstart := hp4;
  5948. end
  5949. else
  5950. begin
  5951. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  5952. { Inserting it right before p will guarantee that the flags are also tracked }
  5953. Asml.InsertBefore(hp5, p);
  5954. hp_pos := p;
  5955. hp_allocstart := hp5;
  5956. end;
  5957. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  5958. end;
  5959. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  5960. taicpu(hp4).condition := taicpu(p).condition;
  5961. asml.InsertBefore(hp4, hp_pos);
  5962. if taicpu(hp3).is_jmp then
  5963. begin
  5964. JumpLoc.decrefs;
  5965. MakeUnconditional(taicpu(p));
  5966. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5967. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5968. end
  5969. else
  5970. ConvertJumpToRET(p, hp3);
  5971. if SecondReg <> NR_NO then
  5972. { Ensure the destination register is allocated over this region }
  5973. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  5974. if (JumpLoc.getrefs = 0) then
  5975. RemoveDeadCodeAfterJump(hp3);
  5976. Result:=true;
  5977. exit;
  5978. end;
  5979. end;
  5980. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5981. var
  5982. hp1, hp2: tai;
  5983. ActiveReg: TRegister;
  5984. OldOffset: asizeint;
  5985. ThisConst: TCGInt;
  5986. function RegDeallocated: Boolean;
  5987. begin
  5988. TransferUsedRegs(TmpUsedRegs);
  5989. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5990. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5991. end;
  5992. begin
  5993. Result:=false;
  5994. hp1 := nil;
  5995. { replace
  5996. subX const,%reg1
  5997. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5998. dealloc %reg1
  5999. by
  6000. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6001. }
  6002. if MatchOpType(taicpu(p),top_const,top_reg) then
  6003. begin
  6004. ActiveReg := taicpu(p).oper[1]^.reg;
  6005. { Ensures the entire register was updated }
  6006. if (taicpu(p).opsize >= S_L) and
  6007. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6008. MatchInstruction(hp1,A_LEA,[]) and
  6009. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6010. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6011. (
  6012. { Cover the case where the register in the reference is also the destination register }
  6013. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6014. (
  6015. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6016. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6017. RegDeallocated
  6018. )
  6019. ) then
  6020. begin
  6021. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6022. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6023. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6024. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6025. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6026. {$ifdef x86_64}
  6027. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6028. begin
  6029. { Overflow; abort }
  6030. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6031. end
  6032. else
  6033. {$endif x86_64}
  6034. begin
  6035. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6036. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6037. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6038. RemoveCurrentP(p, hp1)
  6039. else
  6040. RemoveCurrentP(p);
  6041. result:=true;
  6042. Exit;
  6043. end;
  6044. end;
  6045. if (
  6046. { Save calling GetNextInstructionUsingReg again }
  6047. Assigned(hp1) or
  6048. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6049. ) and
  6050. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6051. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6052. begin
  6053. if taicpu(hp1).oper[0]^.typ = top_const then
  6054. begin
  6055. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6056. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6057. Result := True;
  6058. { Handle any overflows }
  6059. case taicpu(p).opsize of
  6060. S_B:
  6061. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6062. S_W:
  6063. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6064. S_L:
  6065. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6066. {$ifdef x86_64}
  6067. S_Q:
  6068. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6069. { Overflow; abort }
  6070. Result := False
  6071. else
  6072. taicpu(p).oper[0]^.val := ThisConst;
  6073. {$endif x86_64}
  6074. else
  6075. InternalError(2021102611);
  6076. end;
  6077. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6078. if Result then
  6079. begin
  6080. if (taicpu(p).oper[0]^.val < 0) and
  6081. (
  6082. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6083. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6084. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6085. ) then
  6086. begin
  6087. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6088. taicpu(p).opcode := A_SUB;
  6089. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6090. end
  6091. else
  6092. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6093. RemoveInstruction(hp1);
  6094. end;
  6095. end
  6096. else
  6097. begin
  6098. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6099. TransferUsedRegs(TmpUsedRegs);
  6100. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6101. hp2 := p;
  6102. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6103. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6104. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6105. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6106. begin
  6107. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6108. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6109. Asml.Remove(p);
  6110. Asml.InsertAfter(p, hp1);
  6111. p := hp1;
  6112. Result := True;
  6113. Exit;
  6114. end;
  6115. end;
  6116. end;
  6117. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6118. { * change "sub/add const1, reg" or "dec reg" followed by
  6119. "sub const2, reg" to one "sub ..., reg" }
  6120. {$ifdef i386}
  6121. if (taicpu(p).oper[0]^.val = 2) and
  6122. (ActiveReg = NR_ESP) and
  6123. { Don't do the sub/push optimization if the sub }
  6124. { comes from setting up the stack frame (JM) }
  6125. (not(GetLastInstruction(p,hp1)) or
  6126. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6127. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6128. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6129. begin
  6130. hp1 := tai(p.next);
  6131. while Assigned(hp1) and
  6132. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6133. not RegReadByInstruction(NR_ESP,hp1) and
  6134. not RegModifiedByInstruction(NR_ESP,hp1) do
  6135. hp1 := tai(hp1.next);
  6136. if Assigned(hp1) and
  6137. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6138. begin
  6139. taicpu(hp1).changeopsize(S_L);
  6140. if taicpu(hp1).oper[0]^.typ=top_reg then
  6141. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6142. hp1 := tai(p.next);
  6143. RemoveCurrentp(p, hp1);
  6144. Result:=true;
  6145. exit;
  6146. end;
  6147. end;
  6148. {$endif i386}
  6149. if DoArithCombineOpt(p) then
  6150. Result:=true;
  6151. end;
  6152. end;
  6153. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6154. var
  6155. TmpBool1,TmpBool2 : Boolean;
  6156. tmpref : treference;
  6157. hp1,hp2: tai;
  6158. mask, shiftval: tcgint;
  6159. begin
  6160. Result:=false;
  6161. { All these optimisations work on "shl/sal const,%reg" }
  6162. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6163. Exit;
  6164. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6165. (taicpu(p).oper[0]^.val <= 3) then
  6166. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6167. begin
  6168. { should we check the next instruction? }
  6169. TmpBool1 := True;
  6170. { have we found an add/sub which could be
  6171. integrated in the lea? }
  6172. TmpBool2 := False;
  6173. reference_reset(tmpref,2,[]);
  6174. TmpRef.index := taicpu(p).oper[1]^.reg;
  6175. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6176. while TmpBool1 and
  6177. GetNextInstruction(p, hp1) and
  6178. (tai(hp1).typ = ait_instruction) and
  6179. ((((taicpu(hp1).opcode = A_ADD) or
  6180. (taicpu(hp1).opcode = A_SUB)) and
  6181. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6182. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6183. (((taicpu(hp1).opcode = A_INC) or
  6184. (taicpu(hp1).opcode = A_DEC)) and
  6185. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6186. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6187. ((taicpu(hp1).opcode = A_LEA) and
  6188. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6189. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6190. (not GetNextInstruction(hp1,hp2) or
  6191. not instrReadsFlags(hp2)) Do
  6192. begin
  6193. TmpBool1 := False;
  6194. if taicpu(hp1).opcode=A_LEA then
  6195. begin
  6196. if (TmpRef.base = NR_NO) and
  6197. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6198. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6199. { Segment register isn't a concern here }
  6200. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6201. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6202. begin
  6203. TmpBool1 := True;
  6204. TmpBool2 := True;
  6205. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6206. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6207. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6208. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6209. RemoveInstruction(hp1);
  6210. end
  6211. end
  6212. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6213. begin
  6214. TmpBool1 := True;
  6215. TmpBool2 := True;
  6216. case taicpu(hp1).opcode of
  6217. A_ADD:
  6218. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6219. A_SUB:
  6220. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6221. else
  6222. internalerror(2019050536);
  6223. end;
  6224. RemoveInstruction(hp1);
  6225. end
  6226. else
  6227. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6228. (((taicpu(hp1).opcode = A_ADD) and
  6229. (TmpRef.base = NR_NO)) or
  6230. (taicpu(hp1).opcode = A_INC) or
  6231. (taicpu(hp1).opcode = A_DEC)) then
  6232. begin
  6233. TmpBool1 := True;
  6234. TmpBool2 := True;
  6235. case taicpu(hp1).opcode of
  6236. A_ADD:
  6237. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6238. A_INC:
  6239. inc(TmpRef.offset);
  6240. A_DEC:
  6241. dec(TmpRef.offset);
  6242. else
  6243. internalerror(2019050535);
  6244. end;
  6245. RemoveInstruction(hp1);
  6246. end;
  6247. end;
  6248. if TmpBool2
  6249. {$ifndef x86_64}
  6250. or
  6251. ((current_settings.optimizecputype < cpu_Pentium2) and
  6252. (taicpu(p).oper[0]^.val <= 3) and
  6253. not(cs_opt_size in current_settings.optimizerswitches))
  6254. {$endif x86_64}
  6255. then
  6256. begin
  6257. if not(TmpBool2) and
  6258. (taicpu(p).oper[0]^.val=1) then
  6259. begin
  6260. taicpu(p).opcode := A_ADD;
  6261. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6262. end
  6263. else
  6264. begin
  6265. taicpu(p).opcode := A_LEA;
  6266. taicpu(p).loadref(0, TmpRef);
  6267. end;
  6268. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6269. Result := True;
  6270. end;
  6271. end
  6272. {$ifndef x86_64}
  6273. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6274. begin
  6275. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6276. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6277. (unlike shl, which is only Tairable in the U pipe) }
  6278. if taicpu(p).oper[0]^.val=1 then
  6279. begin
  6280. taicpu(p).opcode := A_ADD;
  6281. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6282. Result := True;
  6283. end
  6284. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6285. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6286. else if (taicpu(p).opsize = S_L) and
  6287. (taicpu(p).oper[0]^.val<= 3) then
  6288. begin
  6289. reference_reset(tmpref,2,[]);
  6290. TmpRef.index := taicpu(p).oper[1]^.reg;
  6291. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6292. taicpu(p).opcode := A_LEA;
  6293. taicpu(p).loadref(0, TmpRef);
  6294. Result := True;
  6295. end;
  6296. end
  6297. {$endif x86_64}
  6298. else if
  6299. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6300. (
  6301. (
  6302. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6303. SetAndTest(hp1, hp2)
  6304. {$ifdef x86_64}
  6305. ) or
  6306. (
  6307. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6308. GetNextInstruction(hp1, hp2) and
  6309. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6310. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6311. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6312. {$endif x86_64}
  6313. )
  6314. ) and
  6315. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6316. begin
  6317. { Change:
  6318. shl x, %reg1
  6319. mov -(1<<x), %reg2
  6320. and %reg2, %reg1
  6321. Or:
  6322. shl x, %reg1
  6323. and -(1<<x), %reg1
  6324. To just:
  6325. shl x, %reg1
  6326. Since the and operation only zeroes bits that are already zero from the shl operation
  6327. }
  6328. case taicpu(p).oper[0]^.val of
  6329. 8:
  6330. mask:=$FFFFFFFFFFFFFF00;
  6331. 16:
  6332. mask:=$FFFFFFFFFFFF0000;
  6333. 32:
  6334. mask:=$FFFFFFFF00000000;
  6335. 63:
  6336. { Constant pre-calculated to prevent overflow errors with Int64 }
  6337. mask:=$8000000000000000;
  6338. else
  6339. begin
  6340. if taicpu(p).oper[0]^.val >= 64 then
  6341. { Shouldn't happen realistically, since the register
  6342. is guaranteed to be set to zero at this point }
  6343. mask := 0
  6344. else
  6345. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6346. end;
  6347. end;
  6348. if taicpu(hp1).oper[0]^.val = mask then
  6349. begin
  6350. { Everything checks out, perform the optimisation, as long as
  6351. the FLAGS register isn't being used}
  6352. TransferUsedRegs(TmpUsedRegs);
  6353. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6354. {$ifdef x86_64}
  6355. if (hp1 <> hp2) then
  6356. begin
  6357. { "shl/mov/and" version }
  6358. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6359. { Don't do the optimisation if the FLAGS register is in use }
  6360. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6361. begin
  6362. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6363. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6364. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6365. begin
  6366. RemoveInstruction(hp1);
  6367. Result := True;
  6368. end;
  6369. { Only set Result to True if the 'mov' instruction was removed }
  6370. RemoveInstruction(hp2);
  6371. end;
  6372. end
  6373. else
  6374. {$endif x86_64}
  6375. begin
  6376. { "shl/and" version }
  6377. { Don't do the optimisation if the FLAGS register is in use }
  6378. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6379. begin
  6380. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6381. RemoveInstruction(hp1);
  6382. Result := True;
  6383. end;
  6384. end;
  6385. Exit;
  6386. end
  6387. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6388. begin
  6389. { Even if the mask doesn't allow for its removal, we might be
  6390. able to optimise the mask for the "shl/and" version, which
  6391. may permit other peephole optimisations }
  6392. {$ifdef DEBUG_AOPTCPU}
  6393. mask := taicpu(hp1).oper[0]^.val and mask;
  6394. if taicpu(hp1).oper[0]^.val <> mask then
  6395. begin
  6396. DebugMsg(
  6397. SPeepholeOptimization +
  6398. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6399. ' to $' + debug_tostr(mask) +
  6400. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6401. taicpu(hp1).oper[0]^.val := mask;
  6402. end;
  6403. {$else DEBUG_AOPTCPU}
  6404. { If debugging is off, just set the operand even if it's the same }
  6405. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6406. {$endif DEBUG_AOPTCPU}
  6407. end;
  6408. end;
  6409. {
  6410. change
  6411. shl/sal const,reg
  6412. <op> ...(...,reg,1),...
  6413. into
  6414. <op> ...(...,reg,1 shl const),...
  6415. if const in 1..3
  6416. }
  6417. if MatchOpType(taicpu(p), top_const, top_reg) and
  6418. (taicpu(p).oper[0]^.val in [1..3]) and
  6419. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6420. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6421. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6422. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6423. MatchOpType(taicpu(hp1),top_ref))
  6424. ) and
  6425. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6426. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6427. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6428. begin
  6429. TransferUsedRegs(TmpUsedRegs);
  6430. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6431. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6432. begin
  6433. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6434. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6435. RemoveCurrentP(p);
  6436. Result:=true;
  6437. exit;
  6438. end;
  6439. end;
  6440. if MatchOpType(taicpu(p), top_const, top_reg) and
  6441. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6442. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6443. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6444. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6445. begin
  6446. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6447. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6448. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6449. {$ifdef x86_64}
  6450. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6451. {$endif x86_64}
  6452. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6453. begin
  6454. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6455. taicpu(hp1).opcode:=A_MOV;
  6456. taicpu(hp1).oper[0]^.val:=0;
  6457. end
  6458. else
  6459. begin
  6460. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6461. taicpu(hp1).oper[0]^.val:=shiftval;
  6462. end;
  6463. RemoveCurrentP(p);
  6464. Result:=true;
  6465. exit;
  6466. end;
  6467. end;
  6468. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6469. begin
  6470. case shr_size of
  6471. S_B:
  6472. { No valid combinations }
  6473. Result := False;
  6474. S_W:
  6475. Result := (Shift >= 8) and (movz_size = S_BW);
  6476. S_L:
  6477. Result :=
  6478. (Shift >= 24) { Any opsize is valid for this shift } or
  6479. ((Shift >= 16) and (movz_size = S_WL));
  6480. {$ifdef x86_64}
  6481. S_Q:
  6482. Result :=
  6483. (Shift >= 56) { Any opsize is valid for this shift } or
  6484. ((Shift >= 48) and (movz_size = S_WL));
  6485. {$endif x86_64}
  6486. else
  6487. InternalError(2022081510);
  6488. end;
  6489. end;
  6490. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6491. var
  6492. hp1, hp2: tai;
  6493. Shift: TCGInt;
  6494. LimitSize: Topsize;
  6495. DoNotMerge: Boolean;
  6496. begin
  6497. Result := False;
  6498. { All these optimisations work on "shr const,%reg" }
  6499. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6500. Exit;
  6501. DoNotMerge := False;
  6502. Shift := taicpu(p).oper[0]^.val;
  6503. LimitSize := taicpu(p).opsize;
  6504. hp1 := p;
  6505. repeat
  6506. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6507. Exit;
  6508. case taicpu(hp1).opcode of
  6509. A_TEST, A_CMP, A_Jcc:
  6510. { Skip over conditional jumps and relevant comparisons }
  6511. Continue;
  6512. A_MOVZX:
  6513. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6514. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6515. begin
  6516. { Since the original register is being read as is, subsequent
  6517. SHRs must not be merged at this point }
  6518. DoNotMerge := True;
  6519. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6520. begin
  6521. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6522. begin
  6523. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6524. taicpu(hp1).opcode := A_MOV;
  6525. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6526. case taicpu(hp1).opsize of
  6527. S_BW:
  6528. taicpu(hp1).opsize := S_W;
  6529. S_BL, S_WL:
  6530. taicpu(hp1).opsize := S_L;
  6531. else
  6532. InternalError(2022081503);
  6533. end;
  6534. { p itself hasn't changed, so no need to set Result to True }
  6535. Include(OptsToCheck, aoc_ForceNewIteration);
  6536. { See if there's anything afterwards that can be
  6537. optimised, since the input register hasn't changed }
  6538. Continue;
  6539. end;
  6540. { NOTE: If the MOVZX instruction reads and writes the same
  6541. register, defer this to the post-peephole optimisation stage }
  6542. Exit;
  6543. end;
  6544. end;
  6545. A_SHL, A_SAL, A_SHR:
  6546. if (taicpu(hp1).opsize <= LimitSize) and
  6547. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6548. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6549. begin
  6550. { Make sure the sizes don't exceed the register size limit
  6551. (measured by the shift value falling below the limit) }
  6552. if taicpu(hp1).opsize < LimitSize then
  6553. LimitSize := taicpu(hp1).opsize;
  6554. if taicpu(hp1).opcode = A_SHR then
  6555. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6556. else
  6557. begin
  6558. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6559. DoNotMerge := True;
  6560. end;
  6561. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6562. Exit;
  6563. { Since we've established that the combined shift is within
  6564. limits, we can actually combine the adjacent SHR
  6565. instructions even if they're different sizes }
  6566. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6567. begin
  6568. hp2 := tai(hp1.Previous);
  6569. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6570. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6571. RemoveInstruction(hp1);
  6572. hp1 := hp2;
  6573. { Though p has changed, only the constant has, and its
  6574. effects can still be detected on the next iteration of
  6575. the repeat..until loop }
  6576. Include(OptsToCheck, aoc_ForceNewIteration);
  6577. end;
  6578. { Move onto the next instruction }
  6579. Continue;
  6580. end;
  6581. else
  6582. ;
  6583. end;
  6584. Break;
  6585. until False;
  6586. end;
  6587. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6588. var
  6589. CurrentRef: TReference;
  6590. FullReg: TRegister;
  6591. hp1, hp2: tai;
  6592. begin
  6593. Result := False;
  6594. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6595. Exit;
  6596. { We assume you've checked if the operand is actually a reference by
  6597. this point. If it isn't, you'll most likely get an access violation }
  6598. CurrentRef := first_mov.oper[1]^.ref^;
  6599. { Memory must be aligned }
  6600. if (CurrentRef.offset mod 4) <> 0 then
  6601. Exit;
  6602. Inc(CurrentRef.offset);
  6603. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6604. if MatchOperand(second_mov.oper[0]^, 0) and
  6605. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6606. GetNextInstruction(second_mov, hp1) and
  6607. (hp1.typ = ait_instruction) and
  6608. (taicpu(hp1).opcode = A_MOV) and
  6609. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6610. (taicpu(hp1).oper[0]^.val = 0) then
  6611. begin
  6612. Inc(CurrentRef.offset);
  6613. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6614. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6615. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6616. begin
  6617. case taicpu(hp1).opsize of
  6618. S_B:
  6619. if GetNextInstruction(hp1, hp2) and
  6620. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6621. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6622. (taicpu(hp2).oper[0]^.val = 0) then
  6623. begin
  6624. Inc(CurrentRef.offset);
  6625. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6626. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6627. (taicpu(hp2).opsize = S_B) then
  6628. begin
  6629. RemoveInstruction(hp1);
  6630. RemoveInstruction(hp2);
  6631. first_mov.opsize := S_L;
  6632. if first_mov.oper[0]^.typ = top_reg then
  6633. begin
  6634. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6635. { Reuse second_mov as a MOVZX instruction }
  6636. second_mov.opcode := A_MOVZX;
  6637. second_mov.opsize := S_BL;
  6638. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6639. second_mov.loadreg(1, FullReg);
  6640. first_mov.oper[0]^.reg := FullReg;
  6641. asml.Remove(second_mov);
  6642. asml.InsertBefore(second_mov, first_mov);
  6643. end
  6644. else
  6645. { It's a value }
  6646. begin
  6647. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6648. RemoveInstruction(second_mov);
  6649. end;
  6650. Result := True;
  6651. Exit;
  6652. end;
  6653. end;
  6654. S_W:
  6655. begin
  6656. RemoveInstruction(hp1);
  6657. first_mov.opsize := S_L;
  6658. if first_mov.oper[0]^.typ = top_reg then
  6659. begin
  6660. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6661. { Reuse second_mov as a MOVZX instruction }
  6662. second_mov.opcode := A_MOVZX;
  6663. second_mov.opsize := S_BL;
  6664. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6665. second_mov.loadreg(1, FullReg);
  6666. first_mov.oper[0]^.reg := FullReg;
  6667. asml.Remove(second_mov);
  6668. asml.InsertBefore(second_mov, first_mov);
  6669. end
  6670. else
  6671. { It's a value }
  6672. begin
  6673. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6674. RemoveInstruction(second_mov);
  6675. end;
  6676. Result := True;
  6677. Exit;
  6678. end;
  6679. else
  6680. ;
  6681. end;
  6682. end;
  6683. end;
  6684. end;
  6685. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6686. { returns true if a "continue" should be done after this optimization }
  6687. var
  6688. hp1, hp2, hp3: tai;
  6689. begin
  6690. Result := false;
  6691. hp3 := nil;
  6692. if MatchOpType(taicpu(p),top_ref) and
  6693. GetNextInstruction(p, hp1) and
  6694. (hp1.typ = ait_instruction) and
  6695. (((taicpu(hp1).opcode = A_FLD) and
  6696. (taicpu(p).opcode = A_FSTP)) or
  6697. ((taicpu(p).opcode = A_FISTP) and
  6698. (taicpu(hp1).opcode = A_FILD))) and
  6699. MatchOpType(taicpu(hp1),top_ref) and
  6700. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6701. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6702. begin
  6703. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6704. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6705. GetNextInstruction(hp1, hp2) and
  6706. (((hp2.typ = ait_instruction) and
  6707. IsExitCode(hp2) and
  6708. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6709. not(assigned(current_procinfo.procdef.funcretsym) and
  6710. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6711. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6712. { fstp <temp>
  6713. fld <temp>
  6714. <dealloc> <temp>
  6715. }
  6716. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6717. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6718. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6719. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6720. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6721. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6722. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6723. )
  6724. )
  6725. ) then
  6726. begin
  6727. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6728. RemoveInstruction(hp1);
  6729. RemoveCurrentP(p, hp2);
  6730. { first case: exit code }
  6731. if hp2.typ = ait_instruction then
  6732. RemoveLastDeallocForFuncRes(p);
  6733. Result := true;
  6734. end
  6735. else
  6736. { we can do this only in fast math mode as fstp is rounding ...
  6737. ... still disabled as it breaks the compiler and/or rtl }
  6738. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6739. { ... or if another fstp equal to the first one follows }
  6740. GetNextInstruction(hp1,hp2) and
  6741. (hp2.typ = ait_instruction) and
  6742. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6743. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6744. begin
  6745. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6746. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6747. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6748. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6749. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6750. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6751. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6752. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6753. ) then
  6754. begin
  6755. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6756. RemoveCurrentP(p,hp2);
  6757. RemoveInstruction(hp1);
  6758. Result := true;
  6759. end
  6760. else if { fst can't store an extended/comp value }
  6761. (taicpu(p).opsize <> S_FX) and
  6762. (taicpu(p).opsize <> S_IQ) then
  6763. begin
  6764. if (taicpu(p).opcode = A_FSTP) then
  6765. taicpu(p).opcode := A_FST
  6766. else
  6767. taicpu(p).opcode := A_FIST;
  6768. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6769. RemoveInstruction(hp1);
  6770. Result := true;
  6771. end;
  6772. end;
  6773. end;
  6774. end;
  6775. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6776. var
  6777. hp1, hp2, hp3: tai;
  6778. begin
  6779. result:=false;
  6780. if MatchOpType(taicpu(p),top_reg) and
  6781. GetNextInstruction(p, hp1) and
  6782. (hp1.typ = Ait_Instruction) and
  6783. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6784. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6785. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6786. { change to
  6787. fld reg fxxx reg,st
  6788. fxxxp st, st1 (hp1)
  6789. Remark: non commutative operations must be reversed!
  6790. }
  6791. begin
  6792. case taicpu(hp1).opcode Of
  6793. A_FMULP,A_FADDP,
  6794. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6795. begin
  6796. case taicpu(hp1).opcode Of
  6797. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6798. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6799. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6800. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6801. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6802. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6803. else
  6804. internalerror(2019050534);
  6805. end;
  6806. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6807. taicpu(hp1).oper[1]^.reg := NR_ST;
  6808. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6809. RemoveCurrentP(p, hp1);
  6810. Result:=true;
  6811. exit;
  6812. end;
  6813. else
  6814. ;
  6815. end;
  6816. end
  6817. else
  6818. if MatchOpType(taicpu(p),top_ref) and
  6819. GetNextInstruction(p, hp2) and
  6820. (hp2.typ = Ait_Instruction) and
  6821. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6822. (taicpu(p).opsize in [S_FS, S_FL]) and
  6823. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6824. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6825. if GetLastInstruction(p, hp1) and
  6826. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6827. MatchOpType(taicpu(hp1),top_ref) and
  6828. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6829. if ((taicpu(hp2).opcode = A_FMULP) or
  6830. (taicpu(hp2).opcode = A_FADDP)) then
  6831. { change to
  6832. fld/fst mem1 (hp1) fld/fst mem1
  6833. fld mem1 (p) fadd/
  6834. faddp/ fmul st, st
  6835. fmulp st, st1 (hp2) }
  6836. begin
  6837. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6838. RemoveCurrentP(p, hp1);
  6839. if (taicpu(hp2).opcode = A_FADDP) then
  6840. taicpu(hp2).opcode := A_FADD
  6841. else
  6842. taicpu(hp2).opcode := A_FMUL;
  6843. taicpu(hp2).oper[1]^.reg := NR_ST;
  6844. end
  6845. else
  6846. { change to
  6847. fld/fst mem1 (hp1) fld/fst mem1
  6848. fld mem1 (p) fld st
  6849. }
  6850. begin
  6851. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6852. taicpu(p).changeopsize(S_FL);
  6853. taicpu(p).loadreg(0,NR_ST);
  6854. end
  6855. else
  6856. begin
  6857. case taicpu(hp2).opcode Of
  6858. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6859. { change to
  6860. fld/fst mem1 (hp1) fld/fst mem1
  6861. fld mem2 (p) fxxx mem2
  6862. fxxxp st, st1 (hp2) }
  6863. begin
  6864. case taicpu(hp2).opcode Of
  6865. A_FADDP: taicpu(p).opcode := A_FADD;
  6866. A_FMULP: taicpu(p).opcode := A_FMUL;
  6867. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6868. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6869. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6870. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6871. else
  6872. internalerror(2019050533);
  6873. end;
  6874. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6875. RemoveInstruction(hp2);
  6876. end
  6877. else
  6878. ;
  6879. end
  6880. end
  6881. end;
  6882. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6883. begin
  6884. Result := condition_in(cond1, cond2) or
  6885. { Not strictly subsets due to the actual flags checked, but because we're
  6886. comparing integers, E is a subset of AE and GE and their aliases }
  6887. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6888. end;
  6889. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6890. var
  6891. v: TCGInt;
  6892. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6893. FirstMatch, TempBool: Boolean;
  6894. NewReg: TRegister;
  6895. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6896. begin
  6897. Result:=false;
  6898. { All these optimisations need a next instruction }
  6899. if not GetNextInstruction(p, hp1) then
  6900. Exit;
  6901. { Search for:
  6902. cmp ###,###
  6903. j(c1) @lbl1
  6904. ...
  6905. @lbl:
  6906. cmp ###,### (same comparison as above)
  6907. j(c2) @lbl2
  6908. If c1 is a subset of c2, change to:
  6909. cmp ###,###
  6910. j(c1) @lbl2
  6911. (@lbl1 may become a dead label as a result)
  6912. }
  6913. { Also handle cases where there are multiple jumps in a row }
  6914. p_jump := hp1;
  6915. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6916. begin
  6917. if IsJumpToLabel(taicpu(p_jump)) then
  6918. begin
  6919. { Do jump optimisations first in case the condition becomes
  6920. unnecessary }
  6921. TempBool := True;
  6922. if DoJumpOptimizations(p_jump, TempBool) or
  6923. not TempBool then
  6924. begin
  6925. if Assigned(p_jump) then
  6926. begin
  6927. hp1 := p_jump;
  6928. if (p_jump.typ in [ait_align]) then
  6929. SkipAligns(p_jump, p_jump);
  6930. { CollapseZeroDistJump will be set to the label after the
  6931. jump if it optimises, whether or not it's live or dead }
  6932. if (p_jump.typ in [ait_label]) and
  6933. not (tai_label(p_jump).labsym.is_used) then
  6934. GetNextInstruction(p_jump, p_jump);
  6935. end;
  6936. TransferUsedRegs(TmpUsedRegs);
  6937. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6938. if not Assigned(p_jump) or
  6939. (
  6940. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  6941. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  6942. ) then
  6943. begin
  6944. { No more conditional jumps; conditional statement is no longer required }
  6945. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  6946. RemoveCurrentP(p);
  6947. Result := True;
  6948. Exit;
  6949. end;
  6950. hp1 := p_jump;
  6951. Include(OptsToCheck, aoc_ForceNewIteration);
  6952. Continue;
  6953. end;
  6954. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6955. if GetNextInstruction(p_jump, hp2) and
  6956. (
  6957. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  6958. not TempBool
  6959. ) then
  6960. begin
  6961. hp1 := p_jump;
  6962. Include(OptsToCheck, aoc_ForceNewIteration);
  6963. Continue;
  6964. end;
  6965. p_label := nil;
  6966. if Assigned(JumpLabel) then
  6967. p_label := getlabelwithsym(JumpLabel);
  6968. if Assigned(p_label) and
  6969. GetNextInstruction(p_label, p_dist) and
  6970. MatchInstruction(p_dist, A_CMP, []) and
  6971. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6972. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6973. GetNextInstruction(p_dist, hp1_dist) and
  6974. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6975. begin
  6976. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6977. if JumpLabel = JumpLabel_dist then
  6978. { This is an infinite loop }
  6979. Exit;
  6980. { Best optimisation when the first condition is a subset (or equal) of the second }
  6981. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6982. begin
  6983. { Any registers used here will already be allocated }
  6984. if Assigned(JumpLabel) then
  6985. JumpLabel.DecRefs;
  6986. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6987. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6988. Result := True;
  6989. { Don't exit yet. Since p and p_jump haven't actually been
  6990. removed, we can check for more on this iteration }
  6991. end
  6992. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6993. GetNextInstruction(hp1_dist, hp1_label) and
  6994. SkipAligns(hp1_label, hp1_label) and
  6995. (hp1_label.typ = ait_label) then
  6996. begin
  6997. JumpLabel_far := tai_label(hp1_label).labsym;
  6998. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6999. { This is an infinite loop }
  7000. Exit;
  7001. if Assigned(JumpLabel_far) then
  7002. begin
  7003. { In this situation, if the first jump branches, the second one will never,
  7004. branch so change the destination label to after the second jump }
  7005. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7006. if Assigned(JumpLabel) then
  7007. JumpLabel.DecRefs;
  7008. JumpLabel_far.IncRefs;
  7009. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7010. Result := True;
  7011. { Don't exit yet. Since p and p_jump haven't actually been
  7012. removed, we can check for more on this iteration }
  7013. Continue;
  7014. end;
  7015. end;
  7016. end;
  7017. end;
  7018. { Search for:
  7019. cmp ###,###
  7020. j(c1) @lbl1
  7021. cmp ###,### (same as first)
  7022. Remove second cmp
  7023. }
  7024. if GetNextInstruction(p_jump, hp2) and
  7025. (
  7026. (
  7027. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7028. (
  7029. (
  7030. MatchOpType(taicpu(p), top_const, top_reg) and
  7031. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7032. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7033. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7034. ) or (
  7035. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7036. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7037. )
  7038. )
  7039. ) or (
  7040. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7041. MatchOperand(taicpu(p).oper[0]^, 0) and
  7042. (taicpu(p).oper[1]^.typ = top_reg) and
  7043. MatchInstruction(hp2, A_TEST, []) and
  7044. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7045. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7046. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7047. )
  7048. ) then
  7049. begin
  7050. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7051. RemoveInstruction(hp2);
  7052. Result := True;
  7053. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7054. end;
  7055. GetNextInstruction(p_jump, p_jump);
  7056. end;
  7057. if (
  7058. { Don't call GetNextInstruction again if we already have it }
  7059. (hp1 = p_jump) or
  7060. GetNextInstruction(p, hp1)
  7061. ) and
  7062. MatchInstruction(hp1, A_Jcc, []) and
  7063. IsJumpToLabel(taicpu(hp1)) and
  7064. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7065. GetNextInstruction(hp1, hp2) then
  7066. begin
  7067. {
  7068. cmp x, y (or "cmp y, x")
  7069. je @lbl
  7070. mov x, y
  7071. @lbl:
  7072. (x and y can be constants, registers or references)
  7073. Change to:
  7074. mov x, y (x and y will always be equal in the end)
  7075. @lbl: (may beceome a dead label)
  7076. Also:
  7077. cmp x, y (or "cmp y, x")
  7078. jne @lbl
  7079. mov x, y
  7080. @lbl:
  7081. (x and y can be constants, registers or references)
  7082. Change to:
  7083. Absolutely nothing! (Except @lbl if it's still live)
  7084. }
  7085. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7086. (
  7087. (
  7088. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7089. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7090. ) or (
  7091. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7092. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7093. )
  7094. ) and
  7095. GetNextInstruction(hp2, hp1_label) and
  7096. SkipAligns(hp1_label, hp1_label) and
  7097. (hp1_label.typ = ait_label) and
  7098. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7099. begin
  7100. tai_label(hp1_label).labsym.DecRefs;
  7101. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7102. begin
  7103. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7104. RemoveInstruction(hp2);
  7105. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7106. end
  7107. else
  7108. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7109. RemoveInstruction(hp1);
  7110. RemoveCurrentp(p, hp2);
  7111. Result := True;
  7112. Exit;
  7113. end;
  7114. {
  7115. Try to optimise the following:
  7116. cmp $x,### ($x and $y can be registers or constants)
  7117. je @lbl1 (only reference)
  7118. cmp $y,### (### are identical)
  7119. @Lbl:
  7120. sete %reg1
  7121. Change to:
  7122. cmp $x,###
  7123. sete %reg2 (allocate new %reg2)
  7124. cmp $y,###
  7125. sete %reg1
  7126. orb %reg2,%reg1
  7127. (dealloc %reg2)
  7128. This adds an instruction (so don't perform under -Os), but it removes
  7129. a conditional branch.
  7130. }
  7131. if not (cs_opt_size in current_settings.optimizerswitches) and
  7132. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7133. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7134. { The first operand of CMP instructions can only be a register or
  7135. immediate anyway, so no need to check }
  7136. GetNextInstruction(hp2, p_label) and
  7137. (p_label.typ = ait_label) and
  7138. (tai_label(p_label).labsym.getrefs = 1) and
  7139. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7140. GetNextInstruction(p_label, p_dist) and
  7141. MatchInstruction(p_dist, A_SETcc, []) and
  7142. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7143. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7144. begin
  7145. TransferUsedRegs(TmpUsedRegs);
  7146. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7147. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7148. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7149. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7150. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7151. { Get the instruction after the SETcc instruction so we can
  7152. allocate a new register over the entire range }
  7153. GetNextInstruction(p_dist, hp1_dist) then
  7154. begin
  7155. { Register can appear in p if it's not used afterwards, so only
  7156. allocate between hp1 and hp1_dist }
  7157. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7158. if NewReg <> NR_NO then
  7159. begin
  7160. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7161. { Change the jump instruction into a SETcc instruction }
  7162. taicpu(hp1).opcode := A_SETcc;
  7163. taicpu(hp1).opsize := S_B;
  7164. taicpu(hp1).loadreg(0, NewReg);
  7165. { This is now a dead label }
  7166. tai_label(p_label).labsym.decrefs;
  7167. { Prefer adding before the next instruction so the FLAGS
  7168. register is deallicated first }
  7169. AsmL.InsertBefore(
  7170. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7171. hp1_dist
  7172. );
  7173. Result := True;
  7174. { Don't exit yet, as p wasn't changed and hp1, while
  7175. modified, is still intact and might be optimised by the
  7176. SETcc optimisation below }
  7177. end;
  7178. end;
  7179. end;
  7180. end;
  7181. if taicpu(p).oper[0]^.typ = top_const then
  7182. begin
  7183. if (taicpu(p).oper[0]^.val = 0) and
  7184. (taicpu(p).oper[1]^.typ = top_reg) and
  7185. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7186. begin
  7187. hp2 := p;
  7188. FirstMatch := True;
  7189. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7190. anything meaningful once it's converted to "test %reg,%reg";
  7191. additionally, some jumps will always (or never) branch, so
  7192. evaluate every jump immediately following the
  7193. comparison, optimising the conditions if possible.
  7194. Similarly with SETcc... those that are always set to 0 or 1
  7195. are changed to MOV instructions }
  7196. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7197. (
  7198. GetNextInstruction(hp2, hp1) and
  7199. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7200. ) do
  7201. begin
  7202. FirstMatch := False;
  7203. case taicpu(hp1).condition of
  7204. C_B, C_C, C_NAE, C_O:
  7205. { For B/NAE:
  7206. Will never branch since an unsigned integer can never be below zero
  7207. For C/O:
  7208. Result cannot overflow because 0 is being subtracted
  7209. }
  7210. begin
  7211. if taicpu(hp1).opcode = A_Jcc then
  7212. begin
  7213. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7214. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7215. RemoveInstruction(hp1);
  7216. { Since hp1 was deleted, hp2 must not be updated }
  7217. Continue;
  7218. end
  7219. else
  7220. begin
  7221. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7222. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7223. taicpu(hp1).opcode := A_MOV;
  7224. taicpu(hp1).ops := 2;
  7225. taicpu(hp1).condition := C_None;
  7226. taicpu(hp1).opsize := S_B;
  7227. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7228. taicpu(hp1).loadconst(0, 0);
  7229. end;
  7230. end;
  7231. C_BE, C_NA:
  7232. begin
  7233. { Will only branch if equal to zero }
  7234. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7235. taicpu(hp1).condition := C_E;
  7236. end;
  7237. C_A, C_NBE:
  7238. begin
  7239. { Will only branch if not equal to zero }
  7240. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7241. taicpu(hp1).condition := C_NE;
  7242. end;
  7243. C_AE, C_NB, C_NC, C_NO:
  7244. begin
  7245. { Will always branch }
  7246. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7247. if taicpu(hp1).opcode = A_Jcc then
  7248. begin
  7249. MakeUnconditional(taicpu(hp1));
  7250. { Any jumps/set that follow will now be dead code }
  7251. RemoveDeadCodeAfterJump(taicpu(hp1));
  7252. Break;
  7253. end
  7254. else
  7255. begin
  7256. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7257. taicpu(hp1).opcode := A_MOV;
  7258. taicpu(hp1).ops := 2;
  7259. taicpu(hp1).condition := C_None;
  7260. taicpu(hp1).opsize := S_B;
  7261. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7262. taicpu(hp1).loadconst(0, 1);
  7263. end;
  7264. end;
  7265. C_None:
  7266. InternalError(2020012201);
  7267. C_P, C_PE, C_NP, C_PO:
  7268. { We can't handle parity checks and they should never be generated
  7269. after a general-purpose CMP (it's used in some floating-point
  7270. comparisons that don't use CMP) }
  7271. InternalError(2020012202);
  7272. else
  7273. { Zero/Equality, Sign, their complements and all of the
  7274. signed comparisons do not need to be converted };
  7275. end;
  7276. hp2 := hp1;
  7277. end;
  7278. { Convert the instruction to a TEST }
  7279. taicpu(p).opcode := A_TEST;
  7280. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7281. Result := True;
  7282. Exit;
  7283. end
  7284. else if (taicpu(p).oper[0]^.val = 1) and
  7285. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7286. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7287. begin
  7288. { Convert; To:
  7289. cmp $1,r/m cmp $0,r/m
  7290. jl @lbl jle @lbl
  7291. (Also do inverted conditions)
  7292. }
  7293. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7294. taicpu(p).oper[0]^.val := 0;
  7295. if taicpu(hp1).condition in [C_L, C_NGE] then
  7296. taicpu(hp1).condition := C_LE
  7297. else
  7298. taicpu(hp1).condition := C_NLE;
  7299. { If the instruction is now "cmp $0,%reg", convert it to a
  7300. TEST (and effectively do the work of the "cmp $0,%reg" in
  7301. the block above)
  7302. }
  7303. if (taicpu(p).oper[1]^.typ = top_reg) then
  7304. begin
  7305. taicpu(p).opcode := A_TEST;
  7306. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7307. end;
  7308. Result := True;
  7309. Exit;
  7310. end
  7311. else if (taicpu(p).oper[1]^.typ = top_reg)
  7312. {$ifdef x86_64}
  7313. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7314. {$endif x86_64}
  7315. then
  7316. begin
  7317. { cmp register,$8000 neg register
  7318. je target --> jo target
  7319. .... only if register is deallocated before jump.}
  7320. case Taicpu(p).opsize of
  7321. S_B: v:=$80;
  7322. S_W: v:=$8000;
  7323. S_L: v:=qword($80000000);
  7324. else
  7325. internalerror(2013112905);
  7326. end;
  7327. if (taicpu(p).oper[0]^.val=v) and
  7328. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7329. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7330. begin
  7331. TransferUsedRegs(TmpUsedRegs);
  7332. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7333. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7334. begin
  7335. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7336. Taicpu(p).opcode:=A_NEG;
  7337. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7338. Taicpu(p).clearop(1);
  7339. Taicpu(p).ops:=1;
  7340. if Taicpu(hp1).condition=C_E then
  7341. Taicpu(hp1).condition:=C_O
  7342. else
  7343. Taicpu(hp1).condition:=C_NO;
  7344. Result:=true;
  7345. exit;
  7346. end;
  7347. end;
  7348. end;
  7349. end;
  7350. if TrySwapMovCmp(p, hp1) then
  7351. begin
  7352. Result := True;
  7353. Exit;
  7354. end;
  7355. end;
  7356. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7357. var
  7358. hp1: tai;
  7359. begin
  7360. {
  7361. remove the second (v)pxor from
  7362. pxor reg,reg
  7363. ...
  7364. pxor reg,reg
  7365. }
  7366. Result:=false;
  7367. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7368. MatchOpType(taicpu(p),top_reg,top_reg) and
  7369. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7370. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7371. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7372. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7373. begin
  7374. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7375. RemoveInstruction(hp1);
  7376. Result:=true;
  7377. Exit;
  7378. end
  7379. {
  7380. replace
  7381. pxor reg1,reg1
  7382. movapd/s reg1,reg2
  7383. dealloc reg1
  7384. by
  7385. pxor reg2,reg2
  7386. }
  7387. else if GetNextInstruction(p,hp1) and
  7388. { we mix single and double opperations here because we assume that the compiler
  7389. generates vmovapd only after double operations and vmovaps only after single operations }
  7390. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7391. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7392. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7393. (taicpu(p).oper[0]^.typ=top_reg) then
  7394. begin
  7395. TransferUsedRegs(TmpUsedRegs);
  7396. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7397. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7398. begin
  7399. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7400. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7401. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7402. RemoveInstruction(hp1);
  7403. result:=true;
  7404. end;
  7405. end;
  7406. end;
  7407. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7408. var
  7409. hp1: tai;
  7410. begin
  7411. {
  7412. remove the second (v)pxor from
  7413. (v)pxor reg,reg
  7414. ...
  7415. (v)pxor reg,reg
  7416. }
  7417. Result:=false;
  7418. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7419. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7420. begin
  7421. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7422. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7423. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7424. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7425. begin
  7426. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7427. RemoveInstruction(hp1);
  7428. Result:=true;
  7429. Exit;
  7430. end;
  7431. {$ifdef x86_64}
  7432. {
  7433. replace
  7434. vpxor reg1,reg1,reg1
  7435. vmov reg,mem
  7436. by
  7437. movq $0,mem
  7438. }
  7439. if GetNextInstruction(p,hp1) and
  7440. MatchInstruction(hp1,A_VMOVSD,[]) and
  7441. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7442. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7443. begin
  7444. TransferUsedRegs(TmpUsedRegs);
  7445. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7446. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7447. begin
  7448. taicpu(hp1).loadconst(0,0);
  7449. taicpu(hp1).opcode:=A_MOV;
  7450. taicpu(hp1).opsize:=S_Q;
  7451. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7452. RemoveCurrentP(p);
  7453. result:=true;
  7454. Exit;
  7455. end;
  7456. end;
  7457. {$endif x86_64}
  7458. end
  7459. {
  7460. replace
  7461. vpxor reg1,reg1,reg2
  7462. by
  7463. vpxor reg2,reg2,reg2
  7464. to avoid unncessary data dependencies
  7465. }
  7466. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7467. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7468. begin
  7469. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7470. { avoid unncessary data dependency }
  7471. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7472. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7473. result:=true;
  7474. exit;
  7475. end;
  7476. Result:=OptPass1VOP(p);
  7477. end;
  7478. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7479. var
  7480. hp1 : tai;
  7481. begin
  7482. result:=false;
  7483. { replace
  7484. IMul const,%mreg1,%mreg2
  7485. Mov %reg2,%mreg3
  7486. dealloc %mreg3
  7487. by
  7488. Imul const,%mreg1,%mreg23
  7489. }
  7490. if (taicpu(p).ops=3) and
  7491. GetNextInstruction(p,hp1) and
  7492. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7493. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7494. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7495. begin
  7496. TransferUsedRegs(TmpUsedRegs);
  7497. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7498. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7499. begin
  7500. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7501. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7502. RemoveInstruction(hp1);
  7503. result:=true;
  7504. end;
  7505. end;
  7506. end;
  7507. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7508. var
  7509. hp1 : tai;
  7510. begin
  7511. result:=false;
  7512. { replace
  7513. IMul %reg0,%reg1,%reg2
  7514. Mov %reg2,%reg3
  7515. dealloc %reg2
  7516. by
  7517. Imul %reg0,%reg1,%reg3
  7518. }
  7519. if GetNextInstruction(p,hp1) and
  7520. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7521. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7522. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7523. begin
  7524. TransferUsedRegs(TmpUsedRegs);
  7525. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7526. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7527. begin
  7528. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7529. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7530. RemoveInstruction(hp1);
  7531. result:=true;
  7532. end;
  7533. end;
  7534. end;
  7535. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7536. var
  7537. hp1: tai;
  7538. begin
  7539. Result:=false;
  7540. { get rid of
  7541. (v)cvtss2sd reg0,<reg1,>reg2
  7542. (v)cvtss2sd reg2,<reg2,>reg0
  7543. }
  7544. if GetNextInstruction(p,hp1) and
  7545. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7546. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7547. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7548. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7549. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7550. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7551. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7552. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7553. )
  7554. ) then
  7555. begin
  7556. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7557. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7558. begin
  7559. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7560. RemoveCurrentP(p);
  7561. RemoveInstruction(hp1);
  7562. end
  7563. else
  7564. begin
  7565. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7566. if taicpu(hp1).opcode=A_CVTSD2SS then
  7567. begin
  7568. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7569. taicpu(p).opcode:=A_MOVAPS;
  7570. end
  7571. else
  7572. begin
  7573. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7574. taicpu(p).opcode:=A_VMOVAPS;
  7575. end;
  7576. taicpu(p).ops:=2;
  7577. RemoveInstruction(hp1);
  7578. end;
  7579. Result:=true;
  7580. Exit;
  7581. end;
  7582. end;
  7583. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7584. var
  7585. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7586. ThisReg: TRegister;
  7587. begin
  7588. Result := False;
  7589. if not GetNextInstruction(p,hp1) then
  7590. Exit;
  7591. {
  7592. convert
  7593. j<c> .L1
  7594. mov 1,reg
  7595. jmp .L2
  7596. .L1
  7597. mov 0,reg
  7598. .L2
  7599. into
  7600. mov 0,reg
  7601. set<not(c)> reg
  7602. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7603. would destroy the flag contents
  7604. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7605. executed at the same time as a previous comparison.
  7606. set<not(c)> reg
  7607. movzx reg, reg
  7608. }
  7609. if MatchInstruction(hp1,A_MOV,[]) and
  7610. (taicpu(hp1).oper[0]^.typ = top_const) and
  7611. (
  7612. (
  7613. (taicpu(hp1).oper[1]^.typ = top_reg)
  7614. {$ifdef i386}
  7615. { Under i386, ESI, EDI, EBP and ESP
  7616. don't have an 8-bit representation }
  7617. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7618. {$endif i386}
  7619. ) or (
  7620. {$ifdef i386}
  7621. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7622. {$endif i386}
  7623. (taicpu(hp1).opsize = S_B)
  7624. )
  7625. ) and
  7626. GetNextInstruction(hp1,hp2) and
  7627. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7628. GetNextInstruction(hp2,hp3) and
  7629. SkipAligns(hp3, hp3) and
  7630. (hp3.typ=ait_label) and
  7631. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7632. GetNextInstruction(hp3,hp4) and
  7633. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7634. (taicpu(hp4).oper[0]^.typ = top_const) and
  7635. (
  7636. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7637. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7638. ) and
  7639. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7640. GetNextInstruction(hp4,hp5) and
  7641. SkipAligns(hp5, hp5) and
  7642. (hp5.typ=ait_label) and
  7643. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7644. begin
  7645. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7646. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7647. tai_label(hp3).labsym.DecRefs;
  7648. { If this isn't the only reference to the middle label, we can
  7649. still make a saving - only that the first jump and everything
  7650. that follows will remain. }
  7651. if (tai_label(hp3).labsym.getrefs = 0) then
  7652. begin
  7653. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7654. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7655. else
  7656. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7657. { remove jump, first label and second MOV (also catching any aligns) }
  7658. repeat
  7659. if not GetNextInstruction(hp2, hp3) then
  7660. InternalError(2021040810);
  7661. RemoveInstruction(hp2);
  7662. hp2 := hp3;
  7663. until hp2 = hp5;
  7664. { Don't decrement reference count before the removal loop
  7665. above, otherwise GetNextInstruction won't stop on the
  7666. the label }
  7667. tai_label(hp5).labsym.DecRefs;
  7668. end
  7669. else
  7670. begin
  7671. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7672. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7673. else
  7674. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7675. end;
  7676. taicpu(p).opcode:=A_SETcc;
  7677. taicpu(p).opsize:=S_B;
  7678. taicpu(p).is_jmp:=False;
  7679. if taicpu(hp1).opsize=S_B then
  7680. begin
  7681. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7682. if taicpu(hp1).oper[1]^.typ = top_reg then
  7683. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7684. RemoveInstruction(hp1);
  7685. end
  7686. else
  7687. begin
  7688. { Will be a register because the size can't be S_B otherwise }
  7689. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7690. taicpu(p).loadreg(0, ThisReg);
  7691. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7692. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7693. begin
  7694. case taicpu(hp1).opsize of
  7695. S_W:
  7696. taicpu(hp1).opsize := S_BW;
  7697. S_L:
  7698. taicpu(hp1).opsize := S_BL;
  7699. {$ifdef x86_64}
  7700. S_Q:
  7701. begin
  7702. taicpu(hp1).opsize := S_BL;
  7703. { Change the destination register to 32-bit }
  7704. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7705. end;
  7706. {$endif x86_64}
  7707. else
  7708. InternalError(2021040820);
  7709. end;
  7710. taicpu(hp1).opcode := A_MOVZX;
  7711. taicpu(hp1).loadreg(0, ThisReg);
  7712. end
  7713. else
  7714. begin
  7715. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7716. { hp1 is already a MOV instruction with the correct register }
  7717. taicpu(hp1).loadconst(0, 0);
  7718. { Inserting it right before p will guarantee that the flags are also tracked }
  7719. asml.Remove(hp1);
  7720. asml.InsertBefore(hp1, p);
  7721. end;
  7722. end;
  7723. Result:=true;
  7724. exit;
  7725. end
  7726. else if (hp1.typ = ait_label) then
  7727. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7728. end;
  7729. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7730. var
  7731. hp1, hp2, hp3: tai;
  7732. SourceRef, TargetRef: TReference;
  7733. CurrentReg: TRegister;
  7734. begin
  7735. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7736. if not UseAVX then
  7737. InternalError(2021100501);
  7738. Result := False;
  7739. { Look for the following to simplify:
  7740. vmovdqa/u x(mem1), %xmmreg
  7741. vmovdqa/u %xmmreg, y(mem2)
  7742. vmovdqa/u x+16(mem1), %xmmreg
  7743. vmovdqa/u %xmmreg, y+16(mem2)
  7744. Change to:
  7745. vmovdqa/u x(mem1), %ymmreg
  7746. vmovdqa/u %ymmreg, y(mem2)
  7747. vpxor %ymmreg, %ymmreg, %ymmreg
  7748. ( The VPXOR instruction is to zero the upper half, thus removing the
  7749. need to call the potentially expensive VZEROUPPER instruction. Other
  7750. peephole optimisations can remove VPXOR if it's unnecessary )
  7751. }
  7752. TransferUsedRegs(TmpUsedRegs);
  7753. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7754. { NOTE: In the optimisations below, if the references dictate that an
  7755. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7756. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7757. if (taicpu(p).opsize = S_XMM) and
  7758. MatchOpType(taicpu(p), top_ref, top_reg) and
  7759. GetNextInstruction(p, hp1) and
  7760. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7761. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7762. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7763. begin
  7764. SourceRef := taicpu(p).oper[0]^.ref^;
  7765. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7766. if GetNextInstruction(hp1, hp2) and
  7767. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7768. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7769. begin
  7770. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7771. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7772. Inc(SourceRef.offset, 16);
  7773. { Reuse the register in the first block move }
  7774. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7775. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7776. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7777. begin
  7778. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7779. Inc(TargetRef.offset, 16);
  7780. if GetNextInstruction(hp2, hp3) and
  7781. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7782. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7783. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7784. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7785. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7786. begin
  7787. { Update the register tracking to the new size }
  7788. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7789. { Remember that the offsets are 16 ahead }
  7790. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7791. if not (
  7792. ((SourceRef.offset mod 32) = 16) and
  7793. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7794. ) then
  7795. taicpu(p).opcode := A_VMOVDQU;
  7796. taicpu(p).opsize := S_YMM;
  7797. taicpu(p).oper[1]^.reg := CurrentReg;
  7798. if not (
  7799. ((TargetRef.offset mod 32) = 16) and
  7800. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7801. ) then
  7802. taicpu(hp1).opcode := A_VMOVDQU;
  7803. taicpu(hp1).opsize := S_YMM;
  7804. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7805. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7806. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7807. if (pi_uses_ymm in current_procinfo.flags) then
  7808. RemoveInstruction(hp2)
  7809. else
  7810. begin
  7811. taicpu(hp2).opcode := A_VPXOR;
  7812. taicpu(hp2).opsize := S_YMM;
  7813. taicpu(hp2).loadreg(0, CurrentReg);
  7814. taicpu(hp2).loadreg(1, CurrentReg);
  7815. taicpu(hp2).loadreg(2, CurrentReg);
  7816. taicpu(hp2).ops := 3;
  7817. end;
  7818. RemoveInstruction(hp3);
  7819. Result := True;
  7820. Exit;
  7821. end;
  7822. end
  7823. else
  7824. begin
  7825. { See if the next references are 16 less rather than 16 greater }
  7826. Dec(SourceRef.offset, 32); { -16 the other way }
  7827. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7828. begin
  7829. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7830. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7831. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7832. GetNextInstruction(hp2, hp3) and
  7833. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7834. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7835. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7836. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7837. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7838. begin
  7839. { Update the register tracking to the new size }
  7840. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7841. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7842. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7843. if not(
  7844. ((SourceRef.offset mod 32) = 0) and
  7845. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7846. ) then
  7847. taicpu(hp2).opcode := A_VMOVDQU;
  7848. taicpu(hp2).opsize := S_YMM;
  7849. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7850. if not (
  7851. ((TargetRef.offset mod 32) = 0) and
  7852. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7853. ) then
  7854. taicpu(hp3).opcode := A_VMOVDQU;
  7855. taicpu(hp3).opsize := S_YMM;
  7856. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7857. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7858. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7859. if (pi_uses_ymm in current_procinfo.flags) then
  7860. RemoveInstruction(hp1)
  7861. else
  7862. begin
  7863. taicpu(hp1).opcode := A_VPXOR;
  7864. taicpu(hp1).opsize := S_YMM;
  7865. taicpu(hp1).loadreg(0, CurrentReg);
  7866. taicpu(hp1).loadreg(1, CurrentReg);
  7867. taicpu(hp1).loadreg(2, CurrentReg);
  7868. taicpu(hp1).ops := 3;
  7869. Asml.Remove(hp1);
  7870. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7871. end;
  7872. RemoveCurrentP(p, hp2);
  7873. Result := True;
  7874. Exit;
  7875. end;
  7876. end;
  7877. end;
  7878. end;
  7879. end;
  7880. end;
  7881. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7882. var
  7883. hp2, hp3, first_assignment: tai;
  7884. IncCount, OperIdx: Integer;
  7885. OrigLabel: TAsmLabel;
  7886. begin
  7887. Count := 0;
  7888. Result := False;
  7889. first_assignment := nil;
  7890. if (LoopCount >= 20) then
  7891. begin
  7892. { Guard against infinite loops }
  7893. Exit;
  7894. end;
  7895. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7896. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7897. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7898. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7899. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7900. Exit;
  7901. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7902. {
  7903. change
  7904. jmp .L1
  7905. ...
  7906. .L1:
  7907. mov ##, ## ( multiple movs possible )
  7908. jmp/ret
  7909. into
  7910. mov ##, ##
  7911. jmp/ret
  7912. }
  7913. if not Assigned(hp1) then
  7914. begin
  7915. hp1 := GetLabelWithSym(OrigLabel);
  7916. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7917. Exit;
  7918. end;
  7919. hp2 := hp1;
  7920. while Assigned(hp2) do
  7921. begin
  7922. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7923. SkipLabels(hp2,hp2);
  7924. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7925. Break;
  7926. case taicpu(hp2).opcode of
  7927. A_MOVSD:
  7928. begin
  7929. if taicpu(hp2).ops = 0 then
  7930. { Wrong MOVSD }
  7931. Break;
  7932. Inc(Count);
  7933. if Count >= 5 then
  7934. { Too many to be worthwhile }
  7935. Break;
  7936. GetNextInstruction(hp2, hp2);
  7937. Continue;
  7938. end;
  7939. A_MOV,
  7940. A_MOVD,
  7941. A_MOVQ,
  7942. A_MOVSX,
  7943. {$ifdef x86_64}
  7944. A_MOVSXD,
  7945. {$endif x86_64}
  7946. A_MOVZX,
  7947. A_MOVAPS,
  7948. A_MOVUPS,
  7949. A_MOVSS,
  7950. A_MOVAPD,
  7951. A_MOVUPD,
  7952. A_MOVDQA,
  7953. A_MOVDQU,
  7954. A_VMOVSS,
  7955. A_VMOVAPS,
  7956. A_VMOVUPS,
  7957. A_VMOVSD,
  7958. A_VMOVAPD,
  7959. A_VMOVUPD,
  7960. A_VMOVDQA,
  7961. A_VMOVDQU:
  7962. begin
  7963. Inc(Count);
  7964. if Count >= 5 then
  7965. { Too many to be worthwhile }
  7966. Break;
  7967. GetNextInstruction(hp2, hp2);
  7968. Continue;
  7969. end;
  7970. A_JMP:
  7971. begin
  7972. { Guard against infinite loops }
  7973. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7974. Exit;
  7975. { Analyse this jump first in case it also duplicates assignments }
  7976. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7977. begin
  7978. { Something did change! }
  7979. Result := True;
  7980. Inc(Count, IncCount);
  7981. if Count >= 5 then
  7982. begin
  7983. { Too many to be worthwhile }
  7984. Exit;
  7985. end;
  7986. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7987. Break;
  7988. end;
  7989. Result := True;
  7990. Break;
  7991. end;
  7992. A_RET:
  7993. begin
  7994. Result := True;
  7995. Break;
  7996. end;
  7997. else
  7998. Break;
  7999. end;
  8000. end;
  8001. if Result then
  8002. begin
  8003. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8004. if Count = 0 then
  8005. begin
  8006. Result := False;
  8007. Exit;
  8008. end;
  8009. hp3 := p;
  8010. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8011. while True do
  8012. begin
  8013. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  8014. SkipLabels(hp1,hp1);
  8015. if (hp1.typ <> ait_instruction) then
  8016. InternalError(2021040720);
  8017. case taicpu(hp1).opcode of
  8018. A_JMP:
  8019. begin
  8020. { Change the original jump to the new destination }
  8021. OrigLabel.decrefs;
  8022. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8023. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8024. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8025. if not Assigned(first_assignment) then
  8026. InternalError(2021040810)
  8027. else
  8028. p := first_assignment;
  8029. Exit;
  8030. end;
  8031. A_RET:
  8032. begin
  8033. { Now change the jump into a RET instruction }
  8034. ConvertJumpToRET(p, hp1);
  8035. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8036. if not Assigned(first_assignment) then
  8037. InternalError(2021040811)
  8038. else
  8039. p := first_assignment;
  8040. Exit;
  8041. end;
  8042. else
  8043. begin
  8044. { Duplicate the MOV instruction }
  8045. hp3:=tai(hp1.getcopy);
  8046. if first_assignment = nil then
  8047. first_assignment := hp3;
  8048. asml.InsertBefore(hp3, p);
  8049. { Make sure the compiler knows about any final registers written here }
  8050. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8051. with taicpu(hp3).oper[OperIdx]^ do
  8052. begin
  8053. case typ of
  8054. top_ref:
  8055. begin
  8056. if (ref^.base <> NR_NO) and
  8057. (getsupreg(ref^.base) <> RS_ESP) and
  8058. (getsupreg(ref^.base) <> RS_EBP)
  8059. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8060. then
  8061. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8062. if (ref^.index <> NR_NO) and
  8063. (getsupreg(ref^.index) <> RS_ESP) and
  8064. (getsupreg(ref^.index) <> RS_EBP)
  8065. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8066. (ref^.index <> ref^.base) then
  8067. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8068. end;
  8069. top_reg:
  8070. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8071. else
  8072. ;
  8073. end;
  8074. end;
  8075. end;
  8076. end;
  8077. if not GetNextInstruction(hp1, hp1) then
  8078. { Should have dropped out earlier }
  8079. InternalError(2021040710);
  8080. end;
  8081. end;
  8082. end;
  8083. const
  8084. WriteOp: array[0..3] of set of TInsChange = (
  8085. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8086. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8087. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8088. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8089. RegWriteFlags: array[0..7] of set of TInsChange = (
  8090. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8091. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8092. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8093. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8094. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8095. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8096. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8097. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8098. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8099. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8100. var
  8101. hp2: tai;
  8102. X: Integer;
  8103. begin
  8104. { If we have something like:
  8105. op ###,###
  8106. mov ###,###
  8107. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8108. interfere in regards to what they write to.
  8109. NOTE: p must be a 2-operand instruction
  8110. }
  8111. Result := False;
  8112. if (hp1.typ <> ait_instruction) or
  8113. taicpu(hp1).is_jmp or
  8114. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8115. Exit;
  8116. { NOP is a pipeline fence, likely marking the beginning of the function
  8117. epilogue, so drop out. Similarly, drop out if POP or RET are
  8118. encountered }
  8119. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8120. Exit;
  8121. if (taicpu(hp1).opcode = A_MOVSD) and
  8122. (taicpu(hp1).ops = 0) then
  8123. { Wrong MOVSD }
  8124. Exit;
  8125. { Check for writes to specific registers first }
  8126. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8127. for X := 0 to 7 do
  8128. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8129. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8130. Exit;
  8131. for X := 0 to taicpu(hp1).ops - 1 do
  8132. begin
  8133. { Check to see if this operand writes to something }
  8134. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8135. { And matches something in the CMP/TEST instruction }
  8136. (
  8137. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8138. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8139. (
  8140. { If it's a register, make sure the register written to doesn't
  8141. appear in the cmp instruction as part of a reference }
  8142. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8143. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8144. )
  8145. ) then
  8146. Exit;
  8147. end;
  8148. { Check p to make sure it doesn't write to something that affects hp1 }
  8149. { Check for writes to specific registers first }
  8150. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8151. for X := 0 to 7 do
  8152. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8153. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8154. Exit;
  8155. for X := 0 to taicpu(p).ops - 1 do
  8156. begin
  8157. { Check to see if this operand writes to something }
  8158. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8159. { And matches something in hp1 }
  8160. (taicpu(p).oper[X]^.typ = top_reg) and
  8161. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8162. Exit;
  8163. end;
  8164. { The instruction can be safely moved }
  8165. asml.Remove(hp1);
  8166. { Try to insert after the last instructions where the FLAGS register is not
  8167. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8168. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8169. asml.InsertBefore(hp1, hp2)
  8170. { Failing that, try to insert after the last instructions where the
  8171. FLAGS register is not yet in use }
  8172. else if GetLastInstruction(p, hp2) and
  8173. (
  8174. (hp2.typ <> ait_instruction) or
  8175. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8176. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8177. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8178. ) then
  8179. asml.InsertAfter(hp1, hp2)
  8180. else
  8181. { Note, if p.Previous is nil (even if it should logically never be the
  8182. case), FindRegAllocBackward immediately exits with False and so we
  8183. safely land here (we can't just pass p because FindRegAllocBackward
  8184. immediately exits on an instruction). [Kit] }
  8185. asml.InsertBefore(hp1, p);
  8186. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8187. { We can't trust UsedRegs because we're looking backwards, although we
  8188. know the registers are allocated after p at the very least, so manually
  8189. create tai_regalloc objects if needed }
  8190. for X := 0 to taicpu(hp1).ops - 1 do
  8191. case taicpu(hp1).oper[X]^.typ of
  8192. top_reg:
  8193. begin
  8194. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8195. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8196. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8197. end;
  8198. top_ref:
  8199. begin
  8200. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8201. begin
  8202. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8203. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8204. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8205. end;
  8206. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8207. begin
  8208. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8209. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8210. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8211. end;
  8212. end;
  8213. else
  8214. ;
  8215. end;
  8216. Result := True;
  8217. end;
  8218. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8219. var
  8220. hp2: tai;
  8221. X: Integer;
  8222. begin
  8223. { If we have something like:
  8224. cmp ###,%reg1
  8225. mov 0,%reg2
  8226. And no modified registers are shared, move the instruction to before
  8227. the comparison as this means it can be optimised without worrying
  8228. about the FLAGS register. (CMP/MOV is generated by
  8229. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8230. As long as the second instruction doesn't use the flags or one of the
  8231. registers used by CMP or TEST (also check any references that use the
  8232. registers), then it can be moved prior to the comparison.
  8233. }
  8234. Result := False;
  8235. if not TrySwapMovOp(p, hp1) then
  8236. Exit;
  8237. if taicpu(hp1).opcode = A_LEA then
  8238. { The flags will be overwritten by the CMP/TEST instruction }
  8239. ConvertLEA(taicpu(hp1));
  8240. Result := True;
  8241. { Can we move it one further back? }
  8242. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8243. { Check to see if CMP/TEST is a comparison against zero }
  8244. (
  8245. (
  8246. (taicpu(p).opcode = A_CMP) and
  8247. MatchOperand(taicpu(p).oper[0]^, 0)
  8248. ) or
  8249. (
  8250. (taicpu(p).opcode = A_TEST) and
  8251. (
  8252. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8253. MatchOperand(taicpu(p).oper[0]^, -1)
  8254. )
  8255. )
  8256. ) and
  8257. { These instructions set the zero flag if the result is zero }
  8258. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8259. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8260. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8261. TrySwapMovOp(hp2, hp1);
  8262. end;
  8263. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8264. function IsXCHGAcceptable: Boolean; inline;
  8265. begin
  8266. { Always accept if optimising for size }
  8267. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8268. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8269. than 3, so it becomes a saving compared to three MOVs with two of
  8270. them able to execute simultaneously. [Kit] }
  8271. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8272. end;
  8273. var
  8274. NewRef: TReference;
  8275. hp1, hp2, hp3, hp4: Tai;
  8276. {$ifndef x86_64}
  8277. OperIdx: Integer;
  8278. {$endif x86_64}
  8279. NewInstr : Taicpu;
  8280. NewAligh : Tai_align;
  8281. DestLabel: TAsmLabel;
  8282. TempTracking: TAllUsedRegs;
  8283. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8284. var
  8285. NextInstr: tai;
  8286. begin
  8287. Result := False;
  8288. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8289. if not GetNextInstruction(InputInstr, NextInstr) or
  8290. (
  8291. { The FLAGS register isn't always tracked properly, so do not
  8292. perform this optimisation if a conditional statement follows }
  8293. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8294. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8295. ) then
  8296. begin
  8297. reference_reset(NewRef, 1, []);
  8298. NewRef.base := taicpu(p).oper[0]^.reg;
  8299. NewRef.scalefactor := 1;
  8300. if taicpu(InputInstr).opcode = A_ADD then
  8301. begin
  8302. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8303. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8304. end
  8305. else
  8306. begin
  8307. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8308. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8309. end;
  8310. taicpu(p).opcode := A_LEA;
  8311. taicpu(p).loadref(0, NewRef);
  8312. RemoveInstruction(InputInstr);
  8313. Result := True;
  8314. end;
  8315. end;
  8316. begin
  8317. Result:=false;
  8318. { This optimisation adds an instruction, so only do it for speed }
  8319. if not (cs_opt_size in current_settings.optimizerswitches) and
  8320. MatchOpType(taicpu(p), top_const, top_reg) and
  8321. (taicpu(p).oper[0]^.val = 0) then
  8322. begin
  8323. { To avoid compiler warning }
  8324. DestLabel := nil;
  8325. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8326. InternalError(2021040750);
  8327. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8328. Exit;
  8329. case hp1.typ of
  8330. ait_align,
  8331. ait_label:
  8332. begin
  8333. { Change:
  8334. mov $0,%reg mov $0,%reg
  8335. @Lbl1: @Lbl1:
  8336. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8337. je @Lbl2 jne @Lbl2
  8338. To: To:
  8339. mov $0,%reg mov $0,%reg
  8340. jmp @Lbl2 jmp @Lbl3
  8341. (align) (align)
  8342. @Lbl1: @Lbl1:
  8343. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8344. je @Lbl2 je @Lbl2
  8345. @Lbl3: <-- Only if label exists
  8346. (Not if it's optimised for size)
  8347. }
  8348. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8349. Exit;
  8350. if (hp2.typ = ait_instruction) and
  8351. (
  8352. { Register sizes must exactly match }
  8353. (
  8354. (taicpu(hp2).opcode = A_CMP) and
  8355. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8356. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8357. ) or (
  8358. (taicpu(hp2).opcode = A_TEST) and
  8359. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8360. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8361. )
  8362. ) and GetNextInstruction(hp2, hp3) and
  8363. (hp3.typ = ait_instruction) and
  8364. (taicpu(hp3).opcode = A_JCC) and
  8365. (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
  8366. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8367. begin
  8368. { Check condition of jump }
  8369. { Always true? }
  8370. if condition_in(C_E, taicpu(hp3).condition) then
  8371. begin
  8372. { Copy label symbol and obtain matching label entry for the
  8373. conditional jump, as this will be our destination}
  8374. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8375. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8376. Result := True;
  8377. end
  8378. { Always false? }
  8379. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8380. begin
  8381. { This is only worth it if there's a jump to take }
  8382. case hp2.typ of
  8383. ait_instruction:
  8384. begin
  8385. if taicpu(hp2).opcode = A_JMP then
  8386. begin
  8387. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8388. { An unconditional jump follows the conditional jump which will always be false,
  8389. so use this jump's destination for the new jump }
  8390. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8391. Result := True;
  8392. end
  8393. else if taicpu(hp2).opcode = A_JCC then
  8394. begin
  8395. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8396. if condition_in(C_E, taicpu(hp2).condition) then
  8397. begin
  8398. { A second conditional jump follows the conditional jump which will always be false,
  8399. while the second jump is always True, so use this jump's destination for the new jump }
  8400. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8401. Result := True;
  8402. end;
  8403. { Don't risk it if the jump isn't always true (Result remains False) }
  8404. end;
  8405. end;
  8406. else
  8407. { If anything else don't optimise };
  8408. end;
  8409. end;
  8410. if Result then
  8411. begin
  8412. { Just so we have something to insert as a paremeter}
  8413. reference_reset(NewRef, 1, []);
  8414. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8415. { Now actually load the correct parameter (this also
  8416. increases the reference count) }
  8417. NewInstr.loadsymbol(0, DestLabel, 0);
  8418. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8419. begin
  8420. { Get instruction before original label (may not be p under -O3) }
  8421. if not GetLastInstruction(hp1, hp2) then
  8422. { Shouldn't fail here }
  8423. InternalError(2021040701);
  8424. { Before the aligns too }
  8425. while (hp2.typ = ait_align) do
  8426. if not GetLastInstruction(hp2, hp2) then
  8427. { Shouldn't fail here }
  8428. InternalError(2021040702);
  8429. end
  8430. else
  8431. hp2 := p;
  8432. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8433. AsmL.InsertAfter(NewInstr, hp2);
  8434. { Add new alignment field }
  8435. (* AsmL.InsertAfter(
  8436. cai_align.create_max(
  8437. current_settings.alignment.jumpalign,
  8438. current_settings.alignment.jumpalignskipmax
  8439. ),
  8440. NewInstr
  8441. ); *)
  8442. end;
  8443. Exit;
  8444. end;
  8445. end;
  8446. else
  8447. ;
  8448. end;
  8449. end;
  8450. if not GetNextInstruction(p, hp1) then
  8451. Exit;
  8452. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8453. and DoMovCmpMemOpt(p, hp1) then
  8454. begin
  8455. Result := True;
  8456. Exit;
  8457. end
  8458. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8459. begin
  8460. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8461. further, but we can't just put this jump optimisation in pass 1
  8462. because it tends to perform worse when conditional jumps are
  8463. nearby (e.g. when converting CMOV instructions). [Kit] }
  8464. CopyUsedRegs(TempTracking);
  8465. UpdateUsedRegs(tai(p.Next));
  8466. if OptPass2JMP(hp1) then
  8467. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8468. Result := OptPass1MOV(p);
  8469. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8470. returned True and the instruction is still a MOV, thus checking
  8471. the optimisations below }
  8472. { If OptPass2JMP returned False, no optimisations were done to
  8473. the jump and there are no further optimisations that can be done
  8474. to the MOV instruction on this pass }
  8475. { Restore register state }
  8476. RestoreUsedRegs(TempTracking);
  8477. ReleaseUsedRegs(TempTracking);
  8478. end
  8479. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8480. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8481. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8482. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8483. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8484. begin
  8485. { Change:
  8486. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8487. addl/q $x,%reg2 subl/q $x,%reg2
  8488. To:
  8489. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8490. }
  8491. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8492. { be lazy, checking separately for sub would be slightly better }
  8493. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8494. begin
  8495. TransferUsedRegs(TmpUsedRegs);
  8496. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8497. if TryMovArith2Lea(hp1) then
  8498. begin
  8499. Result := True;
  8500. Exit;
  8501. end
  8502. end
  8503. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8504. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8505. { Same as above, but also adds or subtracts to %reg2 in between.
  8506. It's still valid as long as the flags aren't in use }
  8507. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8508. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8509. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8510. { be lazy, checking separately for sub would be slightly better }
  8511. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8512. begin
  8513. TransferUsedRegs(TmpUsedRegs);
  8514. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8515. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8516. if TryMovArith2Lea(hp2) then
  8517. begin
  8518. Result := True;
  8519. Exit;
  8520. end;
  8521. end;
  8522. end
  8523. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8524. {$ifdef x86_64}
  8525. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8526. {$else x86_64}
  8527. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8528. {$endif x86_64}
  8529. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8530. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8531. { mov reg1, reg2 mov reg1, reg2
  8532. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8533. begin
  8534. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8535. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8536. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8537. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8538. TransferUsedRegs(TmpUsedRegs);
  8539. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8540. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8541. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8542. then
  8543. begin
  8544. RemoveCurrentP(p, hp1);
  8545. Result:=true;
  8546. end;
  8547. exit;
  8548. end
  8549. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8550. IsXCHGAcceptable and
  8551. { XCHG doesn't support 8-byte registers }
  8552. (taicpu(p).opsize <> S_B) and
  8553. MatchInstruction(hp1, A_MOV, []) and
  8554. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8555. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8556. GetNextInstruction(hp1, hp2) and
  8557. MatchInstruction(hp2, A_MOV, []) and
  8558. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8559. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8560. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8561. begin
  8562. { mov %reg1,%reg2
  8563. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8564. mov %reg2,%reg3
  8565. (%reg2 not used afterwards)
  8566. Note that xchg takes 3 cycles to execute, and generally mov's take
  8567. only one cycle apiece, but the first two mov's can be executed in
  8568. parallel, only taking 2 cycles overall. Older processors should
  8569. therefore only optimise for size. [Kit]
  8570. }
  8571. TransferUsedRegs(TmpUsedRegs);
  8572. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8573. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8574. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8575. begin
  8576. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8577. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8578. taicpu(hp1).opcode := A_XCHG;
  8579. RemoveCurrentP(p, hp1);
  8580. RemoveInstruction(hp2);
  8581. Result := True;
  8582. Exit;
  8583. end;
  8584. end
  8585. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8586. MatchInstruction(hp1, A_SAR, []) then
  8587. begin
  8588. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8589. begin
  8590. { the use of %edx also covers the opsize being S_L }
  8591. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8592. begin
  8593. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8594. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8595. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8596. begin
  8597. { Change:
  8598. movl %eax,%edx
  8599. sarl $31,%edx
  8600. To:
  8601. cltd
  8602. }
  8603. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8604. RemoveInstruction(hp1);
  8605. taicpu(p).opcode := A_CDQ;
  8606. taicpu(p).opsize := S_NO;
  8607. taicpu(p).clearop(1);
  8608. taicpu(p).clearop(0);
  8609. taicpu(p).ops:=0;
  8610. Result := True;
  8611. end
  8612. else if (cs_opt_size in current_settings.optimizerswitches) and
  8613. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8614. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8615. begin
  8616. { Change:
  8617. movl %edx,%eax
  8618. sarl $31,%edx
  8619. To:
  8620. movl %edx,%eax
  8621. cltd
  8622. Note that this creates a dependency between the two instructions,
  8623. so only perform if optimising for size.
  8624. }
  8625. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8626. taicpu(hp1).opcode := A_CDQ;
  8627. taicpu(hp1).opsize := S_NO;
  8628. taicpu(hp1).clearop(1);
  8629. taicpu(hp1).clearop(0);
  8630. taicpu(hp1).ops:=0;
  8631. end;
  8632. {$ifndef x86_64}
  8633. end
  8634. { Don't bother if CMOV is supported, because a more optimal
  8635. sequence would have been generated for the Abs() intrinsic }
  8636. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8637. { the use of %eax also covers the opsize being S_L }
  8638. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8639. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8640. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8641. GetNextInstruction(hp1, hp2) and
  8642. MatchInstruction(hp2, A_XOR, [S_L]) and
  8643. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8644. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8645. GetNextInstruction(hp2, hp3) and
  8646. MatchInstruction(hp3, A_SUB, [S_L]) and
  8647. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8648. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8649. begin
  8650. { Change:
  8651. movl %eax,%edx
  8652. sarl $31,%eax
  8653. xorl %eax,%edx
  8654. subl %eax,%edx
  8655. (Instruction that uses %edx)
  8656. (%eax deallocated)
  8657. (%edx deallocated)
  8658. To:
  8659. cltd
  8660. xorl %edx,%eax <-- Note the registers have swapped
  8661. subl %edx,%eax
  8662. (Instruction that uses %eax) <-- %eax rather than %edx
  8663. }
  8664. TransferUsedRegs(TmpUsedRegs);
  8665. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8666. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8667. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8668. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8669. begin
  8670. if GetNextInstruction(hp3, hp4) and
  8671. not RegModifiedByInstruction(NR_EDX, hp4) and
  8672. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8673. begin
  8674. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8675. taicpu(p).opcode := A_CDQ;
  8676. taicpu(p).clearop(1);
  8677. taicpu(p).clearop(0);
  8678. taicpu(p).ops:=0;
  8679. RemoveInstruction(hp1);
  8680. taicpu(hp2).loadreg(0, NR_EDX);
  8681. taicpu(hp2).loadreg(1, NR_EAX);
  8682. taicpu(hp3).loadreg(0, NR_EDX);
  8683. taicpu(hp3).loadreg(1, NR_EAX);
  8684. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8685. { Convert references in the following instruction (hp4) from %edx to %eax }
  8686. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8687. with taicpu(hp4).oper[OperIdx]^ do
  8688. case typ of
  8689. top_reg:
  8690. if getsupreg(reg) = RS_EDX then
  8691. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8692. top_ref:
  8693. begin
  8694. if getsupreg(reg) = RS_EDX then
  8695. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8696. if getsupreg(reg) = RS_EDX then
  8697. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8698. end;
  8699. else
  8700. ;
  8701. end;
  8702. end;
  8703. end;
  8704. {$else x86_64}
  8705. end;
  8706. end
  8707. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8708. { the use of %rdx also covers the opsize being S_Q }
  8709. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8710. begin
  8711. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8712. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8713. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8714. begin
  8715. { Change:
  8716. movq %rax,%rdx
  8717. sarq $63,%rdx
  8718. To:
  8719. cqto
  8720. }
  8721. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8722. RemoveInstruction(hp1);
  8723. taicpu(p).opcode := A_CQO;
  8724. taicpu(p).opsize := S_NO;
  8725. taicpu(p).clearop(1);
  8726. taicpu(p).clearop(0);
  8727. taicpu(p).ops:=0;
  8728. Result := True;
  8729. end
  8730. else if (cs_opt_size in current_settings.optimizerswitches) and
  8731. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8732. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8733. begin
  8734. { Change:
  8735. movq %rdx,%rax
  8736. sarq $63,%rdx
  8737. To:
  8738. movq %rdx,%rax
  8739. cqto
  8740. Note that this creates a dependency between the two instructions,
  8741. so only perform if optimising for size.
  8742. }
  8743. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8744. taicpu(hp1).opcode := A_CQO;
  8745. taicpu(hp1).opsize := S_NO;
  8746. taicpu(hp1).clearop(1);
  8747. taicpu(hp1).clearop(0);
  8748. taicpu(hp1).ops:=0;
  8749. {$endif x86_64}
  8750. end;
  8751. end;
  8752. end
  8753. else if MatchInstruction(hp1, A_MOV, []) and
  8754. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8755. { Though "GetNextInstruction" could be factored out, along with
  8756. the instructions that depend on hp2, it is an expensive call that
  8757. should be delayed for as long as possible, hence we do cheaper
  8758. checks first that are likely to be False. [Kit] }
  8759. begin
  8760. if (
  8761. (
  8762. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8763. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8764. (
  8765. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8766. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8767. )
  8768. ) or
  8769. (
  8770. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8771. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8772. (
  8773. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8774. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8775. )
  8776. )
  8777. ) and
  8778. GetNextInstruction(hp1, hp2) and
  8779. MatchInstruction(hp2, A_SAR, []) and
  8780. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8781. begin
  8782. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8783. begin
  8784. { Change:
  8785. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8786. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8787. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8788. To:
  8789. movl r/m,%eax <- Note the change in register
  8790. cltd
  8791. }
  8792. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8793. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8794. taicpu(p).loadreg(1, NR_EAX);
  8795. taicpu(hp1).opcode := A_CDQ;
  8796. taicpu(hp1).clearop(1);
  8797. taicpu(hp1).clearop(0);
  8798. taicpu(hp1).ops:=0;
  8799. RemoveInstruction(hp2);
  8800. (*
  8801. {$ifdef x86_64}
  8802. end
  8803. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8804. { This code sequence does not get generated - however it might become useful
  8805. if and when 128-bit signed integer types make an appearance, so the code
  8806. is kept here for when it is eventually needed. [Kit] }
  8807. (
  8808. (
  8809. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8810. (
  8811. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8812. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8813. )
  8814. ) or
  8815. (
  8816. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8817. (
  8818. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8819. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8820. )
  8821. )
  8822. ) and
  8823. GetNextInstruction(hp1, hp2) and
  8824. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8825. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8826. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8827. begin
  8828. { Change:
  8829. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8830. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8831. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8832. To:
  8833. movq r/m,%rax <- Note the change in register
  8834. cqto
  8835. }
  8836. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8837. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8838. taicpu(p).loadreg(1, NR_RAX);
  8839. taicpu(hp1).opcode := A_CQO;
  8840. taicpu(hp1).clearop(1);
  8841. taicpu(hp1).clearop(0);
  8842. taicpu(hp1).ops:=0;
  8843. RemoveInstruction(hp2);
  8844. {$endif x86_64}
  8845. *)
  8846. end;
  8847. end;
  8848. {$ifdef x86_64}
  8849. end
  8850. else if (taicpu(p).opsize = S_L) and
  8851. (taicpu(p).oper[1]^.typ = top_reg) and
  8852. (
  8853. MatchInstruction(hp1, A_MOV,[]) and
  8854. (taicpu(hp1).opsize = S_L) and
  8855. (taicpu(hp1).oper[1]^.typ = top_reg)
  8856. ) and (
  8857. GetNextInstruction(hp1, hp2) and
  8858. (tai(hp2).typ=ait_instruction) and
  8859. (taicpu(hp2).opsize = S_Q) and
  8860. (
  8861. (
  8862. MatchInstruction(hp2, A_ADD,[]) and
  8863. (taicpu(hp2).opsize = S_Q) and
  8864. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8865. (
  8866. (
  8867. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8868. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8869. ) or (
  8870. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8871. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8872. )
  8873. )
  8874. ) or (
  8875. MatchInstruction(hp2, A_LEA,[]) and
  8876. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8877. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8878. (
  8879. (
  8880. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8881. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8882. ) or (
  8883. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8884. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8885. )
  8886. ) and (
  8887. (
  8888. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8889. ) or (
  8890. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8891. )
  8892. )
  8893. )
  8894. )
  8895. ) and (
  8896. GetNextInstruction(hp2, hp3) and
  8897. MatchInstruction(hp3, A_SHR,[]) and
  8898. (taicpu(hp3).opsize = S_Q) and
  8899. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8900. (taicpu(hp3).oper[0]^.val = 1) and
  8901. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8902. ) then
  8903. begin
  8904. { Change movl x, reg1d movl x, reg1d
  8905. movl y, reg2d movl y, reg2d
  8906. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8907. shrq $1, reg1q shrq $1, reg1q
  8908. ( reg1d and reg2d can be switched around in the first two instructions )
  8909. To movl x, reg1d
  8910. addl y, reg1d
  8911. rcrl $1, reg1d
  8912. This corresponds to the common expression (x + y) shr 1, where
  8913. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8914. smaller code, but won't account for x + y causing an overflow). [Kit]
  8915. }
  8916. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  8917. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8918. { Change first MOV command to have the same register as the final output }
  8919. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8920. else
  8921. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8922. { Change second MOV command to an ADD command. This is easier than
  8923. converting the existing command because it means we don't have to
  8924. touch 'y', which might be a complicated reference, and also the
  8925. fact that the third command might either be ADD or LEA. [Kit] }
  8926. taicpu(hp1).opcode := A_ADD;
  8927. { Delete old ADD/LEA instruction }
  8928. RemoveInstruction(hp2);
  8929. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8930. taicpu(hp3).opcode := A_RCR;
  8931. taicpu(hp3).changeopsize(S_L);
  8932. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8933. {$endif x86_64}
  8934. end;
  8935. if FuncMov2Func(p, hp1) then
  8936. begin
  8937. Result := True;
  8938. Exit;
  8939. end;
  8940. end;
  8941. {$push}
  8942. {$q-}{$r-}
  8943. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8944. var
  8945. ThisReg: TRegister;
  8946. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8947. TargetSubReg: TSubRegister;
  8948. hp1, hp2: tai;
  8949. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8950. { Store list of found instructions so we don't have to call
  8951. GetNextInstructionUsingReg multiple times }
  8952. InstrList: array of taicpu;
  8953. InstrMax, Index: Integer;
  8954. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8955. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8956. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8957. WorkingValue: TCgInt;
  8958. PreMessage: string;
  8959. { Data flow analysis }
  8960. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8961. BitwiseOnly, OrXorUsed,
  8962. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8963. function CheckOverflowConditions: Boolean;
  8964. begin
  8965. Result := True;
  8966. if (TestValSignedMax > SignedUpperLimit) then
  8967. UpperSignedOverflow := True;
  8968. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8969. LowerSignedOverflow := True;
  8970. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8971. LowerUnsignedOverflow := True;
  8972. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8973. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8974. begin
  8975. { Absolute overflow }
  8976. Result := False;
  8977. Exit;
  8978. end;
  8979. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8980. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8981. ShiftDownOverflow := True;
  8982. if (TestValMin < 0) or (TestValMax < 0) then
  8983. begin
  8984. LowerUnsignedOverflow := True;
  8985. UpperUnsignedOverflow := True;
  8986. end;
  8987. end;
  8988. function AdjustInitialLoadAndSize: Boolean;
  8989. begin
  8990. Result := False;
  8991. if not p_removed then
  8992. begin
  8993. if TargetSize = MinSize then
  8994. begin
  8995. { Convert the input MOVZX to a MOV }
  8996. if (taicpu(p).oper[0]^.typ = top_reg) and
  8997. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8998. begin
  8999. { Or remove it completely! }
  9000. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9001. RemoveCurrentP(p);
  9002. p_removed := True;
  9003. end
  9004. else
  9005. begin
  9006. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9007. taicpu(p).opcode := A_MOV;
  9008. taicpu(p).oper[1]^.reg := ThisReg;
  9009. taicpu(p).opsize := TargetSize;
  9010. end;
  9011. Result := True;
  9012. end
  9013. else if TargetSize <> MaxSize then
  9014. begin
  9015. case MaxSize of
  9016. S_L:
  9017. if TargetSize = S_W then
  9018. begin
  9019. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9020. taicpu(p).opsize := S_BW;
  9021. taicpu(p).oper[1]^.reg := ThisReg;
  9022. Result := True;
  9023. end
  9024. else
  9025. InternalError(2020112341);
  9026. S_W:
  9027. if TargetSize = S_L then
  9028. begin
  9029. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9030. taicpu(p).opsize := S_BL;
  9031. taicpu(p).oper[1]^.reg := ThisReg;
  9032. Result := True;
  9033. end
  9034. else
  9035. InternalError(2020112342);
  9036. else
  9037. ;
  9038. end;
  9039. end
  9040. else if not hp1_removed and not RegInUse then
  9041. begin
  9042. { If we have something like:
  9043. movzbl (oper),%regd
  9044. add x, %regd
  9045. movzbl %regb, %regd
  9046. We can reduce the register size to the input of the final
  9047. movzbl instruction. Overflows won't have any effect.
  9048. }
  9049. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9050. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9051. begin
  9052. TargetSize := S_B;
  9053. setsubreg(ThisReg, R_SUBL);
  9054. Result := True;
  9055. end
  9056. else if (taicpu(p).opsize = S_WL) and
  9057. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9058. begin
  9059. TargetSize := S_W;
  9060. setsubreg(ThisReg, R_SUBW);
  9061. Result := True;
  9062. end;
  9063. if Result then
  9064. begin
  9065. { Convert the input MOVZX to a MOV }
  9066. if (taicpu(p).oper[0]^.typ = top_reg) and
  9067. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9068. begin
  9069. { Or remove it completely! }
  9070. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9071. RemoveCurrentP(p);
  9072. p_removed := True;
  9073. end
  9074. else
  9075. begin
  9076. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9077. taicpu(p).opcode := A_MOV;
  9078. taicpu(p).oper[1]^.reg := ThisReg;
  9079. taicpu(p).opsize := TargetSize;
  9080. end;
  9081. end;
  9082. end;
  9083. end;
  9084. end;
  9085. procedure AdjustFinalLoad;
  9086. begin
  9087. if not LowerUnsignedOverflow then
  9088. begin
  9089. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9090. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9091. begin
  9092. { Convert the output MOVZX to a MOV }
  9093. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9094. begin
  9095. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9096. if (MinSize = S_B) or
  9097. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9098. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9099. begin
  9100. { Remove it completely! }
  9101. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9102. { Be careful; if p = hp1 and p was also removed, p
  9103. will become a dangling pointer }
  9104. if p = hp1 then
  9105. begin
  9106. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9107. p_removed := True;
  9108. end
  9109. else
  9110. RemoveInstruction(hp1);
  9111. hp1_removed := True;
  9112. end;
  9113. end
  9114. else
  9115. begin
  9116. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9117. taicpu(hp1).opcode := A_MOV;
  9118. taicpu(hp1).oper[0]^.reg := ThisReg;
  9119. taicpu(hp1).opsize := TargetSize;
  9120. end;
  9121. end
  9122. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9123. begin
  9124. { Need to change the size of the output }
  9125. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9126. taicpu(hp1).oper[0]^.reg := ThisReg;
  9127. taicpu(hp1).opsize := S_BL;
  9128. end;
  9129. end;
  9130. end;
  9131. function CompressInstructions: Boolean;
  9132. var
  9133. LocalIndex: Integer;
  9134. begin
  9135. Result := False;
  9136. { The objective here is to try to find a combination that
  9137. removes one of the MOV/Z instructions. }
  9138. if (
  9139. (taicpu(p).oper[0]^.typ <> top_reg) or
  9140. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9141. ) and
  9142. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9143. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9144. begin
  9145. { Make a preference to remove the second MOVZX instruction }
  9146. case taicpu(hp1).opsize of
  9147. S_BL, S_WL:
  9148. begin
  9149. TargetSize := S_L;
  9150. TargetSubReg := R_SUBD;
  9151. end;
  9152. S_BW:
  9153. begin
  9154. TargetSize := S_W;
  9155. TargetSubReg := R_SUBW;
  9156. end;
  9157. else
  9158. InternalError(2020112302);
  9159. end;
  9160. end
  9161. else
  9162. begin
  9163. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9164. begin
  9165. { Exceeded lower bound but not upper bound }
  9166. TargetSize := MaxSize;
  9167. end
  9168. else if not LowerUnsignedOverflow then
  9169. begin
  9170. { Size didn't exceed lower bound }
  9171. TargetSize := MinSize;
  9172. end
  9173. else
  9174. Exit;
  9175. end;
  9176. case TargetSize of
  9177. S_B:
  9178. TargetSubReg := R_SUBL;
  9179. S_W:
  9180. TargetSubReg := R_SUBW;
  9181. S_L:
  9182. TargetSubReg := R_SUBD;
  9183. else
  9184. InternalError(2020112350);
  9185. end;
  9186. { Update the register to its new size }
  9187. setsubreg(ThisReg, TargetSubReg);
  9188. RegInUse := False;
  9189. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9190. begin
  9191. { Check to see if the active register is used afterwards;
  9192. if not, we can change it and make a saving. }
  9193. TransferUsedRegs(TmpUsedRegs);
  9194. { The target register may be marked as in use to cross
  9195. a jump to a distant label, so exclude it }
  9196. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9197. hp2 := p;
  9198. repeat
  9199. { Explicitly check for the excluded register (don't include the first
  9200. instruction as it may be reading from here }
  9201. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9202. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9203. begin
  9204. RegInUse := True;
  9205. Break;
  9206. end;
  9207. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9208. if not GetNextInstruction(hp2, hp2) then
  9209. InternalError(2020112340);
  9210. until (hp2 = hp1);
  9211. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9212. { We might still be able to get away with this }
  9213. RegInUse := not
  9214. (
  9215. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9216. (hp2.typ = ait_instruction) and
  9217. (
  9218. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9219. instruction that doesn't actually contain ThisReg }
  9220. (cs_opt_level3 in current_settings.optimizerswitches) or
  9221. RegInInstruction(ThisReg, hp2)
  9222. ) and
  9223. RegLoadedWithNewValue(ThisReg, hp2)
  9224. );
  9225. if not RegInUse then
  9226. begin
  9227. { Force the register size to the same as this instruction so it can be removed}
  9228. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9229. begin
  9230. TargetSize := S_L;
  9231. TargetSubReg := R_SUBD;
  9232. end
  9233. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9234. begin
  9235. TargetSize := S_W;
  9236. TargetSubReg := R_SUBW;
  9237. end;
  9238. ThisReg := taicpu(hp1).oper[1]^.reg;
  9239. setsubreg(ThisReg, TargetSubReg);
  9240. RegChanged := True;
  9241. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9242. TransferUsedRegs(TmpUsedRegs);
  9243. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9244. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9245. if p = hp1 then
  9246. begin
  9247. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9248. p_removed := True;
  9249. end
  9250. else
  9251. RemoveInstruction(hp1);
  9252. hp1_removed := True;
  9253. { Instruction will become "mov %reg,%reg" }
  9254. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9255. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9256. begin
  9257. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9258. RemoveCurrentP(p);
  9259. p_removed := True;
  9260. end
  9261. else
  9262. taicpu(p).oper[1]^.reg := ThisReg;
  9263. Result := True;
  9264. end
  9265. else
  9266. begin
  9267. if TargetSize <> MaxSize then
  9268. begin
  9269. { Since the register is in use, we have to force it to
  9270. MaxSize otherwise part of it may become undefined later on }
  9271. TargetSize := MaxSize;
  9272. case TargetSize of
  9273. S_B:
  9274. TargetSubReg := R_SUBL;
  9275. S_W:
  9276. TargetSubReg := R_SUBW;
  9277. S_L:
  9278. TargetSubReg := R_SUBD;
  9279. else
  9280. InternalError(2020112351);
  9281. end;
  9282. setsubreg(ThisReg, TargetSubReg);
  9283. end;
  9284. AdjustFinalLoad;
  9285. end;
  9286. end
  9287. else
  9288. AdjustFinalLoad;
  9289. Result := AdjustInitialLoadAndSize or Result;
  9290. { Now go through every instruction we found and change the
  9291. size. If TargetSize = MaxSize, then almost no changes are
  9292. needed and Result can remain False if it hasn't been set
  9293. yet.
  9294. If RegChanged is True, then the register requires changing
  9295. and so the point about TargetSize = MaxSize doesn't apply. }
  9296. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9297. begin
  9298. for LocalIndex := 0 to InstrMax do
  9299. begin
  9300. { If p_removed is true, then the original MOV/Z was removed
  9301. and removing the AND instruction may not be safe if it
  9302. appears first }
  9303. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9304. InternalError(2020112310);
  9305. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9306. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9307. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9308. InstrList[LocalIndex].opsize := TargetSize;
  9309. end;
  9310. Result := True;
  9311. end;
  9312. end;
  9313. begin
  9314. Result := False;
  9315. p_removed := False;
  9316. hp1_removed := False;
  9317. ThisReg := taicpu(p).oper[1]^.reg;
  9318. { Check for:
  9319. movs/z ###,%ecx (or %cx or %rcx)
  9320. ...
  9321. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9322. (dealloc %ecx)
  9323. Change to:
  9324. mov ###,%cl (if ### = %cl, then remove completely)
  9325. ...
  9326. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9327. }
  9328. if (getsupreg(ThisReg) = RS_ECX) and
  9329. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9330. (hp1.typ = ait_instruction) and
  9331. (
  9332. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9333. instruction that doesn't actually contain ECX }
  9334. (cs_opt_level3 in current_settings.optimizerswitches) or
  9335. RegInInstruction(NR_ECX, hp1) or
  9336. (
  9337. { It's common for the shift/rotate's read/write register to be
  9338. initialised in between, so under -O2 and under, search ahead
  9339. one more instruction
  9340. }
  9341. GetNextInstruction(hp1, hp1) and
  9342. (hp1.typ = ait_instruction) and
  9343. RegInInstruction(NR_ECX, hp1)
  9344. )
  9345. ) and
  9346. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9347. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9348. begin
  9349. TransferUsedRegs(TmpUsedRegs);
  9350. hp2 := p;
  9351. repeat
  9352. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9353. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9354. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9355. begin
  9356. case taicpu(p).opsize of
  9357. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9358. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9359. begin
  9360. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9361. RemoveCurrentP(p);
  9362. end
  9363. else
  9364. begin
  9365. taicpu(p).opcode := A_MOV;
  9366. taicpu(p).opsize := S_B;
  9367. taicpu(p).oper[1]^.reg := NR_CL;
  9368. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9369. end;
  9370. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9371. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9372. begin
  9373. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9374. RemoveCurrentP(p);
  9375. end
  9376. else
  9377. begin
  9378. taicpu(p).opcode := A_MOV;
  9379. taicpu(p).opsize := S_W;
  9380. taicpu(p).oper[1]^.reg := NR_CX;
  9381. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9382. end;
  9383. {$ifdef x86_64}
  9384. S_LQ:
  9385. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9386. begin
  9387. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9388. RemoveCurrentP(p);
  9389. end
  9390. else
  9391. begin
  9392. taicpu(p).opcode := A_MOV;
  9393. taicpu(p).opsize := S_L;
  9394. taicpu(p).oper[1]^.reg := NR_ECX;
  9395. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9396. end;
  9397. {$endif x86_64}
  9398. else
  9399. InternalError(2021120401);
  9400. end;
  9401. Result := True;
  9402. Exit;
  9403. end;
  9404. end;
  9405. { This is anything but quick! }
  9406. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9407. Exit;
  9408. SetLength(InstrList, 0);
  9409. InstrMax := -1;
  9410. case taicpu(p).opsize of
  9411. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9412. begin
  9413. {$if defined(i386) or defined(i8086)}
  9414. { If the target size is 8-bit, make sure we can actually encode it }
  9415. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9416. Exit;
  9417. {$endif i386 or i8086}
  9418. LowerLimit := $FF;
  9419. SignedLowerLimit := $7F;
  9420. SignedLowerLimitBottom := -128;
  9421. MinSize := S_B;
  9422. if taicpu(p).opsize = S_BW then
  9423. begin
  9424. MaxSize := S_W;
  9425. UpperLimit := $FFFF;
  9426. SignedUpperLimit := $7FFF;
  9427. SignedUpperLimitBottom := -32768;
  9428. end
  9429. else
  9430. begin
  9431. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9432. MaxSize := S_L;
  9433. UpperLimit := $FFFFFFFF;
  9434. SignedUpperLimit := $7FFFFFFF;
  9435. SignedUpperLimitBottom := -2147483648;
  9436. end;
  9437. end;
  9438. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9439. begin
  9440. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9441. LowerLimit := $FFFF;
  9442. SignedLowerLimit := $7FFF;
  9443. SignedLowerLimitBottom := -32768;
  9444. UpperLimit := $FFFFFFFF;
  9445. SignedUpperLimit := $7FFFFFFF;
  9446. SignedUpperLimitBottom := -2147483648;
  9447. MinSize := S_W;
  9448. MaxSize := S_L;
  9449. end;
  9450. {$ifdef x86_64}
  9451. S_LQ:
  9452. begin
  9453. { Both the lower and upper limits are set to 32-bit. If a limit
  9454. is breached, then optimisation is impossible }
  9455. LowerLimit := $FFFFFFFF;
  9456. SignedLowerLimit := $7FFFFFFF;
  9457. SignedLowerLimitBottom := -2147483648;
  9458. UpperLimit := $FFFFFFFF;
  9459. SignedUpperLimit := $7FFFFFFF;
  9460. SignedUpperLimitBottom := -2147483648;
  9461. MinSize := S_L;
  9462. MaxSize := S_L;
  9463. end;
  9464. {$endif x86_64}
  9465. else
  9466. InternalError(2020112301);
  9467. end;
  9468. TestValMin := 0;
  9469. TestValMax := LowerLimit;
  9470. TestValSignedMax := SignedLowerLimit;
  9471. TryShiftDownLimit := LowerLimit;
  9472. TryShiftDown := S_NO;
  9473. ShiftDownOverflow := False;
  9474. RegChanged := False;
  9475. BitwiseOnly := True;
  9476. OrXorUsed := False;
  9477. UpperSignedOverflow := False;
  9478. LowerSignedOverflow := False;
  9479. UpperUnsignedOverflow := False;
  9480. LowerUnsignedOverflow := False;
  9481. hp1 := p;
  9482. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9483. (hp1.typ = ait_instruction) and
  9484. (
  9485. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9486. instruction that doesn't actually contain ThisReg }
  9487. (cs_opt_level3 in current_settings.optimizerswitches) or
  9488. { This allows this Movx optimisation to work through the SETcc instructions
  9489. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9490. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9491. skip over these SETcc instructions). }
  9492. (taicpu(hp1).opcode = A_SETcc) or
  9493. RegInInstruction(ThisReg, hp1)
  9494. ) do
  9495. begin
  9496. case taicpu(hp1).opcode of
  9497. A_INC,A_DEC:
  9498. begin
  9499. { Has to be an exact match on the register }
  9500. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9501. Break;
  9502. if taicpu(hp1).opcode = A_INC then
  9503. begin
  9504. Inc(TestValMin);
  9505. Inc(TestValMax);
  9506. Inc(TestValSignedMax);
  9507. end
  9508. else
  9509. begin
  9510. Dec(TestValMin);
  9511. Dec(TestValMax);
  9512. Dec(TestValSignedMax);
  9513. end;
  9514. end;
  9515. A_TEST, A_CMP:
  9516. begin
  9517. if (
  9518. { Too high a risk of non-linear behaviour that breaks DFA
  9519. here, unless it's cmp $0,%reg, which is equivalent to
  9520. test %reg,%reg }
  9521. OrXorUsed and
  9522. (taicpu(hp1).opcode = A_CMP) and
  9523. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9524. ) or
  9525. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9526. { Has to be an exact match on the register }
  9527. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9528. (
  9529. { Permit "test %reg,%reg" }
  9530. (taicpu(hp1).opcode = A_TEST) and
  9531. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9532. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9533. ) or
  9534. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9535. { Make sure the comparison value is not smaller than the
  9536. smallest allowed signed value for the minimum size (e.g.
  9537. -128 for 8-bit) }
  9538. not (
  9539. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9540. { Is it in the negative range? }
  9541. (
  9542. (taicpu(hp1).oper[0]^.val < 0) and
  9543. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9544. )
  9545. ) then
  9546. Break;
  9547. { Check to see if the active register is used afterwards }
  9548. TransferUsedRegs(TmpUsedRegs);
  9549. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9550. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9551. begin
  9552. { Make sure the comparison or any previous instructions
  9553. hasn't pushed the test values outside of the range of
  9554. MinSize }
  9555. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9556. begin
  9557. { Exceeded lower bound but not upper bound }
  9558. Exit;
  9559. end
  9560. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9561. begin
  9562. { Size didn't exceed lower bound }
  9563. TargetSize := MinSize;
  9564. end
  9565. else
  9566. Break;
  9567. case TargetSize of
  9568. S_B:
  9569. TargetSubReg := R_SUBL;
  9570. S_W:
  9571. TargetSubReg := R_SUBW;
  9572. S_L:
  9573. TargetSubReg := R_SUBD;
  9574. else
  9575. InternalError(2021051002);
  9576. end;
  9577. if TargetSize <> MaxSize then
  9578. begin
  9579. { Update the register to its new size }
  9580. setsubreg(ThisReg, TargetSubReg);
  9581. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9582. taicpu(hp1).oper[1]^.reg := ThisReg;
  9583. taicpu(hp1).opsize := TargetSize;
  9584. { Convert the input MOVZX to a MOV if necessary }
  9585. AdjustInitialLoadAndSize;
  9586. if (InstrMax >= 0) then
  9587. begin
  9588. for Index := 0 to InstrMax do
  9589. begin
  9590. { If p_removed is true, then the original MOV/Z was removed
  9591. and removing the AND instruction may not be safe if it
  9592. appears first }
  9593. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9594. InternalError(2020112311);
  9595. if InstrList[Index].oper[0]^.typ = top_reg then
  9596. InstrList[Index].oper[0]^.reg := ThisReg;
  9597. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9598. InstrList[Index].opsize := MinSize;
  9599. end;
  9600. end;
  9601. Result := True;
  9602. end;
  9603. Exit;
  9604. end;
  9605. end;
  9606. A_SETcc:
  9607. begin
  9608. { This allows this Movx optimisation to work through the SETcc instructions
  9609. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9610. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9611. skip over these SETcc instructions). }
  9612. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9613. { Of course, break out if the current register is used }
  9614. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9615. Break
  9616. else
  9617. { We must use Continue so the instruction doesn't get added
  9618. to InstrList }
  9619. Continue;
  9620. end;
  9621. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9622. begin
  9623. if
  9624. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9625. { Has to be an exact match on the register }
  9626. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9627. (
  9628. (
  9629. (taicpu(hp1).oper[0]^.typ = top_const) and
  9630. (
  9631. (
  9632. (taicpu(hp1).opcode = A_SHL) and
  9633. (
  9634. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9635. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9636. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9637. )
  9638. ) or (
  9639. (taicpu(hp1).opcode <> A_SHL) and
  9640. (
  9641. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9642. { Is it in the negative range? }
  9643. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9644. )
  9645. )
  9646. )
  9647. ) or (
  9648. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9649. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9650. )
  9651. ) then
  9652. Break;
  9653. { Only process OR and XOR if there are only bitwise operations,
  9654. since otherwise they can too easily fool the data flow
  9655. analysis (they can cause non-linear behaviour) }
  9656. case taicpu(hp1).opcode of
  9657. A_ADD:
  9658. begin
  9659. if OrXorUsed then
  9660. { Too high a risk of non-linear behaviour that breaks DFA here }
  9661. Break
  9662. else
  9663. BitwiseOnly := False;
  9664. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9665. begin
  9666. TestValMin := TestValMin * 2;
  9667. TestValMax := TestValMax * 2;
  9668. TestValSignedMax := TestValSignedMax * 2;
  9669. end
  9670. else
  9671. begin
  9672. WorkingValue := taicpu(hp1).oper[0]^.val;
  9673. TestValMin := TestValMin + WorkingValue;
  9674. TestValMax := TestValMax + WorkingValue;
  9675. TestValSignedMax := TestValSignedMax + WorkingValue;
  9676. end;
  9677. end;
  9678. A_SUB:
  9679. begin
  9680. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9681. begin
  9682. TestValMin := 0;
  9683. TestValMax := 0;
  9684. TestValSignedMax := 0;
  9685. end
  9686. else
  9687. begin
  9688. if OrXorUsed then
  9689. { Too high a risk of non-linear behaviour that breaks DFA here }
  9690. Break
  9691. else
  9692. BitwiseOnly := False;
  9693. WorkingValue := taicpu(hp1).oper[0]^.val;
  9694. TestValMin := TestValMin - WorkingValue;
  9695. TestValMax := TestValMax - WorkingValue;
  9696. TestValSignedMax := TestValSignedMax - WorkingValue;
  9697. end;
  9698. end;
  9699. A_AND:
  9700. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9701. begin
  9702. { we might be able to go smaller if AND appears first }
  9703. if InstrMax = -1 then
  9704. case MinSize of
  9705. S_B:
  9706. ;
  9707. S_W:
  9708. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9709. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9710. begin
  9711. TryShiftDown := S_B;
  9712. TryShiftDownLimit := $FF;
  9713. end;
  9714. S_L:
  9715. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9716. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9717. begin
  9718. TryShiftDown := S_B;
  9719. TryShiftDownLimit := $FF;
  9720. end
  9721. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9722. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9723. begin
  9724. TryShiftDown := S_W;
  9725. TryShiftDownLimit := $FFFF;
  9726. end;
  9727. else
  9728. InternalError(2020112320);
  9729. end;
  9730. WorkingValue := taicpu(hp1).oper[0]^.val;
  9731. TestValMin := TestValMin and WorkingValue;
  9732. TestValMax := TestValMax and WorkingValue;
  9733. TestValSignedMax := TestValSignedMax and WorkingValue;
  9734. end;
  9735. A_OR:
  9736. begin
  9737. if not BitwiseOnly then
  9738. Break;
  9739. OrXorUsed := True;
  9740. WorkingValue := taicpu(hp1).oper[0]^.val;
  9741. TestValMin := TestValMin or WorkingValue;
  9742. TestValMax := TestValMax or WorkingValue;
  9743. TestValSignedMax := TestValSignedMax or WorkingValue;
  9744. end;
  9745. A_XOR:
  9746. begin
  9747. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9748. begin
  9749. TestValMin := 0;
  9750. TestValMax := 0;
  9751. TestValSignedMax := 0;
  9752. end
  9753. else
  9754. begin
  9755. if not BitwiseOnly then
  9756. Break;
  9757. OrXorUsed := True;
  9758. WorkingValue := taicpu(hp1).oper[0]^.val;
  9759. TestValMin := TestValMin xor WorkingValue;
  9760. TestValMax := TestValMax xor WorkingValue;
  9761. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9762. end;
  9763. end;
  9764. A_SHL:
  9765. begin
  9766. BitwiseOnly := False;
  9767. WorkingValue := taicpu(hp1).oper[0]^.val;
  9768. TestValMin := TestValMin shl WorkingValue;
  9769. TestValMax := TestValMax shl WorkingValue;
  9770. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9771. end;
  9772. A_SHR,
  9773. { The first instruction was MOVZX, so the value won't be negative }
  9774. A_SAR:
  9775. begin
  9776. if InstrMax <> -1 then
  9777. BitwiseOnly := False
  9778. else
  9779. { we might be able to go smaller if SHR appears first }
  9780. case MinSize of
  9781. S_B:
  9782. ;
  9783. S_W:
  9784. if (taicpu(hp1).oper[0]^.val >= 8) then
  9785. begin
  9786. TryShiftDown := S_B;
  9787. TryShiftDownLimit := $FF;
  9788. TryShiftDownSignedLimit := $7F;
  9789. TryShiftDownSignedLimitLower := -128;
  9790. end;
  9791. S_L:
  9792. if (taicpu(hp1).oper[0]^.val >= 24) then
  9793. begin
  9794. TryShiftDown := S_B;
  9795. TryShiftDownLimit := $FF;
  9796. TryShiftDownSignedLimit := $7F;
  9797. TryShiftDownSignedLimitLower := -128;
  9798. end
  9799. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9800. begin
  9801. TryShiftDown := S_W;
  9802. TryShiftDownLimit := $FFFF;
  9803. TryShiftDownSignedLimit := $7FFF;
  9804. TryShiftDownSignedLimitLower := -32768;
  9805. end;
  9806. else
  9807. InternalError(2020112321);
  9808. end;
  9809. WorkingValue := taicpu(hp1).oper[0]^.val;
  9810. if taicpu(hp1).opcode = A_SAR then
  9811. begin
  9812. TestValMin := SarInt64(TestValMin, WorkingValue);
  9813. TestValMax := SarInt64(TestValMax, WorkingValue);
  9814. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9815. end
  9816. else
  9817. begin
  9818. TestValMin := TestValMin shr WorkingValue;
  9819. TestValMax := TestValMax shr WorkingValue;
  9820. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9821. end;
  9822. end;
  9823. else
  9824. InternalError(2020112303);
  9825. end;
  9826. end;
  9827. (*
  9828. A_IMUL:
  9829. case taicpu(hp1).ops of
  9830. 2:
  9831. begin
  9832. if not MatchOpType(hp1, top_reg, top_reg) or
  9833. { Has to be an exact match on the register }
  9834. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9835. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9836. Break;
  9837. TestValMin := TestValMin * TestValMin;
  9838. TestValMax := TestValMax * TestValMax;
  9839. TestValSignedMax := TestValSignedMax * TestValMax;
  9840. end;
  9841. 3:
  9842. begin
  9843. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9844. { Has to be an exact match on the register }
  9845. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9846. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9847. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9848. { Is it in the negative range? }
  9849. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9850. Break;
  9851. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9852. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9853. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9854. end;
  9855. else
  9856. Break;
  9857. end;
  9858. A_IDIV:
  9859. case taicpu(hp1).ops of
  9860. 3:
  9861. begin
  9862. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9863. { Has to be an exact match on the register }
  9864. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9865. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9866. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9867. { Is it in the negative range? }
  9868. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9869. Break;
  9870. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9871. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9872. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9873. end;
  9874. else
  9875. Break;
  9876. end;
  9877. *)
  9878. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9879. begin
  9880. { If there are no instructions in between, then we might be able to make a saving }
  9881. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9882. Break;
  9883. { We have something like:
  9884. movzbw %dl,%dx
  9885. ...
  9886. movswl %dx,%edx
  9887. Change the latter to a zero-extension then enter the
  9888. A_MOVZX case branch.
  9889. }
  9890. {$ifdef x86_64}
  9891. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9892. begin
  9893. { this becomes a zero extension from 32-bit to 64-bit, but
  9894. the upper 32 bits are already zero, so just delete the
  9895. instruction }
  9896. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9897. RemoveInstruction(hp1);
  9898. Result := True;
  9899. Exit;
  9900. end
  9901. else
  9902. {$endif x86_64}
  9903. begin
  9904. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9905. taicpu(hp1).opcode := A_MOVZX;
  9906. {$ifdef x86_64}
  9907. case taicpu(hp1).opsize of
  9908. S_BQ:
  9909. begin
  9910. taicpu(hp1).opsize := S_BL;
  9911. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9912. end;
  9913. S_WQ:
  9914. begin
  9915. taicpu(hp1).opsize := S_WL;
  9916. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9917. end;
  9918. S_LQ:
  9919. begin
  9920. taicpu(hp1).opcode := A_MOV;
  9921. taicpu(hp1).opsize := S_L;
  9922. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9923. { In this instance, we need to break out because the
  9924. instruction is no longer MOVZX or MOVSXD }
  9925. Result := True;
  9926. Exit;
  9927. end;
  9928. else
  9929. ;
  9930. end;
  9931. {$endif x86_64}
  9932. Result := CompressInstructions;
  9933. Exit;
  9934. end;
  9935. end;
  9936. A_MOVZX:
  9937. begin
  9938. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9939. Break;
  9940. if (InstrMax = -1) then
  9941. begin
  9942. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9943. begin
  9944. { Optimise around i40003 }
  9945. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  9946. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  9947. {$ifndef x86_64}
  9948. and (
  9949. (taicpu(p).oper[0]^.typ <> top_reg) or
  9950. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  9951. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  9952. )
  9953. {$endif not x86_64}
  9954. then
  9955. begin
  9956. if (taicpu(p).oper[0]^.typ = top_reg) then
  9957. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  9958. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  9959. taicpu(p).opsize := S_BL;
  9960. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  9961. RemoveInstruction(hp1);
  9962. Result := True;
  9963. Exit;
  9964. end;
  9965. end
  9966. else
  9967. begin
  9968. { Will return false if the second parameter isn't ThisReg
  9969. (can happen on -O2 and under) }
  9970. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9971. begin
  9972. { The two MOVZX instructions are adjacent, so remove the first one }
  9973. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  9974. RemoveCurrentP(p);
  9975. Result := True;
  9976. Exit;
  9977. end;
  9978. Break;
  9979. end;
  9980. end;
  9981. Result := CompressInstructions;
  9982. Exit;
  9983. end;
  9984. else
  9985. { This includes ADC, SBB and IDIV }
  9986. Break;
  9987. end;
  9988. if not CheckOverflowConditions then
  9989. Break;
  9990. { Contains highest index (so instruction count - 1) }
  9991. Inc(InstrMax);
  9992. if InstrMax > High(InstrList) then
  9993. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9994. InstrList[InstrMax] := taicpu(hp1);
  9995. end;
  9996. end;
  9997. {$pop}
  9998. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9999. var
  10000. hp1 : tai;
  10001. begin
  10002. Result:=false;
  10003. if (taicpu(p).ops >= 2) and
  10004. ((taicpu(p).oper[0]^.typ = top_const) or
  10005. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10006. (taicpu(p).oper[1]^.typ = top_reg) and
  10007. ((taicpu(p).ops = 2) or
  10008. ((taicpu(p).oper[2]^.typ = top_reg) and
  10009. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10010. GetLastInstruction(p,hp1) and
  10011. MatchInstruction(hp1,A_MOV,[]) and
  10012. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10013. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10014. begin
  10015. TransferUsedRegs(TmpUsedRegs);
  10016. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10017. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10018. { change
  10019. mov reg1,reg2
  10020. imul y,reg2 to imul y,reg1,reg2 }
  10021. begin
  10022. taicpu(p).ops := 3;
  10023. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10024. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10025. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10026. RemoveInstruction(hp1);
  10027. result:=true;
  10028. end;
  10029. end;
  10030. end;
  10031. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10032. var
  10033. ThisLabel: TAsmLabel;
  10034. begin
  10035. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10036. ThisLabel.decrefs;
  10037. taicpu(p).condition := C_None;
  10038. taicpu(p).opcode := A_RET;
  10039. taicpu(p).is_jmp := false;
  10040. taicpu(p).ops := taicpu(ret_p).ops;
  10041. case taicpu(ret_p).ops of
  10042. 0:
  10043. taicpu(p).clearop(0);
  10044. 1:
  10045. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10046. else
  10047. internalerror(2016041301);
  10048. end;
  10049. { If the original label is now dead, it might turn out that the label
  10050. immediately follows p. As a result, everything beyond it, which will
  10051. be just some final register configuration and a RET instruction, is
  10052. now dead code. [Kit] }
  10053. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10054. running RemoveDeadCodeAfterJump for each RET instruction, because
  10055. this optimisation rarely happens and most RETs appear at the end of
  10056. routines where there is nothing that can be stripped. [Kit] }
  10057. if not ThisLabel.is_used then
  10058. RemoveDeadCodeAfterJump(p);
  10059. end;
  10060. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10061. var
  10062. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10063. Unconditional, PotentialModified: Boolean;
  10064. OperPtr: POper;
  10065. NewRef: TReference;
  10066. InstrList: array of taicpu;
  10067. InstrMax, Index: Integer;
  10068. const
  10069. {$ifdef DEBUG_AOPTCPU}
  10070. SNoFlags: shortstring = ' so the flags aren''t modified';
  10071. {$else DEBUG_AOPTCPU}
  10072. SNoFlags = '';
  10073. {$endif DEBUG_AOPTCPU}
  10074. begin
  10075. Result:=false;
  10076. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10077. begin
  10078. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10079. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10080. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10081. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10082. GetNextInstruction(hp1, hp2) and
  10083. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10084. { Change from: To:
  10085. set(C) %reg j(~C) label
  10086. test %reg,%reg/cmp $0,%reg
  10087. je label
  10088. set(C) %reg j(C) label
  10089. test %reg,%reg/cmp $0,%reg
  10090. jne label
  10091. (Also do something similar with sete/setne instead of je/jne)
  10092. }
  10093. begin
  10094. { Before we do anything else, we need to check the instructions
  10095. in between SETcc and TEST to make sure they don't modify the
  10096. FLAGS register - if -O2 or under, there won't be any
  10097. instructions between SET and TEST }
  10098. TransferUsedRegs(TmpUsedRegs);
  10099. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10100. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10101. begin
  10102. next := p;
  10103. SetLength(InstrList, 0);
  10104. InstrMax := -1;
  10105. PotentialModified := False;
  10106. { Make a note of every instruction that modifies the FLAGS
  10107. register }
  10108. while GetNextInstruction(next, next) and (next <> hp1) do
  10109. begin
  10110. if next.typ <> ait_instruction then
  10111. { GetNextInstructionUsingReg should have returned False }
  10112. InternalError(2021051701);
  10113. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10114. begin
  10115. case taicpu(next).opcode of
  10116. A_SETcc,
  10117. A_CMOVcc,
  10118. A_Jcc:
  10119. begin
  10120. if PotentialModified then
  10121. { Not safe because the flags were modified earlier }
  10122. Exit
  10123. else
  10124. { Condition is the same as the initial SETcc, so this is safe
  10125. (don't add to instruction list though) }
  10126. Continue;
  10127. end;
  10128. A_ADD:
  10129. begin
  10130. if (taicpu(next).opsize = S_B) or
  10131. { LEA doesn't support 8-bit operands }
  10132. (taicpu(next).oper[1]^.typ <> top_reg) or
  10133. { Must write to a register }
  10134. (taicpu(next).oper[0]^.typ = top_ref) then
  10135. { Require a constant or a register }
  10136. Exit;
  10137. PotentialModified := True;
  10138. end;
  10139. A_SUB:
  10140. begin
  10141. if (taicpu(next).opsize = S_B) or
  10142. { LEA doesn't support 8-bit operands }
  10143. (taicpu(next).oper[1]^.typ <> top_reg) or
  10144. { Must write to a register }
  10145. (taicpu(next).oper[0]^.typ <> top_const) or
  10146. (taicpu(next).oper[0]^.val = $80000000) then
  10147. { Can't subtract a register with LEA - also
  10148. check that the value isn't -2^31, as this
  10149. can't be negated }
  10150. Exit;
  10151. PotentialModified := True;
  10152. end;
  10153. A_SAL,
  10154. A_SHL:
  10155. begin
  10156. if (taicpu(next).opsize = S_B) or
  10157. { LEA doesn't support 8-bit operands }
  10158. (taicpu(next).oper[1]^.typ <> top_reg) or
  10159. { Must write to a register }
  10160. (taicpu(next).oper[0]^.typ <> top_const) or
  10161. (taicpu(next).oper[0]^.val < 0) or
  10162. (taicpu(next).oper[0]^.val > 3) then
  10163. Exit;
  10164. PotentialModified := True;
  10165. end;
  10166. A_IMUL:
  10167. begin
  10168. if (taicpu(next).ops <> 3) or
  10169. (taicpu(next).oper[1]^.typ <> top_reg) or
  10170. { Must write to a register }
  10171. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10172. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10173. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10174. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10175. Exit
  10176. else
  10177. PotentialModified := True;
  10178. end;
  10179. else
  10180. { Don't know how to change this, so abort }
  10181. Exit;
  10182. end;
  10183. { Contains highest index (so instruction count - 1) }
  10184. Inc(InstrMax);
  10185. if InstrMax > High(InstrList) then
  10186. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10187. InstrList[InstrMax] := taicpu(next);
  10188. end;
  10189. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10190. end;
  10191. if not Assigned(next) or (next <> hp1) then
  10192. { It should be equal to hp1 }
  10193. InternalError(2021051702);
  10194. { Cycle through each instruction and check to see if we can
  10195. change them to versions that don't modify the flags }
  10196. if (InstrMax >= 0) then
  10197. begin
  10198. for Index := 0 to InstrMax do
  10199. case InstrList[Index].opcode of
  10200. A_ADD:
  10201. begin
  10202. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10203. InstrList[Index].opcode := A_LEA;
  10204. reference_reset(NewRef, 1, []);
  10205. NewRef.base := InstrList[Index].oper[1]^.reg;
  10206. if InstrList[Index].oper[0]^.typ = top_reg then
  10207. begin
  10208. NewRef.index := InstrList[Index].oper[0]^.reg;
  10209. NewRef.scalefactor := 1;
  10210. end
  10211. else
  10212. NewRef.offset := InstrList[Index].oper[0]^.val;
  10213. InstrList[Index].loadref(0, NewRef);
  10214. end;
  10215. A_SUB:
  10216. begin
  10217. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10218. InstrList[Index].opcode := A_LEA;
  10219. reference_reset(NewRef, 1, []);
  10220. NewRef.base := InstrList[Index].oper[1]^.reg;
  10221. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10222. InstrList[Index].loadref(0, NewRef);
  10223. end;
  10224. A_SHL,
  10225. A_SAL:
  10226. begin
  10227. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10228. InstrList[Index].opcode := A_LEA;
  10229. reference_reset(NewRef, 1, []);
  10230. NewRef.index := InstrList[Index].oper[1]^.reg;
  10231. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10232. InstrList[Index].loadref(0, NewRef);
  10233. end;
  10234. A_IMUL:
  10235. begin
  10236. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10237. InstrList[Index].opcode := A_LEA;
  10238. reference_reset(NewRef, 1, []);
  10239. NewRef.index := InstrList[Index].oper[1]^.reg;
  10240. case InstrList[Index].oper[0]^.val of
  10241. 2, 4, 8:
  10242. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10243. else {3, 5 and 9}
  10244. begin
  10245. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10246. NewRef.base := InstrList[Index].oper[1]^.reg;
  10247. end;
  10248. end;
  10249. InstrList[Index].loadref(0, NewRef);
  10250. end;
  10251. else
  10252. InternalError(2021051710);
  10253. end;
  10254. end;
  10255. { Mark the FLAGS register as used across this whole block }
  10256. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10257. end;
  10258. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10259. JumpC := taicpu(hp2).condition;
  10260. Unconditional := False;
  10261. if conditions_equal(JumpC, C_E) then
  10262. SetC := inverse_cond(taicpu(p).condition)
  10263. else if conditions_equal(JumpC, C_NE) then
  10264. SetC := taicpu(p).condition
  10265. else
  10266. { We've got something weird here (and inefficent) }
  10267. begin
  10268. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10269. SetC := C_NONE;
  10270. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10271. if condition_in(C_AE, JumpC) then
  10272. Unconditional := True
  10273. else
  10274. { Not sure what to do with this jump - drop out }
  10275. Exit;
  10276. end;
  10277. RemoveInstruction(hp1);
  10278. if Unconditional then
  10279. MakeUnconditional(taicpu(hp2))
  10280. else
  10281. begin
  10282. if SetC = C_NONE then
  10283. InternalError(2018061402);
  10284. taicpu(hp2).SetCondition(SetC);
  10285. end;
  10286. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10287. TmpUsedRegs }
  10288. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10289. begin
  10290. RemoveCurrentp(p, hp2);
  10291. if taicpu(hp2).opcode = A_SETcc then
  10292. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10293. else
  10294. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10295. end
  10296. else
  10297. if taicpu(hp2).opcode = A_SETcc then
  10298. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10299. else
  10300. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10301. Result := True;
  10302. end
  10303. else if
  10304. { Make sure the instructions are adjacent }
  10305. (
  10306. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10307. GetNextInstruction(p, hp1)
  10308. ) and
  10309. MatchInstruction(hp1, A_MOV, [S_B]) and
  10310. { Writing to memory is allowed }
  10311. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10312. begin
  10313. {
  10314. Watch out for sequences such as:
  10315. set(c)b %regb
  10316. movb %regb,(ref)
  10317. movb $0,1(ref)
  10318. movb $0,2(ref)
  10319. movb $0,3(ref)
  10320. Much more efficient to turn it into:
  10321. movl $0,%regl
  10322. set(c)b %regb
  10323. movl %regl,(ref)
  10324. Or:
  10325. set(c)b %regb
  10326. movzbl %regb,%regl
  10327. movl %regl,(ref)
  10328. }
  10329. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10330. GetNextInstruction(hp1, hp2) and
  10331. MatchInstruction(hp2, A_MOV, [S_B]) and
  10332. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10333. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10334. begin
  10335. { Don't do anything else except set Result to True }
  10336. end
  10337. else
  10338. begin
  10339. if taicpu(p).oper[0]^.typ = top_reg then
  10340. begin
  10341. TransferUsedRegs(TmpUsedRegs);
  10342. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10343. end;
  10344. { If it's not a register, it's a memory address }
  10345. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10346. begin
  10347. { Even if the register is still in use, we can minimise the
  10348. pipeline stall by changing the MOV into another SETcc. }
  10349. taicpu(hp1).opcode := A_SETcc;
  10350. taicpu(hp1).condition := taicpu(p).condition;
  10351. if taicpu(hp1).oper[1]^.typ = top_ref then
  10352. begin
  10353. { Swapping the operand pointers like this is probably a
  10354. bit naughty, but it is far faster than using loadoper
  10355. to transfer the reference from oper[1] to oper[0] if
  10356. you take into account the extra procedure calls and
  10357. the memory allocation and deallocation required }
  10358. OperPtr := taicpu(hp1).oper[1];
  10359. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10360. taicpu(hp1).oper[0] := OperPtr;
  10361. end
  10362. else
  10363. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10364. taicpu(hp1).clearop(1);
  10365. taicpu(hp1).ops := 1;
  10366. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10367. end
  10368. else
  10369. begin
  10370. if taicpu(hp1).oper[1]^.typ = top_reg then
  10371. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10372. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10373. RemoveInstruction(hp1);
  10374. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10375. end
  10376. end;
  10377. Result := True;
  10378. end;
  10379. end;
  10380. end;
  10381. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10382. var
  10383. hp1: tai;
  10384. Count: Integer;
  10385. OrigLabel: TAsmLabel;
  10386. begin
  10387. result := False;
  10388. { Sometimes, the optimisations below can permit this }
  10389. RemoveDeadCodeAfterJump(p);
  10390. 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
  10391. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10392. begin
  10393. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10394. { Also a side-effect of optimisations }
  10395. if CollapseZeroDistJump(p, OrigLabel) then
  10396. begin
  10397. Result := True;
  10398. Exit;
  10399. end;
  10400. hp1 := GetLabelWithSym(OrigLabel);
  10401. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10402. begin
  10403. if taicpu(hp1).opcode = A_RET then
  10404. begin
  10405. {
  10406. change
  10407. jmp .L1
  10408. ...
  10409. .L1:
  10410. ret
  10411. into
  10412. ret
  10413. }
  10414. begin
  10415. ConvertJumpToRET(p, hp1);
  10416. result:=true;
  10417. end;
  10418. end
  10419. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10420. not (cs_opt_size in current_settings.optimizerswitches) and
  10421. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10422. begin
  10423. Result := True;
  10424. Exit;
  10425. end;
  10426. end;
  10427. end;
  10428. end;
  10429. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai) : boolean;
  10430. begin
  10431. Result := assigned(p) and
  10432. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10433. (taicpu(p).oper[1]^.typ = top_reg) and
  10434. (
  10435. (taicpu(p).oper[0]^.typ = top_reg) or
  10436. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10437. it is not expected that this can cause a seg. violation }
  10438. (
  10439. (taicpu(p).oper[0]^.typ = top_ref) and
  10440. { TODO: Can we detect which references become constants at this
  10441. stage so we don't have to do a blanket ban? }
  10442. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10443. (
  10444. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10445. (
  10446. { If the reference also appears in the condition, then we know it's safe, otherwise
  10447. any kind of access violation would have occurred already }
  10448. Assigned(cond_p) and
  10449. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10450. (cond_p.typ = ait_instruction) and
  10451. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10452. { Just consider 2-operand comparison instructions for now to be safe }
  10453. (taicpu(cond_p).ops = 2) and
  10454. (
  10455. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10456. (
  10457. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10458. { Don't risk identical registers but different offsets, as we may have constructs
  10459. such as buffer streams with things like length fields that indicate whether
  10460. any more data follows. And there are probably some contrived examples where
  10461. writing to offsets behind the one being read also lead to access violations }
  10462. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10463. (
  10464. { Check that we're not modifying a register that appears in the reference }
  10465. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10466. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10467. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10468. )
  10469. )
  10470. )
  10471. )
  10472. )
  10473. )
  10474. );
  10475. end;
  10476. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10477. begin
  10478. { Update integer registers, ignoring deallocations }
  10479. repeat
  10480. while assigned(p) and
  10481. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10482. (p.typ = ait_label) or
  10483. ((p.typ = ait_marker) and
  10484. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10485. p := tai(p.next);
  10486. while assigned(p) and
  10487. (p.typ=ait_RegAlloc) Do
  10488. begin
  10489. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10490. begin
  10491. case tai_regalloc(p).ratype of
  10492. ra_alloc :
  10493. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10494. else
  10495. ;
  10496. end;
  10497. end;
  10498. p := tai(p.next);
  10499. end;
  10500. until not(assigned(p)) or
  10501. (not(p.typ in SkipInstr) and
  10502. not((p.typ = ait_label) and
  10503. labelCanBeSkipped(tai_label(p))));
  10504. end;
  10505. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10506. var
  10507. hp1,hp2: tai;
  10508. carryadd_opcode : TAsmOp;
  10509. symbol: TAsmSymbol;
  10510. increg, tmpreg: TRegister;
  10511. {$ifndef i8086}
  10512. { Code and variables specific to CMOV optimisations }
  10513. hp3,hp4,hp5,
  10514. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10515. l, c, w, x : Longint;
  10516. condition, second_condition : TAsmCond;
  10517. FoundMatchingJump, RegMatch: Boolean;
  10518. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10519. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10520. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10521. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10522. new register to store the constant }
  10523. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10524. var
  10525. RegSize: TSubRegister;
  10526. CurrentVal: TCGInt;
  10527. NewReg: TRegister;
  10528. X: ShortInt;
  10529. begin
  10530. Result := False;
  10531. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10532. Exit;
  10533. if StoredCount >= MAX_CMOV_REGISTERS then
  10534. { Arrays are full }
  10535. Exit;
  10536. { Remember that CMOV can't encode 8-bit registers }
  10537. case taicpu(p).opsize of
  10538. S_W:
  10539. RegSize := R_SUBW;
  10540. S_L:
  10541. RegSize := R_SUBD;
  10542. S_Q:
  10543. RegSize := R_SUBQ;
  10544. else
  10545. InternalError(2021100401);
  10546. end;
  10547. { See if the value has already been reserved for another CMOV instruction }
  10548. CurrentVal := taicpu(p).oper[0]^.val;
  10549. for X := 0 to StoredCount - 1 do
  10550. if ConstVals[X] = CurrentVal then
  10551. begin
  10552. ConstRegs[StoredCount] := ConstRegs[X];
  10553. ConstVals[StoredCount] := CurrentVal;
  10554. Result := True;
  10555. Inc(StoredCount);
  10556. { Don't increase CMOVCount this time, since we're re-using a register }
  10557. Exit;
  10558. end;
  10559. NewReg := GetIntRegisterBetween(RegSize, TmpUsedRegs, search_start_p, stop_search_p, True);
  10560. if NewReg = NR_NO then
  10561. { No free registers }
  10562. Exit;
  10563. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10564. up vying for the same register }
  10565. IncludeRegInUsedRegs(NewReg, TmpUsedRegs);
  10566. ConstRegs[StoredCount] := NewReg;
  10567. ConstVals[StoredCount] := CurrentVal;
  10568. Inc(StoredCount);
  10569. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10570. MOV required adds complexity and will cause diminishing returns
  10571. sooner than normal. This is more of an approximate weighting than
  10572. anything else. }
  10573. Inc(CMOVCount);
  10574. Result := True;
  10575. end;
  10576. {$endif i8086}
  10577. begin
  10578. result:=false;
  10579. if GetNextInstruction(p,hp1) then
  10580. begin
  10581. if (hp1.typ=ait_label) then
  10582. begin
  10583. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10584. Exit;
  10585. end
  10586. else if (hp1.typ<>ait_instruction) then
  10587. Exit;
  10588. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10589. if (
  10590. (
  10591. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10592. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10593. (Taicpu(hp1).oper[0]^.val=1)
  10594. ) or
  10595. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10596. ) and
  10597. GetNextInstruction(hp1,hp2) and
  10598. SkipAligns(hp2, hp2) and
  10599. (hp2.typ = ait_label) and
  10600. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10601. { jb @@1 cmc
  10602. inc/dec operand --> adc/sbb operand,0
  10603. @@1:
  10604. ... and ...
  10605. jnb @@1
  10606. inc/dec operand --> adc/sbb operand,0
  10607. @@1: }
  10608. begin
  10609. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10610. begin
  10611. case taicpu(hp1).opcode of
  10612. A_INC,
  10613. A_ADD:
  10614. carryadd_opcode:=A_ADC;
  10615. A_DEC,
  10616. A_SUB:
  10617. carryadd_opcode:=A_SBB;
  10618. else
  10619. InternalError(2021011001);
  10620. end;
  10621. Taicpu(p).clearop(0);
  10622. Taicpu(p).ops:=0;
  10623. Taicpu(p).is_jmp:=false;
  10624. Taicpu(p).opcode:=A_CMC;
  10625. Taicpu(p).condition:=C_NONE;
  10626. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10627. Taicpu(hp1).ops:=2;
  10628. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10629. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10630. else
  10631. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10632. Taicpu(hp1).loadconst(0,0);
  10633. Taicpu(hp1).opcode:=carryadd_opcode;
  10634. result:=true;
  10635. exit;
  10636. end
  10637. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10638. begin
  10639. case taicpu(hp1).opcode of
  10640. A_INC,
  10641. A_ADD:
  10642. carryadd_opcode:=A_ADC;
  10643. A_DEC,
  10644. A_SUB:
  10645. carryadd_opcode:=A_SBB;
  10646. else
  10647. InternalError(2021011002);
  10648. end;
  10649. Taicpu(hp1).ops:=2;
  10650. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10651. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10652. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10653. else
  10654. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10655. Taicpu(hp1).loadconst(0,0);
  10656. Taicpu(hp1).opcode:=carryadd_opcode;
  10657. RemoveCurrentP(p, hp1);
  10658. result:=true;
  10659. exit;
  10660. end
  10661. {
  10662. jcc @@1 setcc tmpreg
  10663. inc/dec/add/sub operand -> (movzx tmpreg)
  10664. @@1: add/sub tmpreg,operand
  10665. While this increases code size slightly, it makes the code much faster if the
  10666. jump is unpredictable
  10667. }
  10668. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10669. begin
  10670. { search for an available register which is volatile }
  10671. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10672. if increg <> NR_NO then
  10673. begin
  10674. { We don't need to check if tmpreg is in hp1 or not, because
  10675. it will be marked as in use at p (if not, this is
  10676. indictive of a compiler bug). }
  10677. TAsmLabel(symbol).decrefs;
  10678. Taicpu(p).clearop(0);
  10679. Taicpu(p).ops:=1;
  10680. Taicpu(p).is_jmp:=false;
  10681. Taicpu(p).opcode:=A_SETcc;
  10682. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10683. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10684. Taicpu(p).loadreg(0,increg);
  10685. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10686. begin
  10687. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10688. R_SUBW:
  10689. begin
  10690. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10691. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10692. end;
  10693. R_SUBD:
  10694. begin
  10695. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10696. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10697. end;
  10698. {$ifdef x86_64}
  10699. R_SUBQ:
  10700. begin
  10701. { MOVZX doesn't have a 64-bit variant, because
  10702. the 32-bit version implicitly zeroes the
  10703. upper 32-bits of the destination register }
  10704. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10705. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10706. setsubreg(tmpreg, R_SUBQ);
  10707. end;
  10708. {$endif x86_64}
  10709. else
  10710. Internalerror(2020030601);
  10711. end;
  10712. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10713. asml.InsertAfter(hp2,p);
  10714. end
  10715. else
  10716. tmpreg := increg;
  10717. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10718. begin
  10719. Taicpu(hp1).ops:=2;
  10720. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10721. end;
  10722. Taicpu(hp1).loadreg(0,tmpreg);
  10723. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10724. Result := True;
  10725. { p is no longer a Jcc instruction, so exit }
  10726. Exit;
  10727. end;
  10728. end;
  10729. end;
  10730. { Detect the following:
  10731. jmp<cond> @Lbl1
  10732. jmp @Lbl2
  10733. ...
  10734. @Lbl1:
  10735. ret
  10736. Change to:
  10737. jmp<inv_cond> @Lbl2
  10738. ret
  10739. }
  10740. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10741. begin
  10742. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10743. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10744. MatchInstruction(hp2,A_RET,[S_NO]) then
  10745. begin
  10746. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10747. { Change label address to that of the unconditional jump }
  10748. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10749. TAsmLabel(symbol).DecRefs;
  10750. taicpu(hp1).opcode := A_RET;
  10751. taicpu(hp1).is_jmp := false;
  10752. taicpu(hp1).ops := taicpu(hp2).ops;
  10753. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10754. case taicpu(hp2).ops of
  10755. 0:
  10756. taicpu(hp1).clearop(0);
  10757. 1:
  10758. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10759. else
  10760. internalerror(2016041302);
  10761. end;
  10762. end;
  10763. {$ifndef i8086}
  10764. end
  10765. {
  10766. convert
  10767. j<c> .L1
  10768. mov 1,reg
  10769. jmp .L2
  10770. .L1
  10771. mov 0,reg
  10772. .L2
  10773. into
  10774. mov 0,reg
  10775. set<not(c)> reg
  10776. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10777. would destroy the flag contents
  10778. }
  10779. else if MatchInstruction(hp1,A_MOV,[]) and
  10780. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10781. {$ifdef i386}
  10782. (
  10783. { Under i386, ESI, EDI, EBP and ESP
  10784. don't have an 8-bit representation }
  10785. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10786. ) and
  10787. {$endif i386}
  10788. (taicpu(hp1).oper[0]^.val=1) and
  10789. GetNextInstruction(hp1,hp2) and
  10790. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10791. GetNextInstruction(hp2,hp3) and
  10792. { skip align }
  10793. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10794. (hp3.typ=ait_label) and
  10795. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10796. (tai_label(hp3).labsym.getrefs=1) and
  10797. GetNextInstruction(hp3,hp4) and
  10798. MatchInstruction(hp4,A_MOV,[]) and
  10799. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10800. (taicpu(hp4).oper[0]^.val=0) and
  10801. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10802. GetNextInstruction(hp4,hp5) and
  10803. (hp5.typ=ait_label) and
  10804. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10805. (tai_label(hp5).labsym.getrefs=1) then
  10806. begin
  10807. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10808. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10809. { remove last label }
  10810. RemoveInstruction(hp5);
  10811. { remove second label }
  10812. RemoveInstruction(hp3);
  10813. { if align is present remove it }
  10814. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10815. RemoveInstruction(hp3);
  10816. { remove jmp }
  10817. RemoveInstruction(hp2);
  10818. if taicpu(hp1).opsize=S_B then
  10819. RemoveInstruction(hp1)
  10820. else
  10821. taicpu(hp1).loadconst(0,0);
  10822. taicpu(hp4).opcode:=A_SETcc;
  10823. taicpu(hp4).opsize:=S_B;
  10824. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10825. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10826. taicpu(hp4).opercnt:=1;
  10827. taicpu(hp4).ops:=1;
  10828. taicpu(hp4).freeop(1);
  10829. RemoveCurrentP(p);
  10830. Result:=true;
  10831. exit;
  10832. end
  10833. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.optimizecputype]) and
  10834. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10835. begin
  10836. { check for
  10837. jCC xxx
  10838. <several movs>
  10839. xxx:
  10840. Also spot:
  10841. Jcc xxx
  10842. <several movs>
  10843. jmp xxx
  10844. Change to:
  10845. <several cmovs with inverted condition>
  10846. jmp xxx (only for the 2nd case)
  10847. }
  10848. hp2 := p;
  10849. hp_lblxxx := hp1;
  10850. hp_flagalloc := nil;
  10851. hp_stop := nil;
  10852. FoundMatchingJump := False;
  10853. { Remember the first instruction in the first block of MOVs }
  10854. hpmov1 := hp1;
  10855. TransferUsedRegs(TmpUsedRegs);
  10856. while assigned(hp_lblxxx) and
  10857. { stop on labels }
  10858. (hp_lblxxx.typ <> ait_label) do
  10859. begin
  10860. { Keep track of all integer registers that are used }
  10861. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10862. if hp_lblxxx.typ = ait_instruction then
  10863. begin
  10864. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  10865. IsJumpToLabel(taicpu(hp_lblxxx)) then
  10866. begin
  10867. hp_stop := hp_lblxxx;
  10868. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  10869. begin
  10870. { We found Jcc xxx; <several movs>; Jmp xxx }
  10871. FoundMatchingJump := True;
  10872. Break;
  10873. end;
  10874. { If it's not the jump we're looking for, it's
  10875. possibly the "if..else" variant }
  10876. end
  10877. { Check to see if we have a valid MOV instruction instead }
  10878. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  10879. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10880. Break
  10881. else
  10882. { This will be a valid MOV }
  10883. hp_stop := hp_lblxxx;
  10884. end;
  10885. hp2 := hp_lblxxx;
  10886. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  10887. end;
  10888. { Just make sure the last MOV is included if there's no jump }
  10889. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  10890. hp_stop := hp_lblxxx;
  10891. { Note, the logic behind using hp_stop over hp_lblxxx in the
  10892. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  10893. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  10894. jmp yyy; xxx:; movs; yyy:" variation }
  10895. if assigned(hp_lblxxx) and
  10896. (
  10897. { If we found JMP xxx, we don't actually need a label
  10898. (hp_lblxxx is the JMP instruction instead) }
  10899. FoundMatchingJump or
  10900. { Make sure we actually have the right label }
  10901. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  10902. ) then
  10903. begin
  10904. { Use TmpUsedRegs to track registers that we reserve }
  10905. { When allocating temporary registers, try to look one
  10906. instruction back, as defining them before a CMP or TEST
  10907. instruction will be faster, and also avoid picking a
  10908. register that was only just deallocated }
  10909. if GetLastInstruction(p, hp_prev) and
  10910. 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
  10911. begin
  10912. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  10913. for l := 0 to 1 do
  10914. with taicpu(hp_prev).oper[l]^ do
  10915. case typ of
  10916. top_reg:
  10917. if getregtype(reg) = R_INTREGISTER then
  10918. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10919. top_ref:
  10920. begin
  10921. if
  10922. {$ifdef x86_64}
  10923. (ref^.base <> NR_RIP) and
  10924. {$endif x86_64}
  10925. (ref^.base <> NR_NO) then
  10926. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  10927. if (ref^.index <> NR_NO) then
  10928. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  10929. end
  10930. else
  10931. ;
  10932. end;
  10933. { When inserting instructions before hp_prev, try to insert
  10934. them before the allocation of the FLAGS register }
  10935. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  10936. { If not found, set it equal to hp_prev so it's something sensible }
  10937. hp_flagalloc := hp_prev;
  10938. hp_prev2 := nil;
  10939. { When dealing with a comparison against zero, take
  10940. note of the instruction before it to see if we can
  10941. move instructions further back in order to benefit
  10942. PostPeepholeOptTestOr.
  10943. }
  10944. if (
  10945. (
  10946. (taicpu(hp_prev).opcode = A_CMP) and
  10947. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  10948. ) or
  10949. (
  10950. (taicpu(hp_prev).opcode = A_TEST) and
  10951. (
  10952. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  10953. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  10954. )
  10955. )
  10956. ) and
  10957. GetLastInstruction(hp_prev, hp_prev2) then
  10958. begin
  10959. if (hp_prev2.typ = ait_instruction) and
  10960. { These instructions set the zero flag if the result is zero }
  10961. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  10962. begin
  10963. { Also mark all the registers in this previous instruction
  10964. as 'in use', even if they've just been deallocated }
  10965. for l := 0 to 1 do
  10966. with taicpu(hp_prev2).oper[l]^ do
  10967. case typ of
  10968. top_reg:
  10969. if getregtype(reg) = R_INTREGISTER then
  10970. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10971. top_ref:
  10972. begin
  10973. if
  10974. {$ifdef x86_64}
  10975. (ref^.base <> NR_RIP) and
  10976. {$endif x86_64}
  10977. (ref^.base <> NR_NO) then
  10978. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  10979. if (ref^.index <> NR_NO) then
  10980. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  10981. end
  10982. else
  10983. ;
  10984. end;
  10985. end
  10986. else
  10987. { Unsuitable instruction }
  10988. hp_prev2 := nil;
  10989. end;
  10990. end
  10991. else
  10992. begin
  10993. hp_prev := p;
  10994. { When inserting instructions before hp_prev, try to insert
  10995. them before the allocation of the FLAGS register }
  10996. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  10997. { If not found, set it equal to p so it's something sensible }
  10998. hp_flagalloc := p;
  10999. hp_prev2 := nil;
  11000. end;
  11001. l := 0;
  11002. c := 0;
  11003. { Initialise RegWrites, ConstRegs and ConstVals }
  11004. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11005. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11006. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11007. while assigned(hp1) and
  11008. { Stop on the label we found }
  11009. (hp1 <> hp_lblxxx) do
  11010. begin
  11011. case hp1.typ of
  11012. ait_instruction:
  11013. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11014. begin
  11015. if CanBeCMOV(hp1, hp_prev) then
  11016. Inc(l)
  11017. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11018. { CMOV with constants grows the code size }
  11019. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  11020. begin
  11021. { Register was reserved by TryCMOVConst and
  11022. stored on ConstRegs[c] }
  11023. end
  11024. else
  11025. Break;
  11026. end
  11027. else
  11028. Break;
  11029. else
  11030. ;
  11031. end;
  11032. GetNextInstruction(hp1,hp1);
  11033. end;
  11034. if (hp1 = hp_lblxxx) then
  11035. begin
  11036. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  11037. begin
  11038. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11039. TmpUsedRegs[R_INTREGISTER].Clear;
  11040. x := 0;
  11041. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  11042. condition := inverse_cond(taicpu(p).condition);
  11043. UpdateUsedRegs(tai(p.next));
  11044. hp1 := hpmov1;
  11045. repeat
  11046. if not Assigned(hp1) then
  11047. InternalError(2018062900);
  11048. if (hp1.typ = ait_instruction) then
  11049. begin
  11050. { Extra safeguard }
  11051. if (taicpu(hp1).opcode <> A_MOV) then
  11052. InternalError(2018062901);
  11053. if taicpu(hp1).oper[0]^.typ = top_const then
  11054. begin
  11055. if x >= MAX_CMOV_REGISTERS then
  11056. InternalError(2021100410);
  11057. { If it's in TmpUsedRegs, then this register
  11058. is being used more than once and hence has
  11059. already had its value defined (it gets
  11060. added to UsedRegs through AllocRegBetween
  11061. below) }
  11062. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11063. begin
  11064. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11065. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  11066. asml.InsertBefore(hp_new, hp_flagalloc);
  11067. if Assigned(hp_prev2) then
  11068. TrySwapMovOp(hp_prev2, hp_new);
  11069. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11070. end
  11071. else
  11072. { We just need an instruction between hp_prev and hp1
  11073. where we know the register is marked as in use }
  11074. hp_new := hpmov1;
  11075. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11076. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11077. Inc(x);
  11078. end;
  11079. taicpu(hp1).opcode := A_CMOVcc;
  11080. taicpu(hp1).condition := condition;
  11081. end;
  11082. UpdateUsedRegs(tai(hp1.next));
  11083. GetNextInstruction(hp1, hp1);
  11084. until (hp1 = hp_lblxxx);
  11085. hp2 := hp_lblxxx;
  11086. repeat
  11087. if not Assigned(hp2) then
  11088. InternalError(2018062910);
  11089. case hp2.typ of
  11090. ait_label:
  11091. { What we expected - break out of the loop (it won't be a dead label at the top of
  11092. a cluster because that was optimised at an earlier stage) }
  11093. Break;
  11094. ait_align:
  11095. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11096. begin
  11097. hp2 := tai(hp2.Next);
  11098. Continue;
  11099. end;
  11100. ait_instruction:
  11101. begin
  11102. if taicpu(hp2).opcode<>A_JMP then
  11103. InternalError(2018062912);
  11104. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11105. Break;
  11106. end
  11107. else
  11108. begin
  11109. { Might be a comment or temporary allocation entry }
  11110. if not (hp2.typ in SkipInstr) then
  11111. InternalError(2018062911);
  11112. hp2 := tai(hp2.Next);
  11113. Continue;
  11114. end;
  11115. end;
  11116. until False;
  11117. { Now we can safely decrement the reference count }
  11118. tasmlabel(symbol).decrefs;
  11119. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11120. { Remove the original jump }
  11121. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11122. if hp2.typ=ait_instruction then
  11123. begin
  11124. p := hp2;
  11125. Result := True;
  11126. end
  11127. else
  11128. begin
  11129. UpdateUsedRegs(tai(hp2.next));
  11130. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11131. { Remove the label if this is its final reference }
  11132. if (tasmlabel(symbol).getrefs=0) then
  11133. begin
  11134. { Make sure the aligns get stripped too }
  11135. hp1 := tai(hp_lblxxx.Previous);
  11136. while Assigned(hp1) and (hp1.typ = ait_align) do
  11137. begin
  11138. hp_lblxxx := hp1;
  11139. hp1 := tai(hp_lblxxx.Previous);
  11140. end;
  11141. StripLabelFast(hp_lblxxx);
  11142. end;
  11143. end;
  11144. Exit;
  11145. end;
  11146. end
  11147. else if assigned(hp_lblxxx) and
  11148. { check further for
  11149. jCC xxx
  11150. <several movs 1>
  11151. jmp yyy
  11152. xxx:
  11153. <several movs 2>
  11154. yyy:
  11155. }
  11156. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11157. { hp1 should be pointing to jmp yyy }
  11158. MatchInstruction(hp1, A_JMP, []) and
  11159. { real label and jump, no further references to the
  11160. label are allowed }
  11161. (TAsmLabel(symbol).getrefs=1) and
  11162. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11163. begin
  11164. hp_jump := hp1;
  11165. { Don't set c to zero }
  11166. l := 0;
  11167. w := 0;
  11168. GetNextInstruction(hp_lblxxx, hpmov2);
  11169. hp2 := hp_lblxxx;
  11170. hp_lblyyy := hpmov2;
  11171. while assigned(hp_lblyyy) and
  11172. { stop on labels }
  11173. (hp_lblyyy.typ <> ait_label) do
  11174. begin
  11175. { Keep track of all integer registers that are used }
  11176. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11177. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11178. Break;
  11179. hp2 := hp_lblyyy;
  11180. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11181. end;
  11182. { Analyse the second batch of MOVs to see if the setup is valid }
  11183. hp1 := hpmov2;
  11184. while assigned(hp1) and
  11185. (hp1 <> hp_lblyyy) do
  11186. begin
  11187. case hp1.typ of
  11188. ait_instruction:
  11189. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11190. begin
  11191. if CanBeCMOV(hp1, hp_prev) then
  11192. Inc(l)
  11193. else if not (cs_opt_size in current_settings.optimizerswitches)
  11194. { CMOV with constants grows the code size }
  11195. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11196. begin
  11197. { Register was reserved by TryCMOVConst and
  11198. stored on ConstRegs[c] }
  11199. end
  11200. else
  11201. Break;
  11202. end
  11203. else
  11204. Break;
  11205. else
  11206. ;
  11207. end;
  11208. GetNextInstruction(hp1,hp1);
  11209. end;
  11210. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11211. TmpUsedRegs[R_INTREGISTER].Clear;
  11212. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11213. (hp1 = hp_lblyyy) and
  11214. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11215. begin
  11216. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11217. second_condition := taicpu(p).condition;
  11218. condition := inverse_cond(taicpu(p).condition);
  11219. UpdateUsedRegs(tai(p.next));
  11220. { Scan through the first set of MOVs to update UsedRegs,
  11221. but don't process them yet }
  11222. hp1 := hpmov1;
  11223. repeat
  11224. if not Assigned(hp1) then
  11225. InternalError(2018062901);
  11226. UpdateUsedRegs(tai(hp1.next));
  11227. GetNextInstruction(hp1, hp1);
  11228. until (hp1 = hp_lblxxx);
  11229. UpdateUsedRegs(tai(hp_lblxxx.next));
  11230. { Process the second set of MOVs first,
  11231. because if a destination register is
  11232. shared between the first and second MOV
  11233. sets, it is more efficient to turn the
  11234. first one into a MOV instruction and place
  11235. it before the CMP if possible, but we
  11236. won't know which registers are shared
  11237. until we've processed at least one list,
  11238. so we might as well make it the second
  11239. one since that won't be modified again. }
  11240. hp1 := hpmov2;
  11241. repeat
  11242. if not Assigned(hp1) then
  11243. InternalError(2018062902);
  11244. if (hp1.typ = ait_instruction) then
  11245. begin
  11246. { Extra safeguard }
  11247. if (taicpu(hp1).opcode <> A_MOV) then
  11248. InternalError(2018062903);
  11249. if taicpu(hp1).oper[0]^.typ = top_const then
  11250. begin
  11251. RegMatch := False;
  11252. for x := 0 to c - 1 do
  11253. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11254. begin
  11255. RegMatch := True;
  11256. { If it's in TmpUsedRegs, then this register
  11257. is being used more than once and hence has
  11258. already had its value defined (it gets
  11259. added to UsedRegs through AllocRegBetween
  11260. below) }
  11261. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11262. begin
  11263. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11264. asml.InsertBefore(hp_new, hp_flagalloc);
  11265. if Assigned(hp_prev2) then
  11266. TrySwapMovOp(hp_prev2, hp_new);
  11267. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11268. end
  11269. else
  11270. { We just need an instruction between hp_prev and hp1
  11271. where we know the register is marked as in use }
  11272. hp_new := hpmov2;
  11273. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11274. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11275. Break;
  11276. end;
  11277. if not RegMatch then
  11278. InternalError(2021100411);
  11279. end;
  11280. taicpu(hp1).opcode := A_CMOVcc;
  11281. taicpu(hp1).condition := second_condition;
  11282. { Store these writes to search for
  11283. duplicates later on }
  11284. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11285. Inc(w);
  11286. end;
  11287. UpdateUsedRegs(tai(hp1.next));
  11288. GetNextInstruction(hp1, hp1);
  11289. until (hp1 = hp_lblyyy);
  11290. { Now do the first set of MOVs }
  11291. hp1 := hpmov1;
  11292. repeat
  11293. if not Assigned(hp1) then
  11294. InternalError(2018062904);
  11295. if (hp1.typ = ait_instruction) then
  11296. begin
  11297. RegMatch := False;
  11298. { Extra safeguard }
  11299. if (taicpu(hp1).opcode <> A_MOV) then
  11300. InternalError(2018062905);
  11301. { Search through the RegWrites list to see
  11302. if there are any opposing CMOV pairs that
  11303. write to the same register }
  11304. for x := 0 to w - 1 do
  11305. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11306. begin
  11307. { We have a match. Keep this as a MOV }
  11308. { Move ahead in preparation }
  11309. GetNextInstruction(hp1, hp1);
  11310. RegMatch := True;
  11311. Break;
  11312. end;
  11313. if RegMatch then
  11314. Continue;
  11315. if taicpu(hp1).oper[0]^.typ = top_const then
  11316. begin
  11317. RegMatch := False;
  11318. for x := 0 to c - 1 do
  11319. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11320. begin
  11321. RegMatch := True;
  11322. { If it's in TmpUsedRegs, then this register
  11323. is being used more than once and hence has
  11324. already had its value defined (it gets
  11325. added to UsedRegs through AllocRegBetween
  11326. below) }
  11327. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11328. begin
  11329. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11330. asml.InsertBefore(hp_new, hp_flagalloc);
  11331. if Assigned(hp_prev2) then
  11332. TrySwapMovOp(hp_prev2, hp_new);
  11333. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11334. end
  11335. else
  11336. { We just need an instruction between hp_prev and hp1
  11337. where we know the register is marked as in use }
  11338. hp_new := hpmov1;
  11339. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11340. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11341. Break;
  11342. end;
  11343. if not RegMatch then
  11344. InternalError(2021100412);
  11345. end;
  11346. taicpu(hp1).opcode := A_CMOVcc;
  11347. taicpu(hp1).condition := condition;
  11348. end;
  11349. GetNextInstruction(hp1, hp1);
  11350. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11351. UpdateUsedRegs(tai(hp_jump.next));
  11352. UpdateUsedRegs(tai(hp_lblyyy.next));
  11353. { Get first instruction after label }
  11354. hp1 := p;
  11355. GetNextInstruction(hp_lblyyy, p);
  11356. { Don't dereference yet, as doing so will cause
  11357. GetNextInstruction to skip the label and
  11358. optional align marker. [Kit] }
  11359. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11360. { remove Jcc }
  11361. RemoveInstruction(hp1);
  11362. { Now we can safely decrement it }
  11363. tasmlabel(symbol).decrefs;
  11364. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11365. { Make sure the aligns get stripped too }
  11366. hp1 := tai(hp_lblxxx.Previous);
  11367. while Assigned(hp1) and (hp1.typ = ait_align) do
  11368. begin
  11369. hp_lblxxx := hp1;
  11370. hp1 := tai(hp_lblxxx.Previous);
  11371. end;
  11372. StripLabelFast(hp_lblxxx);
  11373. { remove jmp }
  11374. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11375. RemoveInstruction(hp_jump);
  11376. { As before, now we can safely decrement it }
  11377. TAsmLabel(symbol).decrefs;
  11378. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11379. if TAsmLabel(symbol).getrefs = 0 then
  11380. begin
  11381. { Make sure the aligns get stripped too }
  11382. hp1 := tai(hp_lblyyy.Previous);
  11383. while Assigned(hp1) and (hp1.typ = ait_align) do
  11384. begin
  11385. hp_lblyyy := hp1;
  11386. hp1 := tai(hp_lblyyy.Previous);
  11387. end;
  11388. StripLabelFast(hp_lblyyy);
  11389. end;
  11390. if Assigned(p) then
  11391. result := True;
  11392. exit;
  11393. end;
  11394. end;
  11395. end;
  11396. {$endif i8086}
  11397. end;
  11398. end;
  11399. end;
  11400. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11401. var
  11402. hp1,hp2,hp3: tai;
  11403. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11404. NewSize: TOpSize;
  11405. NewRegSize: TSubRegister;
  11406. Limit: TCgInt;
  11407. SwapOper: POper;
  11408. begin
  11409. result:=false;
  11410. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11411. GetNextInstruction(p,hp1) and
  11412. (hp1.typ = ait_instruction);
  11413. if reg_and_hp1_is_instr and
  11414. (
  11415. (taicpu(hp1).opcode <> A_LEA) or
  11416. { If the LEA instruction can be converted into an arithmetic instruction,
  11417. it may be possible to then fold it. }
  11418. (
  11419. { If the flags register is in use, don't change the instruction
  11420. to an ADD otherwise this will scramble the flags. [Kit] }
  11421. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11422. ConvertLEA(taicpu(hp1))
  11423. )
  11424. ) and
  11425. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11426. GetNextInstruction(hp1,hp2) and
  11427. MatchInstruction(hp2,A_MOV,[]) and
  11428. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11429. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11430. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11431. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11432. {$ifdef i386}
  11433. { not all registers have byte size sub registers on i386 }
  11434. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11435. {$endif i386}
  11436. (((taicpu(hp1).ops=2) and
  11437. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11438. ((taicpu(hp1).ops=1) and
  11439. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11440. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11441. begin
  11442. { change movsX/movzX reg/ref, reg2
  11443. add/sub/or/... reg3/$const, reg2
  11444. mov reg2 reg/ref
  11445. to add/sub/or/... reg3/$const, reg/ref }
  11446. { by example:
  11447. movswl %si,%eax movswl %si,%eax p
  11448. decl %eax addl %edx,%eax hp1
  11449. movw %ax,%si movw %ax,%si hp2
  11450. ->
  11451. movswl %si,%eax movswl %si,%eax p
  11452. decw %eax addw %edx,%eax hp1
  11453. movw %ax,%si movw %ax,%si hp2
  11454. }
  11455. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11456. {
  11457. ->
  11458. movswl %si,%eax movswl %si,%eax p
  11459. decw %si addw %dx,%si hp1
  11460. movw %ax,%si movw %ax,%si hp2
  11461. }
  11462. case taicpu(hp1).ops of
  11463. 1:
  11464. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11465. 2:
  11466. begin
  11467. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11468. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11469. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11470. end;
  11471. else
  11472. internalerror(2008042702);
  11473. end;
  11474. {
  11475. ->
  11476. decw %si addw %dx,%si p
  11477. }
  11478. DebugMsg(SPeepholeOptimization + 'var3',p);
  11479. RemoveCurrentP(p, hp1);
  11480. RemoveInstruction(hp2);
  11481. Result := True;
  11482. Exit;
  11483. end;
  11484. if reg_and_hp1_is_instr and
  11485. (taicpu(hp1).opcode = A_MOV) and
  11486. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11487. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11488. {$ifdef x86_64}
  11489. { check for implicit extension to 64 bit }
  11490. or
  11491. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11492. (taicpu(hp1).opsize=S_Q) and
  11493. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11494. )
  11495. {$endif x86_64}
  11496. )
  11497. then
  11498. begin
  11499. { change
  11500. movx %reg1,%reg2
  11501. mov %reg2,%reg3
  11502. dealloc %reg2
  11503. into
  11504. movx %reg,%reg3
  11505. }
  11506. TransferUsedRegs(TmpUsedRegs);
  11507. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11508. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11509. begin
  11510. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11511. {$ifdef x86_64}
  11512. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11513. (taicpu(hp1).opsize=S_Q) then
  11514. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11515. else
  11516. {$endif x86_64}
  11517. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11518. RemoveInstruction(hp1);
  11519. Result := True;
  11520. Exit;
  11521. end;
  11522. end;
  11523. if reg_and_hp1_is_instr and
  11524. ((taicpu(hp1).opcode=A_MOV) or
  11525. (taicpu(hp1).opcode=A_ADD) or
  11526. (taicpu(hp1).opcode=A_SUB) or
  11527. (taicpu(hp1).opcode=A_CMP) or
  11528. (taicpu(hp1).opcode=A_OR) or
  11529. (taicpu(hp1).opcode=A_XOR) or
  11530. (taicpu(hp1).opcode=A_AND)
  11531. ) and
  11532. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11533. begin
  11534. AndTest := (taicpu(hp1).opcode=A_AND) and
  11535. GetNextInstruction(hp1, hp2) and
  11536. (hp2.typ = ait_instruction) and
  11537. (
  11538. (
  11539. (taicpu(hp2).opcode=A_TEST) and
  11540. (
  11541. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11542. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11543. (
  11544. { If the AND and TEST instructions share a constant, this is also valid }
  11545. (taicpu(hp1).oper[0]^.typ = top_const) and
  11546. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11547. )
  11548. ) and
  11549. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11550. ) or
  11551. (
  11552. (taicpu(hp2).opcode=A_CMP) and
  11553. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11554. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11555. )
  11556. );
  11557. { change
  11558. movx (oper),%reg2
  11559. and $x,%reg2
  11560. test %reg2,%reg2
  11561. dealloc %reg2
  11562. into
  11563. op %reg1,%reg3
  11564. if the second op accesses only the bits stored in reg1
  11565. }
  11566. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11567. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11568. (taicpu(hp1).oper[0]^.typ = top_const) and
  11569. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11570. AndTest then
  11571. begin
  11572. { Check if the AND constant is in range }
  11573. case taicpu(p).opsize of
  11574. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11575. begin
  11576. NewSize := S_B;
  11577. Limit := $FF;
  11578. end;
  11579. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11580. begin
  11581. NewSize := S_W;
  11582. Limit := $FFFF;
  11583. end;
  11584. {$ifdef x86_64}
  11585. S_LQ:
  11586. begin
  11587. NewSize := S_L;
  11588. Limit := $FFFFFFFF;
  11589. end;
  11590. {$endif x86_64}
  11591. else
  11592. InternalError(2021120303);
  11593. end;
  11594. if (
  11595. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11596. { Check for negative operands }
  11597. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11598. ) and
  11599. GetNextInstruction(hp2,hp3) and
  11600. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11601. (taicpu(hp3).condition in [C_E,C_NE]) then
  11602. begin
  11603. TransferUsedRegs(TmpUsedRegs);
  11604. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11605. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11606. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11607. begin
  11608. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11609. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11610. taicpu(hp1).opcode := A_TEST;
  11611. taicpu(hp1).opsize := NewSize;
  11612. RemoveInstruction(hp2);
  11613. RemoveCurrentP(p, hp1);
  11614. Result:=true;
  11615. exit;
  11616. end;
  11617. end;
  11618. end;
  11619. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11620. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11621. (taicpu(hp1).opsize=S_B)) or
  11622. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11623. (taicpu(hp1).opsize=S_W))
  11624. {$ifdef x86_64}
  11625. or ((taicpu(p).opsize=S_LQ) and
  11626. (taicpu(hp1).opsize=S_L))
  11627. {$endif x86_64}
  11628. ) and
  11629. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11630. begin
  11631. { change
  11632. movx %reg1,%reg2
  11633. op %reg2,%reg3
  11634. dealloc %reg2
  11635. into
  11636. op %reg1,%reg3
  11637. if the second op accesses only the bits stored in reg1
  11638. }
  11639. TransferUsedRegs(TmpUsedRegs);
  11640. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11641. if AndTest then
  11642. begin
  11643. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11644. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11645. end
  11646. else
  11647. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11648. if not RegUsed then
  11649. begin
  11650. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11651. if taicpu(p).oper[0]^.typ=top_reg then
  11652. begin
  11653. case taicpu(hp1).opsize of
  11654. S_B:
  11655. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11656. S_W:
  11657. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11658. S_L:
  11659. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11660. else
  11661. Internalerror(2020102301);
  11662. end;
  11663. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11664. end
  11665. else
  11666. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11667. RemoveCurrentP(p);
  11668. if AndTest then
  11669. RemoveInstruction(hp2);
  11670. result:=true;
  11671. exit;
  11672. end;
  11673. end
  11674. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11675. (
  11676. { Bitwise operations only }
  11677. (taicpu(hp1).opcode=A_AND) or
  11678. (taicpu(hp1).opcode=A_TEST) or
  11679. (
  11680. (taicpu(hp1).oper[0]^.typ = top_const) and
  11681. (
  11682. (taicpu(hp1).opcode=A_OR) or
  11683. (taicpu(hp1).opcode=A_XOR)
  11684. )
  11685. )
  11686. ) and
  11687. (
  11688. (taicpu(hp1).oper[0]^.typ = top_const) or
  11689. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11690. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11691. ) then
  11692. begin
  11693. { change
  11694. movx %reg2,%reg2
  11695. op const,%reg2
  11696. into
  11697. op const,%reg2 (smaller version)
  11698. movx %reg2,%reg2
  11699. also change
  11700. movx %reg1,%reg2
  11701. and/test (oper),%reg2
  11702. dealloc %reg2
  11703. into
  11704. and/test (oper),%reg1
  11705. }
  11706. case taicpu(p).opsize of
  11707. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11708. begin
  11709. NewSize := S_B;
  11710. NewRegSize := R_SUBL;
  11711. Limit := $FF;
  11712. end;
  11713. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11714. begin
  11715. NewSize := S_W;
  11716. NewRegSize := R_SUBW;
  11717. Limit := $FFFF;
  11718. end;
  11719. {$ifdef x86_64}
  11720. S_LQ:
  11721. begin
  11722. NewSize := S_L;
  11723. NewRegSize := R_SUBD;
  11724. Limit := $FFFFFFFF;
  11725. end;
  11726. {$endif x86_64}
  11727. else
  11728. Internalerror(2021120302);
  11729. end;
  11730. TransferUsedRegs(TmpUsedRegs);
  11731. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11732. if AndTest then
  11733. begin
  11734. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11735. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11736. end
  11737. else
  11738. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11739. if
  11740. (
  11741. (taicpu(p).opcode = A_MOVZX) and
  11742. (
  11743. (taicpu(hp1).opcode=A_AND) or
  11744. (taicpu(hp1).opcode=A_TEST)
  11745. ) and
  11746. not (
  11747. { If both are references, then the final instruction will have
  11748. both operands as references, which is not allowed }
  11749. (taicpu(p).oper[0]^.typ = top_ref) and
  11750. (taicpu(hp1).oper[0]^.typ = top_ref)
  11751. ) and
  11752. not RegUsed
  11753. ) or
  11754. (
  11755. (
  11756. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11757. not RegUsed
  11758. ) and
  11759. (taicpu(p).oper[0]^.typ = top_reg) and
  11760. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11761. (taicpu(hp1).oper[0]^.typ = top_const) and
  11762. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11763. ) then
  11764. begin
  11765. {$if defined(i386) or defined(i8086)}
  11766. { If the target size is 8-bit, make sure we can actually encode it }
  11767. 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
  11768. Exit;
  11769. {$endif i386 or i8086}
  11770. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11771. taicpu(hp1).opsize := NewSize;
  11772. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11773. if AndTest then
  11774. begin
  11775. RemoveInstruction(hp2);
  11776. if not RegUsed then
  11777. begin
  11778. taicpu(hp1).opcode := A_TEST;
  11779. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11780. begin
  11781. { Make sure the reference is the second operand }
  11782. SwapOper := taicpu(hp1).oper[0];
  11783. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11784. taicpu(hp1).oper[1] := SwapOper;
  11785. end;
  11786. end;
  11787. end;
  11788. case taicpu(hp1).oper[0]^.typ of
  11789. top_reg:
  11790. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  11791. top_const:
  11792. { For the AND/TEST case }
  11793. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  11794. else
  11795. ;
  11796. end;
  11797. if RegUsed then
  11798. begin
  11799. AsmL.Remove(p);
  11800. AsmL.InsertAfter(p, hp1);
  11801. p := hp1;
  11802. end
  11803. else
  11804. RemoveCurrentP(p, hp1);
  11805. result:=true;
  11806. exit;
  11807. end;
  11808. end;
  11809. end;
  11810. if reg_and_hp1_is_instr and
  11811. (taicpu(p).oper[0]^.typ = top_reg) and
  11812. (
  11813. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  11814. ) and
  11815. (taicpu(hp1).oper[0]^.typ = top_const) and
  11816. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11817. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11818. { Minimum shift value allowed is the bit difference between the sizes }
  11819. (taicpu(hp1).oper[0]^.val >=
  11820. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11821. 8 * (
  11822. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  11823. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11824. )
  11825. ) then
  11826. begin
  11827. { For:
  11828. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  11829. shl/sal ##, %reg1
  11830. Remove the movsx/movzx instruction if the shift overwrites the
  11831. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  11832. }
  11833. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  11834. RemoveCurrentP(p, hp1);
  11835. Result := True;
  11836. Exit;
  11837. end
  11838. else if reg_and_hp1_is_instr and
  11839. (taicpu(p).oper[0]^.typ = top_reg) and
  11840. (
  11841. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  11842. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  11843. ) and
  11844. (taicpu(hp1).oper[0]^.typ = top_const) and
  11845. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11846. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11847. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  11848. (taicpu(hp1).oper[0]^.val <
  11849. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11850. 8 * (
  11851. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11852. )
  11853. ) then
  11854. begin
  11855. { For:
  11856. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  11857. sar ##, %reg1 shr ##, %reg1
  11858. Move the shift to before the movx instruction if the shift value
  11859. is not too large.
  11860. }
  11861. asml.Remove(hp1);
  11862. asml.InsertBefore(hp1, p);
  11863. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11864. case taicpu(p).opsize of
  11865. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  11866. taicpu(hp1).opsize := S_B;
  11867. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  11868. taicpu(hp1).opsize := S_W;
  11869. {$ifdef x86_64}
  11870. S_LQ:
  11871. taicpu(hp1).opsize := S_L;
  11872. {$endif}
  11873. else
  11874. InternalError(2020112401);
  11875. end;
  11876. if (taicpu(hp1).opcode = A_SHR) then
  11877. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  11878. else
  11879. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  11880. Result := True;
  11881. end;
  11882. if reg_and_hp1_is_instr and
  11883. (taicpu(p).oper[0]^.typ = top_reg) and
  11884. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11885. (
  11886. (taicpu(hp1).opcode = taicpu(p).opcode)
  11887. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  11888. {$ifdef x86_64}
  11889. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  11890. {$endif x86_64}
  11891. ) then
  11892. begin
  11893. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  11894. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  11895. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11896. begin
  11897. {
  11898. For example:
  11899. movzbw %al,%ax
  11900. movzwl %ax,%eax
  11901. Compress into:
  11902. movzbl %al,%eax
  11903. }
  11904. RegUsed := False;
  11905. case taicpu(p).opsize of
  11906. S_BW:
  11907. case taicpu(hp1).opsize of
  11908. S_WL:
  11909. begin
  11910. taicpu(p).opsize := S_BL;
  11911. RegUsed := True;
  11912. end;
  11913. {$ifdef x86_64}
  11914. S_WQ:
  11915. begin
  11916. if taicpu(p).opcode = A_MOVZX then
  11917. begin
  11918. taicpu(p).opsize := S_BL;
  11919. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11920. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11921. end
  11922. else
  11923. taicpu(p).opsize := S_BQ;
  11924. RegUsed := True;
  11925. end;
  11926. {$endif x86_64}
  11927. else
  11928. ;
  11929. end;
  11930. {$ifdef x86_64}
  11931. S_BL:
  11932. case taicpu(hp1).opsize of
  11933. S_LQ:
  11934. begin
  11935. if taicpu(p).opcode = A_MOVZX then
  11936. begin
  11937. taicpu(p).opsize := S_BL;
  11938. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11939. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11940. end
  11941. else
  11942. taicpu(p).opsize := S_BQ;
  11943. RegUsed := True;
  11944. end;
  11945. else
  11946. ;
  11947. end;
  11948. S_WL:
  11949. case taicpu(hp1).opsize of
  11950. S_LQ:
  11951. begin
  11952. if taicpu(p).opcode = A_MOVZX then
  11953. begin
  11954. taicpu(p).opsize := S_WL;
  11955. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11956. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11957. end
  11958. else
  11959. taicpu(p).opsize := S_WQ;
  11960. RegUsed := True;
  11961. end;
  11962. else
  11963. ;
  11964. end;
  11965. {$endif x86_64}
  11966. else
  11967. ;
  11968. end;
  11969. if RegUsed then
  11970. begin
  11971. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  11972. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  11973. RemoveInstruction(hp1);
  11974. Result := True;
  11975. Exit;
  11976. end;
  11977. end;
  11978. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  11979. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  11980. GetNextInstruction(hp1, hp2) and
  11981. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  11982. (
  11983. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  11984. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  11985. {$ifdef x86_64}
  11986. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  11987. {$endif x86_64}
  11988. ) and
  11989. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11990. (
  11991. (
  11992. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11993. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11994. ) or
  11995. (
  11996. { Only allow the operands in reverse order for TEST instructions }
  11997. (taicpu(hp2).opcode = A_TEST) and
  11998. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11999. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12000. )
  12001. ) then
  12002. begin
  12003. {
  12004. For example:
  12005. movzbl %al,%eax
  12006. movzbl (ref),%edx
  12007. andl %edx,%eax
  12008. (%edx deallocated)
  12009. Change to:
  12010. andb (ref),%al
  12011. movzbl %al,%eax
  12012. Rules are:
  12013. - First two instructions have the same opcode and opsize
  12014. - First instruction's operands are the same super-register
  12015. - Second instruction operates on a different register
  12016. - Third instruction is AND, OR, XOR or TEST
  12017. - Third instruction's operands are the destination registers of the first two instructions
  12018. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12019. - Second instruction's destination register is deallocated afterwards
  12020. }
  12021. TransferUsedRegs(TmpUsedRegs);
  12022. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12023. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12024. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12025. begin
  12026. case taicpu(p).opsize of
  12027. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12028. NewSize := S_B;
  12029. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12030. NewSize := S_W;
  12031. {$ifdef x86_64}
  12032. S_LQ:
  12033. NewSize := S_L;
  12034. {$endif x86_64}
  12035. else
  12036. InternalError(2021120301);
  12037. end;
  12038. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12039. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12040. taicpu(hp2).opsize := NewSize;
  12041. RemoveInstruction(hp1);
  12042. { With TEST, it's best to keep the MOVX instruction at the top }
  12043. if (taicpu(hp2).opcode <> A_TEST) then
  12044. begin
  12045. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12046. asml.Remove(p);
  12047. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12048. asml.InsertAfter(p, hp2);
  12049. p := hp2;
  12050. end
  12051. else
  12052. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12053. Result := True;
  12054. Exit;
  12055. end;
  12056. end;
  12057. end;
  12058. if taicpu(p).opcode=A_MOVZX then
  12059. begin
  12060. { removes superfluous And's after movzx's }
  12061. if reg_and_hp1_is_instr and
  12062. (taicpu(hp1).opcode = A_AND) and
  12063. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12064. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12065. {$ifdef x86_64}
  12066. { check for implicit extension to 64 bit }
  12067. or
  12068. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12069. (taicpu(hp1).opsize=S_Q) and
  12070. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12071. )
  12072. {$endif x86_64}
  12073. )
  12074. then
  12075. begin
  12076. case taicpu(p).opsize Of
  12077. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12078. if (taicpu(hp1).oper[0]^.val = $ff) then
  12079. begin
  12080. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12081. RemoveInstruction(hp1);
  12082. Result:=true;
  12083. exit;
  12084. end;
  12085. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12086. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12087. begin
  12088. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12089. RemoveInstruction(hp1);
  12090. Result:=true;
  12091. exit;
  12092. end;
  12093. {$ifdef x86_64}
  12094. S_LQ:
  12095. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12096. begin
  12097. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12098. RemoveInstruction(hp1);
  12099. Result:=true;
  12100. exit;
  12101. end;
  12102. {$endif x86_64}
  12103. else
  12104. ;
  12105. end;
  12106. { we cannot get rid of the and, but can we get rid of the movz ?}
  12107. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12108. begin
  12109. case taicpu(p).opsize Of
  12110. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12111. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12112. begin
  12113. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12114. RemoveCurrentP(p,hp1);
  12115. Result:=true;
  12116. exit;
  12117. end;
  12118. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12119. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12120. begin
  12121. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12122. RemoveCurrentP(p,hp1);
  12123. Result:=true;
  12124. exit;
  12125. end;
  12126. {$ifdef x86_64}
  12127. S_LQ:
  12128. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12129. begin
  12130. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12131. RemoveCurrentP(p,hp1);
  12132. Result:=true;
  12133. exit;
  12134. end;
  12135. {$endif x86_64}
  12136. else
  12137. ;
  12138. end;
  12139. end;
  12140. end;
  12141. { changes some movzx constructs to faster synonyms (all examples
  12142. are given with eax/ax, but are also valid for other registers)}
  12143. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12144. begin
  12145. case taicpu(p).opsize of
  12146. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12147. (the machine code is equivalent to movzbl %al,%eax), but the
  12148. code generator still generates that assembler instruction and
  12149. it is silently converted. This should probably be checked.
  12150. [Kit] }
  12151. S_BW:
  12152. begin
  12153. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12154. (
  12155. not IsMOVZXAcceptable
  12156. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12157. or (
  12158. (cs_opt_size in current_settings.optimizerswitches) and
  12159. (taicpu(p).oper[1]^.reg = NR_AX)
  12160. )
  12161. ) then
  12162. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12163. begin
  12164. DebugMsg(SPeepholeOptimization + 'var7',p);
  12165. taicpu(p).opcode := A_AND;
  12166. taicpu(p).changeopsize(S_W);
  12167. taicpu(p).loadConst(0,$ff);
  12168. Result := True;
  12169. end
  12170. else if not IsMOVZXAcceptable and
  12171. GetNextInstruction(p, hp1) and
  12172. (tai(hp1).typ = ait_instruction) and
  12173. (taicpu(hp1).opcode = A_AND) and
  12174. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12175. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12176. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12177. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12178. begin
  12179. DebugMsg(SPeepholeOptimization + 'var8',p);
  12180. taicpu(p).opcode := A_MOV;
  12181. taicpu(p).changeopsize(S_W);
  12182. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12183. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12184. Result := True;
  12185. end;
  12186. end;
  12187. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12188. S_BL:
  12189. if not IsMOVZXAcceptable then
  12190. begin
  12191. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12192. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12193. begin
  12194. DebugMsg(SPeepholeOptimization + 'var9',p);
  12195. taicpu(p).opcode := A_AND;
  12196. taicpu(p).changeopsize(S_L);
  12197. taicpu(p).loadConst(0,$ff);
  12198. Result := True;
  12199. end
  12200. else if GetNextInstruction(p, hp1) and
  12201. (tai(hp1).typ = ait_instruction) and
  12202. (taicpu(hp1).opcode = A_AND) and
  12203. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12204. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12205. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12206. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12207. begin
  12208. DebugMsg(SPeepholeOptimization + 'var10',p);
  12209. taicpu(p).opcode := A_MOV;
  12210. taicpu(p).changeopsize(S_L);
  12211. { do not use R_SUBWHOLE
  12212. as movl %rdx,%eax
  12213. is invalid in assembler PM }
  12214. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12215. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12216. Result := True;
  12217. end;
  12218. end;
  12219. {$endif i8086}
  12220. S_WL:
  12221. if not IsMOVZXAcceptable then
  12222. begin
  12223. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12224. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12225. begin
  12226. DebugMsg(SPeepholeOptimization + 'var11',p);
  12227. taicpu(p).opcode := A_AND;
  12228. taicpu(p).changeopsize(S_L);
  12229. taicpu(p).loadConst(0,$ffff);
  12230. Result := True;
  12231. end
  12232. else if GetNextInstruction(p, hp1) and
  12233. (tai(hp1).typ = ait_instruction) and
  12234. (taicpu(hp1).opcode = A_AND) and
  12235. (taicpu(hp1).oper[0]^.typ = top_const) and
  12236. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12237. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12238. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12239. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12240. begin
  12241. DebugMsg(SPeepholeOptimization + 'var12',p);
  12242. taicpu(p).opcode := A_MOV;
  12243. taicpu(p).changeopsize(S_L);
  12244. { do not use R_SUBWHOLE
  12245. as movl %rdx,%eax
  12246. is invalid in assembler PM }
  12247. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12248. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12249. Result := True;
  12250. end;
  12251. end;
  12252. else
  12253. InternalError(2017050705);
  12254. end;
  12255. end
  12256. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12257. begin
  12258. if GetNextInstruction(p, hp1) and
  12259. (tai(hp1).typ = ait_instruction) 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) then
  12263. begin
  12264. //taicpu(p).opcode := A_MOV;
  12265. case taicpu(p).opsize Of
  12266. S_BL:
  12267. begin
  12268. DebugMsg(SPeepholeOptimization + 'var13',p);
  12269. taicpu(hp1).changeopsize(S_L);
  12270. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12271. end;
  12272. S_WL:
  12273. begin
  12274. DebugMsg(SPeepholeOptimization + 'var14',p);
  12275. taicpu(hp1).changeopsize(S_L);
  12276. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12277. end;
  12278. S_BW:
  12279. begin
  12280. DebugMsg(SPeepholeOptimization + 'var15',p);
  12281. taicpu(hp1).changeopsize(S_W);
  12282. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12283. end;
  12284. else
  12285. Internalerror(2017050704)
  12286. end;
  12287. Result := True;
  12288. end;
  12289. end;
  12290. end;
  12291. end;
  12292. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12293. var
  12294. hp1, hp2 : tai;
  12295. MaskLength : Cardinal;
  12296. MaskedBits : TCgInt;
  12297. ActiveReg : TRegister;
  12298. begin
  12299. Result:=false;
  12300. { There are no optimisations for reference targets }
  12301. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12302. Exit;
  12303. while GetNextInstruction(p, hp1) and
  12304. (hp1.typ = ait_instruction) do
  12305. begin
  12306. if (taicpu(p).oper[0]^.typ = top_const) then
  12307. begin
  12308. case taicpu(hp1).opcode of
  12309. A_AND:
  12310. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12311. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12312. { the second register must contain the first one, so compare their subreg types }
  12313. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12314. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12315. { change
  12316. and const1, reg
  12317. and const2, reg
  12318. to
  12319. and (const1 and const2), reg
  12320. }
  12321. begin
  12322. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12323. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12324. RemoveCurrentP(p, hp1);
  12325. Result:=true;
  12326. exit;
  12327. end;
  12328. A_CMP:
  12329. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12330. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12331. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12332. { Just check that the condition on the next instruction is compatible }
  12333. GetNextInstruction(hp1, hp2) and
  12334. (hp2.typ = ait_instruction) and
  12335. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12336. then
  12337. { change
  12338. and 2^n, reg
  12339. cmp 2^n, reg
  12340. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12341. to
  12342. and 2^n, reg
  12343. test reg, reg
  12344. j(~c) / set(~c) / cmov(~c)
  12345. }
  12346. begin
  12347. { Keep TEST instruction in, rather than remove it, because
  12348. it may trigger other optimisations such as MovAndTest2Test }
  12349. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12350. taicpu(hp1).opcode := A_TEST;
  12351. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12352. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12353. Result := True;
  12354. Exit;
  12355. end
  12356. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12357. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12358. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12359. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12360. { change
  12361. and $ff/$ff/$ffff, reg
  12362. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12363. dealloc reg
  12364. to
  12365. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12366. }
  12367. begin
  12368. TransferUsedRegs(TmpUsedRegs);
  12369. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12370. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12371. begin
  12372. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12373. case taicpu(p).oper[0]^.val of
  12374. $ff:
  12375. begin
  12376. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12377. taicpu(hp1).opsize:=S_B;
  12378. end;
  12379. $ffff:
  12380. begin
  12381. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12382. taicpu(hp1).opsize:=S_W;
  12383. end;
  12384. $ffffffff:
  12385. begin
  12386. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12387. taicpu(hp1).opsize:=S_L;
  12388. end;
  12389. else
  12390. Internalerror(2023030401);
  12391. end;
  12392. RemoveCurrentP(p);
  12393. Result := True;
  12394. Exit;
  12395. end;
  12396. end;
  12397. A_MOVZX:
  12398. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12399. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12400. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12401. (
  12402. (
  12403. (taicpu(p).opsize=S_W) and
  12404. (taicpu(hp1).opsize=S_BW)
  12405. ) or
  12406. (
  12407. (taicpu(p).opsize=S_L) and
  12408. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12409. )
  12410. {$ifdef x86_64}
  12411. or
  12412. (
  12413. (taicpu(p).opsize=S_Q) and
  12414. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12415. )
  12416. {$endif x86_64}
  12417. ) then
  12418. begin
  12419. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12420. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12421. ) or
  12422. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12423. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12424. then
  12425. begin
  12426. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12427. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12428. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12429. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12430. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12431. }
  12432. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12433. RemoveInstruction(hp1);
  12434. { See if there are other optimisations possible }
  12435. Continue;
  12436. end;
  12437. end;
  12438. A_SHL:
  12439. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12440. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12441. begin
  12442. {$ifopt R+}
  12443. {$define RANGE_WAS_ON}
  12444. {$R-}
  12445. {$endif}
  12446. { get length of potential and mask }
  12447. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12448. { really a mask? }
  12449. {$ifdef RANGE_WAS_ON}
  12450. {$R+}
  12451. {$endif}
  12452. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12453. { unmasked part shifted out? }
  12454. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12455. begin
  12456. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12457. RemoveCurrentP(p, hp1);
  12458. Result:=true;
  12459. exit;
  12460. end;
  12461. end;
  12462. A_SHR:
  12463. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12464. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12465. (taicpu(hp1).oper[0]^.val <= 63) then
  12466. begin
  12467. { Does SHR combined with the AND cover all the bits?
  12468. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12469. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12470. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12471. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12472. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12473. begin
  12474. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12475. RemoveCurrentP(p, hp1);
  12476. Result := True;
  12477. Exit;
  12478. end;
  12479. end;
  12480. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12481. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12482. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12483. begin
  12484. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12485. (
  12486. (
  12487. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12488. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12489. ) or (
  12490. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12491. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12492. {$ifdef x86_64}
  12493. ) or (
  12494. (taicpu(hp1).opsize = S_LQ) and
  12495. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12496. {$endif x86_64}
  12497. )
  12498. ) then
  12499. begin
  12500. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12501. begin
  12502. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12503. RemoveInstruction(hp1);
  12504. { See if there are other optimisations possible }
  12505. Continue;
  12506. end;
  12507. { The super-registers are the same though.
  12508. Note that this change by itself doesn't improve
  12509. code speed, but it opens up other optimisations. }
  12510. {$ifdef x86_64}
  12511. { Convert 64-bit register to 32-bit }
  12512. case taicpu(hp1).opsize of
  12513. S_BQ:
  12514. begin
  12515. taicpu(hp1).opsize := S_BL;
  12516. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12517. end;
  12518. S_WQ:
  12519. begin
  12520. taicpu(hp1).opsize := S_WL;
  12521. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12522. end
  12523. else
  12524. ;
  12525. end;
  12526. {$endif x86_64}
  12527. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12528. taicpu(hp1).opcode := A_MOVZX;
  12529. { See if there are other optimisations possible }
  12530. Continue;
  12531. end;
  12532. end;
  12533. else
  12534. ;
  12535. end;
  12536. end
  12537. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12538. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12539. begin
  12540. {$ifdef x86_64}
  12541. if (taicpu(p).opsize = S_Q) then
  12542. begin
  12543. { Never necessary }
  12544. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12545. RemoveCurrentP(p, hp1);
  12546. Result := True;
  12547. Exit;
  12548. end;
  12549. {$endif x86_64}
  12550. { Forward check to determine necessity of and %reg,%reg }
  12551. TransferUsedRegs(TmpUsedRegs);
  12552. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12553. { Saves on a bunch of dereferences }
  12554. ActiveReg := taicpu(p).oper[1]^.reg;
  12555. case taicpu(hp1).opcode of
  12556. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12557. if (
  12558. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12559. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12560. ) and
  12561. (
  12562. (taicpu(hp1).opcode <> A_MOV) or
  12563. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12564. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12565. ) and
  12566. not (
  12567. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12568. (taicpu(hp1).opcode = A_MOV) and
  12569. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12570. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12571. ) and
  12572. (
  12573. (
  12574. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12575. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12576. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12577. ) or
  12578. (
  12579. {$ifdef x86_64}
  12580. (
  12581. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12582. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12583. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12584. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12585. ) and
  12586. {$endif x86_64}
  12587. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12588. )
  12589. ) then
  12590. begin
  12591. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12592. RemoveCurrentP(p, hp1);
  12593. Result := True;
  12594. Exit;
  12595. end;
  12596. A_ADD,
  12597. A_AND,
  12598. A_BSF,
  12599. A_BSR,
  12600. A_BTC,
  12601. A_BTR,
  12602. A_BTS,
  12603. A_OR,
  12604. A_SUB,
  12605. A_XOR:
  12606. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12607. if (
  12608. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12609. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12610. ) and
  12611. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12612. begin
  12613. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12614. RemoveCurrentP(p, hp1);
  12615. Result := True;
  12616. Exit;
  12617. end;
  12618. A_CMP,
  12619. A_TEST:
  12620. if (
  12621. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12622. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12623. ) and
  12624. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12625. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12626. begin
  12627. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12628. RemoveCurrentP(p, hp1);
  12629. Result := True;
  12630. Exit;
  12631. end;
  12632. A_BSWAP,
  12633. A_NEG,
  12634. A_NOT:
  12635. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12636. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12637. begin
  12638. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12639. RemoveCurrentP(p, hp1);
  12640. Result := True;
  12641. Exit;
  12642. end;
  12643. else
  12644. ;
  12645. end;
  12646. end;
  12647. if (taicpu(hp1).is_jmp) and
  12648. (taicpu(hp1).opcode<>A_JMP) and
  12649. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12650. begin
  12651. { change
  12652. and x, reg
  12653. jxx
  12654. to
  12655. test x, reg
  12656. jxx
  12657. if reg is deallocated before the
  12658. jump, but only if it's a conditional jump (PFV)
  12659. }
  12660. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12661. taicpu(p).opcode := A_TEST;
  12662. Exit;
  12663. end;
  12664. Break;
  12665. end;
  12666. { Lone AND tests }
  12667. if (taicpu(p).oper[0]^.typ = top_const) then
  12668. begin
  12669. {
  12670. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12671. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12672. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12673. }
  12674. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12675. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12676. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12677. begin
  12678. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12679. if taicpu(p).opsize = S_L then
  12680. begin
  12681. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12682. Result := True;
  12683. end;
  12684. end;
  12685. end;
  12686. { Backward check to determine necessity of and %reg,%reg }
  12687. if (taicpu(p).oper[0]^.typ = top_reg) and
  12688. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12689. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12690. GetLastInstruction(p, hp2) and
  12691. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12692. { Check size of adjacent instruction to determine if the AND is
  12693. effectively a null operation }
  12694. (
  12695. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12696. { Note: Don't include S_Q }
  12697. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12698. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12699. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12700. ) then
  12701. begin
  12702. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12703. { If GetNextInstruction returned False, hp1 will be nil }
  12704. RemoveCurrentP(p, hp1);
  12705. Result := True;
  12706. Exit;
  12707. end;
  12708. end;
  12709. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12710. var
  12711. hp1, hp2: tai;
  12712. NewRef: TReference;
  12713. Distance: Cardinal;
  12714. TempTracking: TAllUsedRegs;
  12715. { This entire nested function is used in an if-statement below, but we
  12716. want to avoid all the used reg transfers and GetNextInstruction calls
  12717. until we really have to check }
  12718. function MemRegisterNotUsedLater: Boolean; inline;
  12719. var
  12720. hp2: tai;
  12721. begin
  12722. TransferUsedRegs(TmpUsedRegs);
  12723. hp2 := p;
  12724. repeat
  12725. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12726. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12727. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12728. end;
  12729. begin
  12730. Result := False;
  12731. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12732. (taicpu(p).oper[1]^.typ = top_reg) then
  12733. begin
  12734. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12735. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12736. (hp1.typ <> ait_instruction) or
  12737. not
  12738. (
  12739. (cs_opt_level3 in current_settings.optimizerswitches) or
  12740. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12741. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12742. ) then
  12743. Exit;
  12744. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12745. addq $x, %rax
  12746. movq %rax, %rdx
  12747. sarq $63, %rdx
  12748. (%rax still in use)
  12749. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12750. leaq $x(%rax),%rdx
  12751. addq $x, %rax
  12752. sarq $63, %rdx
  12753. ...which is okay since it breaks the dependency chain between
  12754. addq and movq, but if OptPass2MOV is called first:
  12755. addq $x, %rax
  12756. cqto
  12757. ...which is better in all ways, taking only 2 cycles to execute
  12758. and much smaller in code size.
  12759. }
  12760. { The extra register tracking is quite strenuous }
  12761. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12762. MatchInstruction(hp1, A_MOV, []) then
  12763. begin
  12764. { Update the register tracking to the MOV instruction }
  12765. CopyUsedRegs(TempTracking);
  12766. hp2 := p;
  12767. repeat
  12768. UpdateUsedRegs(tai(hp2.Next));
  12769. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12770. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12771. OptPass2ADD get called again }
  12772. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12773. begin
  12774. { Reset the tracking to the current instruction }
  12775. RestoreUsedRegs(TempTracking);
  12776. ReleaseUsedRegs(TempTracking);
  12777. Result := True;
  12778. Exit;
  12779. end;
  12780. { Reset the tracking to the current instruction }
  12781. RestoreUsedRegs(TempTracking);
  12782. ReleaseUsedRegs(TempTracking);
  12783. { If OptPass2MOV returned True, we don't need to set Result to
  12784. True if hp1 didn't change because the ADD instruction didn't
  12785. get modified and we'll be evaluating hp1 again when the
  12786. peephole optimizer reaches it }
  12787. end;
  12788. { Change:
  12789. add %reg2,%reg1
  12790. (%reg2 not modified in between)
  12791. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  12792. To:
  12793. mov/s/z #(%reg1,%reg2),%reg1
  12794. }
  12795. if (taicpu(p).oper[0]^.typ = top_reg) and
  12796. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  12797. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  12798. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  12799. (
  12800. (
  12801. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  12802. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  12803. { r/esp cannot be an index }
  12804. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  12805. ) or (
  12806. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  12807. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  12808. )
  12809. ) and (
  12810. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  12811. (
  12812. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  12813. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12814. MemRegisterNotUsedLater
  12815. )
  12816. ) then
  12817. begin
  12818. if (
  12819. { Instructions are guaranteed to be adjacent on -O2 and under }
  12820. (cs_opt_level3 in current_settings.optimizerswitches) and
  12821. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  12822. ) then
  12823. begin
  12824. { If the other register is used in between, move the MOV
  12825. instruction to right after the ADD instruction so a
  12826. saving can still be made }
  12827. Asml.Remove(hp1);
  12828. Asml.InsertAfter(hp1, p);
  12829. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12830. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12831. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  12832. RemoveCurrentp(p, hp1);
  12833. end
  12834. else
  12835. begin
  12836. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  12837. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12838. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12839. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  12840. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12841. { hp1 may not be the immediate next instruction under -O3 }
  12842. RemoveCurrentp(p)
  12843. else
  12844. RemoveCurrentp(p, hp1);
  12845. end;
  12846. Result := True;
  12847. Exit;
  12848. end;
  12849. { Change:
  12850. addl/q $x,%reg1
  12851. movl/q %reg1,%reg2
  12852. To:
  12853. leal/q $x(%reg1),%reg2
  12854. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12855. Breaks the dependency chain.
  12856. }
  12857. if (taicpu(p).oper[0]^.typ = top_const) and
  12858. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12859. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12860. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12861. (
  12862. { Instructions are guaranteed to be adjacent on -O2 and under }
  12863. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12864. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12865. ) then
  12866. begin
  12867. TransferUsedRegs(TmpUsedRegs);
  12868. hp2 := p;
  12869. repeat
  12870. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12871. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12872. if (
  12873. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  12874. not (cs_opt_size in current_settings.optimizerswitches) or
  12875. (
  12876. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12877. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12878. )
  12879. ) then
  12880. begin
  12881. { Change the MOV instruction to a LEA instruction, and update the
  12882. first operand }
  12883. reference_reset(NewRef, 1, []);
  12884. NewRef.base := taicpu(p).oper[1]^.reg;
  12885. NewRef.scalefactor := 1;
  12886. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  12887. taicpu(hp1).opcode := A_LEA;
  12888. taicpu(hp1).loadref(0, NewRef);
  12889. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12890. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12891. begin
  12892. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12893. { Move what is now the LEA instruction to before the ADD instruction }
  12894. Asml.Remove(hp1);
  12895. Asml.InsertBefore(hp1, p);
  12896. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12897. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  12898. p := hp1;
  12899. end
  12900. else
  12901. begin
  12902. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12903. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  12904. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12905. { hp1 may not be the immediate next instruction under -O3 }
  12906. RemoveCurrentp(p)
  12907. else
  12908. RemoveCurrentp(p, hp1);
  12909. end;
  12910. Result := True;
  12911. end;
  12912. end;
  12913. end;
  12914. end;
  12915. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  12916. var
  12917. SubReg: TSubRegister;
  12918. begin
  12919. Result:=false;
  12920. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  12921. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12922. with taicpu(p).oper[0]^.ref^ do
  12923. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  12924. begin
  12925. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  12926. begin
  12927. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  12928. taicpu(p).opcode := A_ADD;
  12929. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  12930. Result := True;
  12931. end
  12932. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  12933. begin
  12934. if (base <> NR_NO) then
  12935. begin
  12936. if (scalefactor <= 1) then
  12937. begin
  12938. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  12939. taicpu(p).opcode := A_ADD;
  12940. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  12941. Result := True;
  12942. end;
  12943. end
  12944. else
  12945. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  12946. if (scalefactor in [2, 4, 8]) then
  12947. begin
  12948. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  12949. taicpu(p).loadconst(0, BsrByte(scalefactor));
  12950. taicpu(p).opcode := A_SHL;
  12951. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  12952. Result := True;
  12953. end;
  12954. end;
  12955. end;
  12956. end;
  12957. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  12958. var
  12959. hp1, hp2: tai;
  12960. NewRef: TReference;
  12961. Distance: Cardinal;
  12962. TempTracking: TAllUsedRegs;
  12963. begin
  12964. Result := False;
  12965. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12966. MatchOpType(taicpu(p),top_const,top_reg) then
  12967. begin
  12968. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12969. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12970. (hp1.typ <> ait_instruction) or
  12971. not
  12972. (
  12973. (cs_opt_level3 in current_settings.optimizerswitches) or
  12974. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12975. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12976. ) then
  12977. Exit;
  12978. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12979. subq $x, %rax
  12980. movq %rax, %rdx
  12981. sarq $63, %rdx
  12982. (%rax still in use)
  12983. ...letting OptPass2SUB run its course (and without -Os) will produce:
  12984. leaq $-x(%rax),%rdx
  12985. movq $x, %rax
  12986. sarq $63, %rdx
  12987. ...which is okay since it breaks the dependency chain between
  12988. subq and movq, but if OptPass2MOV is called first:
  12989. subq $x, %rax
  12990. cqto
  12991. ...which is better in all ways, taking only 2 cycles to execute
  12992. and much smaller in code size.
  12993. }
  12994. { The extra register tracking is quite strenuous }
  12995. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12996. MatchInstruction(hp1, A_MOV, []) then
  12997. begin
  12998. { Update the register tracking to the MOV instruction }
  12999. CopyUsedRegs(TempTracking);
  13000. hp2 := p;
  13001. repeat
  13002. UpdateUsedRegs(tai(hp2.Next));
  13003. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13004. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13005. OptPass2SUB get called again }
  13006. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13007. begin
  13008. { Reset the tracking to the current instruction }
  13009. RestoreUsedRegs(TempTracking);
  13010. ReleaseUsedRegs(TempTracking);
  13011. Result := True;
  13012. Exit;
  13013. end;
  13014. { Reset the tracking to the current instruction }
  13015. RestoreUsedRegs(TempTracking);
  13016. ReleaseUsedRegs(TempTracking);
  13017. { If OptPass2MOV returned True, we don't need to set Result to
  13018. True if hp1 didn't change because the SUB instruction didn't
  13019. get modified and we'll be evaluating hp1 again when the
  13020. peephole optimizer reaches it }
  13021. end;
  13022. { Change:
  13023. subl/q $x,%reg1
  13024. movl/q %reg1,%reg2
  13025. To:
  13026. leal/q $-x(%reg1),%reg2
  13027. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13028. Breaks the dependency chain and potentially permits the removal of
  13029. a CMP instruction if one follows.
  13030. }
  13031. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13032. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13033. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13034. (
  13035. { Instructions are guaranteed to be adjacent on -O2 and under }
  13036. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13037. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13038. ) then
  13039. begin
  13040. TransferUsedRegs(TmpUsedRegs);
  13041. hp2 := p;
  13042. repeat
  13043. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13044. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13045. if (
  13046. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13047. not (cs_opt_size in current_settings.optimizerswitches) or
  13048. (
  13049. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13050. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13051. )
  13052. ) then
  13053. begin
  13054. { Change the MOV instruction to a LEA instruction, and update the
  13055. first operand }
  13056. reference_reset(NewRef, 1, []);
  13057. NewRef.base := taicpu(p).oper[1]^.reg;
  13058. NewRef.scalefactor := 1;
  13059. NewRef.offset := -taicpu(p).oper[0]^.val;
  13060. taicpu(hp1).opcode := A_LEA;
  13061. taicpu(hp1).loadref(0, NewRef);
  13062. TransferUsedRegs(TmpUsedRegs);
  13063. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13064. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13065. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13066. begin
  13067. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13068. { Move what is now the LEA instruction to before the SUB instruction }
  13069. Asml.Remove(hp1);
  13070. Asml.InsertBefore(hp1, p);
  13071. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13072. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13073. p := hp1;
  13074. end
  13075. else
  13076. begin
  13077. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13078. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13079. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13080. { hp1 may not be the immediate next instruction under -O3 }
  13081. RemoveCurrentp(p)
  13082. else
  13083. RemoveCurrentp(p, hp1);
  13084. end;
  13085. Result := True;
  13086. end;
  13087. end;
  13088. end;
  13089. end;
  13090. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13091. begin
  13092. { we can skip all instructions not messing with the stack pointer }
  13093. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13094. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13095. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13096. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13097. ({(taicpu(hp1).ops=0) or }
  13098. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13099. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13100. ) and }
  13101. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13102. )
  13103. ) do
  13104. GetNextInstruction(hp1,hp1);
  13105. Result:=assigned(hp1);
  13106. end;
  13107. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13108. var
  13109. hp1, hp2, hp3, hp4, hp5: tai;
  13110. begin
  13111. Result:=false;
  13112. hp5:=nil;
  13113. { replace
  13114. leal(q) x(<stackpointer>),<stackpointer>
  13115. call procname
  13116. leal(q) -x(<stackpointer>),<stackpointer>
  13117. ret
  13118. by
  13119. jmp procname
  13120. but do it only on level 4 because it destroys stack back traces
  13121. }
  13122. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13123. MatchOpType(taicpu(p),top_ref,top_reg) and
  13124. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13125. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13126. { the -8 or -24 are not required, but bail out early if possible,
  13127. higher values are unlikely }
  13128. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13129. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13130. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13131. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13132. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13133. GetNextInstruction(p, hp1) and
  13134. { Take a copy of hp1 }
  13135. SetAndTest(hp1, hp4) and
  13136. { trick to skip label }
  13137. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13138. SkipSimpleInstructions(hp1) and
  13139. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13140. GetNextInstruction(hp1, hp2) and
  13141. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13142. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13143. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13144. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13145. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13146. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13147. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13148. { Segment register will be NR_NO }
  13149. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13150. GetNextInstruction(hp2, hp3) and
  13151. { trick to skip label }
  13152. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13153. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13154. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13155. SetAndTest(hp3,hp5) and
  13156. GetNextInstruction(hp3,hp3) and
  13157. MatchInstruction(hp3,A_RET,[S_NO])
  13158. )
  13159. ) and
  13160. (taicpu(hp3).ops=0) then
  13161. begin
  13162. taicpu(hp1).opcode := A_JMP;
  13163. taicpu(hp1).is_jmp := true;
  13164. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13165. RemoveCurrentP(p, hp4);
  13166. RemoveInstruction(hp2);
  13167. RemoveInstruction(hp3);
  13168. if Assigned(hp5) then
  13169. begin
  13170. AsmL.Remove(hp5);
  13171. ASmL.InsertBefore(hp5,hp1)
  13172. end;
  13173. Result:=true;
  13174. end;
  13175. end;
  13176. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13177. {$ifdef x86_64}
  13178. var
  13179. hp1, hp2, hp3, hp4, hp5: tai;
  13180. {$endif x86_64}
  13181. begin
  13182. Result:=false;
  13183. {$ifdef x86_64}
  13184. hp5:=nil;
  13185. { replace
  13186. push %rax
  13187. call procname
  13188. pop %rcx
  13189. ret
  13190. by
  13191. jmp procname
  13192. but do it only on level 4 because it destroys stack back traces
  13193. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13194. for all supported calling conventions
  13195. }
  13196. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13197. MatchOpType(taicpu(p),top_reg) and
  13198. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13199. GetNextInstruction(p, hp1) and
  13200. { Take a copy of hp1 }
  13201. SetAndTest(hp1, hp4) and
  13202. { trick to skip label }
  13203. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13204. SkipSimpleInstructions(hp1) and
  13205. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13206. GetNextInstruction(hp1, hp2) and
  13207. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13208. MatchOpType(taicpu(hp2),top_reg) and
  13209. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13210. GetNextInstruction(hp2, hp3) and
  13211. { trick to skip label }
  13212. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13213. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13214. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13215. SetAndTest(hp3,hp5) and
  13216. GetNextInstruction(hp3,hp3) and
  13217. MatchInstruction(hp3,A_RET,[S_NO])
  13218. )
  13219. ) and
  13220. (taicpu(hp3).ops=0) then
  13221. begin
  13222. taicpu(hp1).opcode := A_JMP;
  13223. taicpu(hp1).is_jmp := true;
  13224. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13225. RemoveCurrentP(p, hp4);
  13226. RemoveInstruction(hp2);
  13227. RemoveInstruction(hp3);
  13228. if Assigned(hp5) then
  13229. begin
  13230. AsmL.Remove(hp5);
  13231. ASmL.InsertBefore(hp5,hp1)
  13232. end;
  13233. Result:=true;
  13234. end;
  13235. {$endif x86_64}
  13236. end;
  13237. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13238. var
  13239. Value, RegName: string;
  13240. begin
  13241. Result:=false;
  13242. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13243. begin
  13244. case taicpu(p).oper[0]^.val of
  13245. 0:
  13246. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13247. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13248. begin
  13249. { change "mov $0,%reg" into "xor %reg,%reg" }
  13250. taicpu(p).opcode := A_XOR;
  13251. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13252. Result := True;
  13253. {$ifdef x86_64}
  13254. end
  13255. else if (taicpu(p).opsize = S_Q) then
  13256. begin
  13257. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13258. { The actual optimization }
  13259. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13260. taicpu(p).changeopsize(S_L);
  13261. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13262. Result := True;
  13263. end;
  13264. $1..$FFFFFFFF:
  13265. begin
  13266. { Code size reduction by J. Gareth "Kit" Moreton }
  13267. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13268. case taicpu(p).opsize of
  13269. S_Q:
  13270. begin
  13271. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13272. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13273. { The actual optimization }
  13274. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13275. taicpu(p).changeopsize(S_L);
  13276. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13277. Result := True;
  13278. end;
  13279. else
  13280. { Do nothing };
  13281. end;
  13282. {$endif x86_64}
  13283. end;
  13284. -1:
  13285. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13286. if (cs_opt_size in current_settings.optimizerswitches) and
  13287. (taicpu(p).opsize <> S_B) and
  13288. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13289. begin
  13290. { change "mov $-1,%reg" into "or $-1,%reg" }
  13291. { NOTES:
  13292. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13293. - This operation creates a false dependency on the register, so only do it when optimising for size
  13294. - 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
  13295. }
  13296. taicpu(p).opcode := A_OR;
  13297. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13298. Result := True;
  13299. end;
  13300. else
  13301. { Do nothing };
  13302. end;
  13303. end;
  13304. end;
  13305. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13306. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13307. begin
  13308. Result := False;
  13309. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13310. Exit;
  13311. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13312. so don't bother optimising }
  13313. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13314. Exit;
  13315. if (taicpu(p).oper[0]^.typ <> top_const) or
  13316. { If the value can fit into an 8-bit signed integer, a smaller
  13317. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13318. falls within this range }
  13319. (
  13320. (taicpu(p).oper[0]^.val > -128) and
  13321. (taicpu(p).oper[0]^.val <= 127)
  13322. ) then
  13323. Exit;
  13324. { If we're optimising for size, this is acceptable }
  13325. if (cs_opt_size in current_settings.optimizerswitches) then
  13326. Exit(True);
  13327. if (taicpu(p).oper[1]^.typ = top_reg) and
  13328. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13329. Exit(True);
  13330. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13331. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13332. Exit(True);
  13333. end;
  13334. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13335. var
  13336. hp1: tai;
  13337. Value: TCGInt;
  13338. begin
  13339. Result := False;
  13340. if MatchOpType(taicpu(p), top_const, top_reg) then
  13341. begin
  13342. { Detect:
  13343. andw x, %ax (0 <= x < $8000)
  13344. ...
  13345. movzwl %ax,%eax
  13346. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13347. }
  13348. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13349. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13350. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13351. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13352. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13353. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13354. begin
  13355. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13356. taicpu(hp1).opcode := A_CWDE;
  13357. taicpu(hp1).clearop(0);
  13358. taicpu(hp1).clearop(1);
  13359. taicpu(hp1).ops := 0;
  13360. { A change was made, but not with p, so don't set Result, but
  13361. notify the compiler that a change was made }
  13362. Include(OptsToCheck, aoc_ForceNewIteration);
  13363. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13364. end;
  13365. end;
  13366. { If "not x" is a power of 2 (popcnt = 1), change:
  13367. and $x, %reg/ref
  13368. To:
  13369. btr lb(x), %reg/ref
  13370. }
  13371. if IsBTXAcceptable(p) and
  13372. (
  13373. { Make sure a TEST doesn't follow that plays with the register }
  13374. not GetNextInstruction(p, hp1) or
  13375. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13376. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13377. ) then
  13378. begin
  13379. {$push}{$R-}{$Q-}
  13380. { Value is a sign-extended 32-bit integer - just correct it
  13381. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13382. checks to see if this operand is an immediate. }
  13383. Value := not taicpu(p).oper[0]^.val;
  13384. {$pop}
  13385. {$ifdef x86_64}
  13386. if taicpu(p).opsize = S_L then
  13387. {$endif x86_64}
  13388. Value := Value and $FFFFFFFF;
  13389. if (PopCnt(QWord(Value)) = 1) then
  13390. begin
  13391. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13392. taicpu(p).opcode := A_BTR;
  13393. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13394. Result := True;
  13395. Exit;
  13396. end;
  13397. end;
  13398. end;
  13399. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13400. begin
  13401. Result := False;
  13402. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13403. Exit;
  13404. { Convert:
  13405. movswl %ax,%eax -> cwtl
  13406. movslq %eax,%rax -> cdqe
  13407. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13408. refer to the same opcode and depends only on the assembler's
  13409. current operand-size attribute. [Kit]
  13410. }
  13411. with taicpu(p) do
  13412. case opsize of
  13413. S_WL:
  13414. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13415. begin
  13416. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13417. opcode := A_CWDE;
  13418. clearop(0);
  13419. clearop(1);
  13420. ops := 0;
  13421. Result := True;
  13422. end;
  13423. {$ifdef x86_64}
  13424. S_LQ:
  13425. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13426. begin
  13427. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13428. opcode := A_CDQE;
  13429. clearop(0);
  13430. clearop(1);
  13431. ops := 0;
  13432. Result := True;
  13433. end;
  13434. {$endif x86_64}
  13435. else
  13436. ;
  13437. end;
  13438. end;
  13439. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13440. var
  13441. hp1, hp2: tai;
  13442. IdentityMask, Shift: TCGInt;
  13443. LimitSize: Topsize;
  13444. DoNotMerge: Boolean;
  13445. begin
  13446. Result := False;
  13447. { All these optimisations work on "shr const,%reg" }
  13448. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13449. Exit;
  13450. DoNotMerge := False;
  13451. Shift := taicpu(p).oper[0]^.val;
  13452. LimitSize := taicpu(p).opsize;
  13453. hp1 := p;
  13454. repeat
  13455. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13456. Break;
  13457. { Detect:
  13458. shr x, %reg
  13459. and y, %reg
  13460. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13461. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13462. }
  13463. case taicpu(hp1).opcode of
  13464. A_AND:
  13465. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13466. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13467. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13468. begin
  13469. { Make sure the FLAGS register isn't in use }
  13470. TransferUsedRegs(TmpUsedRegs);
  13471. hp2 := p;
  13472. repeat
  13473. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13474. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13475. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13476. begin
  13477. { Generate the identity mask }
  13478. case taicpu(p).opsize of
  13479. S_B:
  13480. IdentityMask := $FF shr Shift;
  13481. S_W:
  13482. IdentityMask := $FFFF shr Shift;
  13483. S_L:
  13484. IdentityMask := $FFFFFFFF shr Shift;
  13485. {$ifdef x86_64}
  13486. S_Q:
  13487. { We need to force the operands to be unsigned 64-bit
  13488. integers otherwise the wrong value is generated }
  13489. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13490. {$endif x86_64}
  13491. else
  13492. InternalError(2022081501);
  13493. end;
  13494. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13495. begin
  13496. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13497. { All the possible 1 bits are covered, so we can remove the AND }
  13498. hp2 := tai(hp1.Previous);
  13499. RemoveInstruction(hp1);
  13500. { p wasn't actually changed, so don't set Result to True,
  13501. but a change was nonetheless made elsewhere }
  13502. Include(OptsToCheck, aoc_ForceNewIteration);
  13503. { Do another pass in case other AND or MOVZX instructions
  13504. follow }
  13505. hp1 := hp2;
  13506. Continue;
  13507. end;
  13508. end;
  13509. end;
  13510. A_TEST, A_CMP, A_Jcc:
  13511. { Skip over conditional jumps and relevant comparisons }
  13512. Continue;
  13513. A_MOVZX:
  13514. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13515. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13516. begin
  13517. { Since the original register is being read as is, subsequent
  13518. SHRs must not be merged at this point }
  13519. DoNotMerge := True;
  13520. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13521. begin
  13522. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13523. begin
  13524. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13525. { All the possible 1 bits are covered, so we can remove the AND }
  13526. hp2 := tai(hp1.Previous);
  13527. RemoveInstruction(hp1);
  13528. hp1 := hp2;
  13529. end
  13530. else { Different register target }
  13531. begin
  13532. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13533. taicpu(hp1).opcode := A_MOV;
  13534. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13535. case taicpu(hp1).opsize of
  13536. S_BW:
  13537. taicpu(hp1).opsize := S_W;
  13538. S_BL, S_WL:
  13539. taicpu(hp1).opsize := S_L;
  13540. else
  13541. InternalError(2022081503);
  13542. end;
  13543. end;
  13544. end
  13545. else if (Shift > 0) and
  13546. (taicpu(p).opsize = S_W) and
  13547. (taicpu(hp1).opsize = S_WL) and
  13548. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13549. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13550. begin
  13551. { Detect:
  13552. shr x, %ax (x > 0)
  13553. ...
  13554. movzwl %ax,%eax
  13555. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13556. }
  13557. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13558. taicpu(hp1).opcode := A_CWDE;
  13559. taicpu(hp1).clearop(0);
  13560. taicpu(hp1).clearop(1);
  13561. taicpu(hp1).ops := 0;
  13562. end;
  13563. { Move onto the next instruction }
  13564. Continue;
  13565. end;
  13566. A_SHL, A_SAL, A_SHR:
  13567. if (taicpu(hp1).opsize <= LimitSize) and
  13568. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13569. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13570. begin
  13571. { Make sure the sizes don't exceed the register size limit
  13572. (measured by the shift value falling below the limit) }
  13573. if taicpu(hp1).opsize < LimitSize then
  13574. LimitSize := taicpu(hp1).opsize;
  13575. if taicpu(hp1).opcode = A_SHR then
  13576. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13577. else
  13578. begin
  13579. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13580. DoNotMerge := True;
  13581. end;
  13582. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13583. Break;
  13584. { Since we've established that the combined shift is within
  13585. limits, we can actually combine the adjacent SHR
  13586. instructions even if they're different sizes }
  13587. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13588. begin
  13589. hp2 := tai(hp1.Previous);
  13590. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13591. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13592. RemoveInstruction(hp1);
  13593. hp1 := hp2;
  13594. end;
  13595. { Move onto the next instruction }
  13596. Continue;
  13597. end;
  13598. else
  13599. ;
  13600. end;
  13601. Break;
  13602. until False;
  13603. { Detect the following (looking backwards):
  13604. shr %cl,%reg
  13605. shr x, %reg
  13606. Swap the two SHR instructions to minimise a pipeline stall.
  13607. }
  13608. if GetLastInstruction(p, hp1) and
  13609. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13610. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13611. { First operand will be %cl }
  13612. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13613. { Just to be sure }
  13614. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13615. begin
  13616. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13617. { Moving the entries this way ensures the register tracking remains correct }
  13618. Asml.Remove(p);
  13619. Asml.InsertBefore(p, hp1);
  13620. p := hp1;
  13621. { Don't set Result to True because the current instruction is now
  13622. "shr %cl,%reg" and there's nothing more we can do with it }
  13623. end;
  13624. end;
  13625. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13626. var
  13627. hp1, hp2: tai;
  13628. Opposite, SecondOpposite: TAsmOp;
  13629. NewCond: TAsmCond;
  13630. begin
  13631. Result := False;
  13632. { Change:
  13633. add/sub 128,(dest)
  13634. To:
  13635. sub/add -128,(dest)
  13636. This generaally takes fewer bytes to encode because -128 can be stored
  13637. in a signed byte, whereas +128 cannot.
  13638. }
  13639. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13640. begin
  13641. if taicpu(p).opcode = A_ADD then
  13642. Opposite := A_SUB
  13643. else
  13644. Opposite := A_ADD;
  13645. { Be careful if the flags are in use, because the CF flag inverts
  13646. when changing from ADD to SUB and vice versa }
  13647. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13648. GetNextInstruction(p, hp1) then
  13649. begin
  13650. TransferUsedRegs(TmpUsedRegs);
  13651. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13652. hp2 := hp1;
  13653. { Scan ahead to check if everything's safe }
  13654. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13655. begin
  13656. if (hp1.typ <> ait_instruction) then
  13657. { Probably unsafe since the flags are still in use }
  13658. Exit;
  13659. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13660. { Stop searching at an unconditional jump }
  13661. Break;
  13662. if not
  13663. (
  13664. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13665. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13666. ) and
  13667. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13668. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13669. Exit;
  13670. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13671. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13672. { Move to the next instruction }
  13673. GetNextInstruction(hp1, hp1);
  13674. end;
  13675. while Assigned(hp2) and (hp2 <> hp1) do
  13676. begin
  13677. NewCond := C_None;
  13678. case taicpu(hp2).condition of
  13679. C_A, C_NBE:
  13680. NewCond := C_BE;
  13681. C_B, C_C, C_NAE:
  13682. NewCond := C_AE;
  13683. C_AE, C_NB, C_NC:
  13684. NewCond := C_B;
  13685. C_BE, C_NA:
  13686. NewCond := C_A;
  13687. else
  13688. { No change needed };
  13689. end;
  13690. if NewCond <> C_None then
  13691. begin
  13692. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13693. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13694. taicpu(hp2).condition := NewCond;
  13695. end
  13696. else
  13697. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13698. begin
  13699. { Because of the flipping of the carry bit, to ensure
  13700. the operation remains equivalent, ADC becomes SBB
  13701. and vice versa, and the constant is not-inverted.
  13702. If multiple ADCs or SBBs appear in a row, each one
  13703. changed causes the carry bit to invert, so they all
  13704. need to be flipped }
  13705. if taicpu(hp2).opcode = A_ADC then
  13706. SecondOpposite := A_SBB
  13707. else
  13708. SecondOpposite := A_ADC;
  13709. if taicpu(hp2).oper[0]^.typ <> top_const then
  13710. { Should have broken out of this optimisation already }
  13711. InternalError(2021112901);
  13712. 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]^) + ' -> ' +
  13713. 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);
  13714. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13715. taicpu(hp2).opcode := SecondOpposite;
  13716. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13717. end;
  13718. { Move to the next instruction }
  13719. GetNextInstruction(hp2, hp2);
  13720. end;
  13721. if (hp2 <> hp1) then
  13722. InternalError(2021111501);
  13723. end;
  13724. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13725. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13726. taicpu(p).opcode := Opposite;
  13727. taicpu(p).oper[0]^.val := -128;
  13728. { No further optimisations can be made on this instruction, so move
  13729. onto the next one to save time }
  13730. p := tai(p.Next);
  13731. UpdateUsedRegs(p);
  13732. Result := True;
  13733. Exit;
  13734. end;
  13735. { Detect:
  13736. add/sub %reg2,(dest)
  13737. add/sub x, (dest)
  13738. (dest can be a register or a reference)
  13739. Swap the instructions to minimise a pipeline stall. This reverses the
  13740. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13741. optimisations could be made.
  13742. }
  13743. if (taicpu(p).oper[0]^.typ = top_reg) and
  13744. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13745. (
  13746. (
  13747. (taicpu(p).oper[1]^.typ = top_reg) and
  13748. { We can try searching further ahead if we're writing to a register }
  13749. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13750. ) or
  13751. (
  13752. (taicpu(p).oper[1]^.typ = top_ref) and
  13753. GetNextInstruction(p, hp1)
  13754. )
  13755. ) and
  13756. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13757. (taicpu(hp1).oper[0]^.typ = top_const) and
  13758. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13759. begin
  13760. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13761. TransferUsedRegs(TmpUsedRegs);
  13762. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13763. hp2 := p;
  13764. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13765. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13766. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13767. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13768. begin
  13769. asml.remove(hp1);
  13770. asml.InsertBefore(hp1, p);
  13771. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13772. Result := True;
  13773. end;
  13774. end;
  13775. end;
  13776. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13777. var
  13778. hp1: tai;
  13779. begin
  13780. Result:=false;
  13781. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  13782. while GetNextInstruction(p, hp1) and
  13783. TrySwapMovCmp(p, hp1) do
  13784. begin
  13785. if MatchInstruction(hp1, A_MOV, []) then
  13786. begin
  13787. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13788. begin
  13789. { A little hacky, but since CMP doesn't read the flags, only
  13790. modify them, it's safe if they get scrambled by MOV -> XOR }
  13791. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13792. Result := PostPeepholeOptMov(hp1);
  13793. {$ifdef x86_64}
  13794. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13795. { Used to shrink instruction size }
  13796. PostPeepholeOptXor(hp1);
  13797. {$endif x86_64}
  13798. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13799. end
  13800. else
  13801. begin
  13802. Result := PostPeepholeOptMov(hp1);
  13803. {$ifdef x86_64}
  13804. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13805. { Used to shrink instruction size }
  13806. PostPeepholeOptXor(hp1);
  13807. {$endif x86_64}
  13808. end;
  13809. end;
  13810. { Enabling this flag is actually a null operation, but it marks
  13811. the code as 'modified' during this pass }
  13812. Include(OptsToCheck, aoc_ForceNewIteration);
  13813. end;
  13814. { change "cmp $0, %reg" to "test %reg, %reg" }
  13815. if MatchOpType(taicpu(p),top_const,top_reg) and
  13816. (taicpu(p).oper[0]^.val = 0) then
  13817. begin
  13818. taicpu(p).opcode := A_TEST;
  13819. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  13820. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  13821. Result:=true;
  13822. end;
  13823. end;
  13824. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  13825. var
  13826. IsTestConstX, IsValid : Boolean;
  13827. hp1,hp2 : tai;
  13828. begin
  13829. Result:=false;
  13830. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  13831. if (taicpu(p).opcode = A_TEST) then
  13832. while GetNextInstruction(p, hp1) and
  13833. TrySwapMovCmp(p, hp1) do
  13834. begin
  13835. if MatchInstruction(hp1, A_MOV, []) then
  13836. begin
  13837. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13838. begin
  13839. { A little hacky, but since TEST doesn't read the flags, only
  13840. modify them, it's safe if they get scrambled by MOV -> XOR }
  13841. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13842. Result := PostPeepholeOptMov(hp1);
  13843. {$ifdef x86_64}
  13844. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13845. { Used to shrink instruction size }
  13846. PostPeepholeOptXor(hp1);
  13847. {$endif x86_64}
  13848. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13849. end
  13850. else
  13851. begin
  13852. Result := PostPeepholeOptMov(hp1);
  13853. {$ifdef x86_64}
  13854. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13855. { Used to shrink instruction size }
  13856. PostPeepholeOptXor(hp1);
  13857. {$endif x86_64}
  13858. end;
  13859. end;
  13860. { Enabling this flag is actually a null operation, but it marks
  13861. the code as 'modified' during this pass }
  13862. Include(OptsToCheck, aoc_ForceNewIteration);
  13863. end;
  13864. { If x is a power of 2 (popcnt = 1), change:
  13865. or $x, %reg/ref
  13866. To:
  13867. bts lb(x), %reg/ref
  13868. }
  13869. if (taicpu(p).opcode = A_OR) and
  13870. IsBTXAcceptable(p) and
  13871. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  13872. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13873. (
  13874. { Don't optimise if a test instruction follows }
  13875. not GetNextInstruction(p, hp1) or
  13876. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  13877. ) then
  13878. begin
  13879. 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);
  13880. taicpu(p).opcode := A_BTS;
  13881. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13882. Result := True;
  13883. Exit;
  13884. end;
  13885. { If x is a power of 2 (popcnt = 1), change:
  13886. test $x, %reg/ref
  13887. je / sete / cmove (or jne / setne)
  13888. To:
  13889. bt lb(x), %reg/ref
  13890. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  13891. }
  13892. if (taicpu(p).opcode = A_TEST) and
  13893. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  13894. (taicpu(p).oper[0]^.typ = top_const) and
  13895. (
  13896. (cs_opt_size in current_settings.optimizerswitches) or
  13897. (
  13898. (taicpu(p).oper[1]^.typ = top_reg) and
  13899. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13900. ) or
  13901. (
  13902. (taicpu(p).oper[1]^.typ <> top_reg) and
  13903. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13904. )
  13905. ) and
  13906. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13907. { For sizes less than S_L, the byte size is equal or larger with BT,
  13908. so don't bother optimising }
  13909. (taicpu(p).opsize >= S_L) then
  13910. begin
  13911. IsValid := True;
  13912. { Check the next set of instructions, watching the FLAGS register
  13913. and the conditions used }
  13914. TransferUsedRegs(TmpUsedRegs);
  13915. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13916. hp1 := p;
  13917. hp2 := nil;
  13918. while GetNextInstruction(hp1, hp1) do
  13919. begin
  13920. if not Assigned(hp2) then
  13921. { The first instruction after TEST }
  13922. hp2 := hp1;
  13923. if (hp1.typ <> ait_instruction) then
  13924. begin
  13925. { If the flags are no longer in use, everything is fine }
  13926. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13927. IsValid := False;
  13928. Break;
  13929. end;
  13930. case taicpu(hp1).condition of
  13931. C_None:
  13932. begin
  13933. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13934. { Something is not quite normal, so play safe and don't change }
  13935. IsValid := False;
  13936. Break;
  13937. end;
  13938. C_E, C_Z, C_NE, C_NZ:
  13939. { This is fine };
  13940. else
  13941. begin
  13942. { Unsupported condition }
  13943. IsValid := False;
  13944. Break;
  13945. end;
  13946. end;
  13947. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13948. end;
  13949. if IsValid then
  13950. begin
  13951. while hp2 <> hp1 do
  13952. begin
  13953. case taicpu(hp2).condition of
  13954. C_Z, C_E:
  13955. taicpu(hp2).condition := C_NC;
  13956. C_NZ, C_NE:
  13957. taicpu(hp2).condition := C_C;
  13958. else
  13959. { Should not get this by this point }
  13960. InternalError(2022110701);
  13961. end;
  13962. GetNextInstruction(hp2, hp2);
  13963. end;
  13964. 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);
  13965. taicpu(p).opcode := A_BT;
  13966. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13967. Result := True;
  13968. Exit;
  13969. end;
  13970. end;
  13971. { removes the line marked with (x) from the sequence
  13972. and/or/xor/add/sub/... $x, %y
  13973. test/or %y, %y | test $-1, %y (x)
  13974. j(n)z _Label
  13975. as the first instruction already adjusts the ZF
  13976. %y operand may also be a reference }
  13977. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  13978. MatchOperand(taicpu(p).oper[0]^,-1);
  13979. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  13980. GetLastInstruction(p, hp1) and
  13981. (tai(hp1).typ = ait_instruction) and
  13982. GetNextInstruction(p,hp2) and
  13983. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  13984. case taicpu(hp1).opcode Of
  13985. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  13986. { These two instructions set the zero flag if the result is zero }
  13987. A_POPCNT, A_LZCNT:
  13988. begin
  13989. if (
  13990. { With POPCNT, an input of zero will set the zero flag
  13991. because the population count of zero is zero }
  13992. (taicpu(hp1).opcode = A_POPCNT) and
  13993. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  13994. (
  13995. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  13996. { Faster than going through the second half of the 'or'
  13997. condition below }
  13998. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  13999. )
  14000. ) or (
  14001. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14002. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14003. { and in case of carry for A(E)/B(E)/C/NC }
  14004. (
  14005. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14006. (
  14007. (taicpu(hp1).opcode <> A_ADD) and
  14008. (taicpu(hp1).opcode <> A_SUB) and
  14009. (taicpu(hp1).opcode <> A_LZCNT)
  14010. )
  14011. )
  14012. ) then
  14013. begin
  14014. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14015. RemoveCurrentP(p, hp2);
  14016. Result:=true;
  14017. Exit;
  14018. end;
  14019. end;
  14020. A_SHL, A_SAL, A_SHR, A_SAR:
  14021. begin
  14022. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14023. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14024. { therefore, it's only safe to do this optimization for }
  14025. { shifts by a (nonzero) constant }
  14026. (taicpu(hp1).oper[0]^.typ = top_const) and
  14027. (taicpu(hp1).oper[0]^.val <> 0) and
  14028. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14029. { and in case of carry for A(E)/B(E)/C/NC }
  14030. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14031. begin
  14032. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14033. RemoveCurrentP(p, hp2);
  14034. Result:=true;
  14035. Exit;
  14036. end;
  14037. end;
  14038. A_DEC, A_INC, A_NEG:
  14039. begin
  14040. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14041. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14042. { and in case of carry for A(E)/B(E)/C/NC }
  14043. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14044. begin
  14045. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14046. RemoveCurrentP(p, hp2);
  14047. Result:=true;
  14048. Exit;
  14049. end;
  14050. end;
  14051. A_ANDN, A_BZHI:
  14052. begin
  14053. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14054. { Only the zero and sign flags are consistent with what the result is }
  14055. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14056. begin
  14057. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14058. RemoveCurrentP(p, hp2);
  14059. Result:=true;
  14060. Exit;
  14061. end;
  14062. end;
  14063. A_BEXTR:
  14064. begin
  14065. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14066. { Only the zero flag is set }
  14067. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14068. begin
  14069. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14070. RemoveCurrentP(p, hp2);
  14071. Result:=true;
  14072. Exit;
  14073. end;
  14074. end;
  14075. else
  14076. ;
  14077. end; { case }
  14078. { change "test $-1,%reg" into "test %reg,%reg" }
  14079. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14080. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14081. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14082. if MatchInstruction(p, A_OR, []) and
  14083. { Can only match if they're both registers }
  14084. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14085. begin
  14086. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14087. taicpu(p).opcode := A_TEST;
  14088. { No need to set Result to True, as we've done all the optimisations we can }
  14089. end;
  14090. end;
  14091. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14092. var
  14093. hp1,hp3 : tai;
  14094. {$ifndef x86_64}
  14095. hp2 : taicpu;
  14096. {$endif x86_64}
  14097. begin
  14098. Result:=false;
  14099. hp3:=nil;
  14100. {$ifndef x86_64}
  14101. { don't do this on modern CPUs, this really hurts them due to
  14102. broken call/ret pairing }
  14103. if (current_settings.optimizecputype < cpu_Pentium2) and
  14104. not(cs_create_pic in current_settings.moduleswitches) and
  14105. GetNextInstruction(p, hp1) and
  14106. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14107. MatchOpType(taicpu(hp1),top_ref) and
  14108. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14109. begin
  14110. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14111. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14112. InsertLLItem(p.previous, p, hp2);
  14113. taicpu(p).opcode := A_JMP;
  14114. taicpu(p).is_jmp := true;
  14115. RemoveInstruction(hp1);
  14116. Result:=true;
  14117. end
  14118. else
  14119. {$endif x86_64}
  14120. { replace
  14121. call procname
  14122. ret
  14123. by
  14124. jmp procname
  14125. but do it only on level 4 because it destroys stack back traces
  14126. else if the subroutine is marked as no return, remove the ret
  14127. }
  14128. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14129. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14130. GetNextInstruction(p, hp1) and
  14131. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14132. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14133. SetAndTest(hp1,hp3) and
  14134. GetNextInstruction(hp1,hp1) and
  14135. MatchInstruction(hp1,A_RET,[S_NO])
  14136. )
  14137. ) and
  14138. (taicpu(hp1).ops=0) then
  14139. begin
  14140. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14141. { we might destroy stack alignment here if we do not do a call }
  14142. (target_info.stackalign<=sizeof(SizeUInt)) then
  14143. begin
  14144. taicpu(p).opcode := A_JMP;
  14145. taicpu(p).is_jmp := true;
  14146. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14147. end
  14148. else
  14149. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14150. RemoveInstruction(hp1);
  14151. if Assigned(hp3) then
  14152. begin
  14153. AsmL.Remove(hp3);
  14154. AsmL.InsertBefore(hp3,p)
  14155. end;
  14156. Result:=true;
  14157. end;
  14158. end;
  14159. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14160. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14161. begin
  14162. case OpSize of
  14163. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14164. Result := (Val <= $FF) and (Val >= -128);
  14165. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14166. Result := (Val <= $FFFF) and (Val >= -32768);
  14167. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14168. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14169. else
  14170. Result := True;
  14171. end;
  14172. end;
  14173. var
  14174. hp1, hp2 : tai;
  14175. SizeChange: Boolean;
  14176. PreMessage: string;
  14177. begin
  14178. Result := False;
  14179. if (taicpu(p).oper[0]^.typ = top_reg) and
  14180. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14181. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14182. begin
  14183. { Change (using movzbl %al,%eax as an example):
  14184. movzbl %al, %eax movzbl %al, %eax
  14185. cmpl x, %eax testl %eax,%eax
  14186. To:
  14187. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14188. movzbl %al, %eax movzbl %al, %eax
  14189. Smaller instruction and minimises pipeline stall as the CPU
  14190. doesn't have to wait for the register to get zero-extended. [Kit]
  14191. Also allow if the smaller of the two registers is being checked,
  14192. as this still removes the false dependency.
  14193. }
  14194. if
  14195. (
  14196. (
  14197. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14198. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14199. ) or (
  14200. { If MatchOperand returns True, they must both be registers }
  14201. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14202. )
  14203. ) and
  14204. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14205. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14206. begin
  14207. 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);
  14208. asml.Remove(hp1);
  14209. asml.InsertBefore(hp1, p);
  14210. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14211. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14212. begin
  14213. taicpu(hp1).opcode := A_TEST;
  14214. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14215. end;
  14216. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14217. case taicpu(p).opsize of
  14218. S_BW, S_BL:
  14219. begin
  14220. SizeChange := taicpu(hp1).opsize <> S_B;
  14221. taicpu(hp1).changeopsize(S_B);
  14222. end;
  14223. S_WL:
  14224. begin
  14225. SizeChange := taicpu(hp1).opsize <> S_W;
  14226. taicpu(hp1).changeopsize(S_W);
  14227. end
  14228. else
  14229. InternalError(2020112701);
  14230. end;
  14231. UpdateUsedRegs(tai(p.Next));
  14232. { Check if the register is used aferwards - if not, we can
  14233. remove the movzx instruction completely }
  14234. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14235. begin
  14236. { Hp1 is a better position than p for debugging purposes }
  14237. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14238. RemoveCurrentp(p, hp1);
  14239. Result := True;
  14240. end;
  14241. if SizeChange then
  14242. DebugMsg(SPeepholeOptimization + PreMessage +
  14243. 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)
  14244. else
  14245. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14246. Exit;
  14247. end;
  14248. { Change (using movzwl %ax,%eax as an example):
  14249. movzwl %ax, %eax
  14250. movb %al, (dest) (Register is smaller than read register in movz)
  14251. To:
  14252. movb %al, (dest) (Move one back to avoid a false dependency)
  14253. movzwl %ax, %eax
  14254. }
  14255. if (taicpu(hp1).opcode = A_MOV) and
  14256. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14257. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14258. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14259. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14260. begin
  14261. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14262. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14263. asml.Remove(hp1);
  14264. asml.InsertBefore(hp1, p);
  14265. if taicpu(hp1).oper[1]^.typ = top_reg then
  14266. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14267. { Check if the register is used aferwards - if not, we can
  14268. remove the movzx instruction completely }
  14269. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14270. begin
  14271. { Hp1 is a better position than p for debugging purposes }
  14272. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14273. RemoveCurrentp(p, hp1);
  14274. Result := True;
  14275. end;
  14276. Exit;
  14277. end;
  14278. end;
  14279. end;
  14280. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14281. var
  14282. hp1: tai;
  14283. {$ifdef x86_64}
  14284. PreMessage, RegName: string;
  14285. {$endif x86_64}
  14286. begin
  14287. Result := False;
  14288. { If x is a power of 2 (popcnt = 1), change:
  14289. xor $x, %reg/ref
  14290. To:
  14291. btc lb(x), %reg/ref
  14292. }
  14293. if IsBTXAcceptable(p) and
  14294. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14295. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14296. (
  14297. { Don't optimise if a test instruction follows }
  14298. not GetNextInstruction(p, hp1) or
  14299. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14300. ) then
  14301. begin
  14302. 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);
  14303. taicpu(p).opcode := A_BTC;
  14304. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14305. Result := True;
  14306. Exit;
  14307. end;
  14308. {$ifdef x86_64}
  14309. { Code size reduction by J. Gareth "Kit" Moreton }
  14310. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14311. as this removes the REX prefix }
  14312. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14313. Exit;
  14314. if taicpu(p).oper[0]^.typ <> top_reg then
  14315. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14316. InternalError(2018011500);
  14317. case taicpu(p).opsize of
  14318. S_Q:
  14319. begin
  14320. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14321. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14322. { The actual optimization }
  14323. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14324. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14325. taicpu(p).changeopsize(S_L);
  14326. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14327. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14328. end;
  14329. else
  14330. ;
  14331. end;
  14332. {$endif x86_64}
  14333. end;
  14334. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14335. var
  14336. XReg: TRegister;
  14337. begin
  14338. Result := False;
  14339. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14340. Smaller encoding and slightly faster on some platforms (also works for
  14341. ZMM-sized registers) }
  14342. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14343. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14344. begin
  14345. XReg := taicpu(p).oper[0]^.reg;
  14346. if (taicpu(p).oper[1]^.reg = XReg) then
  14347. begin
  14348. taicpu(p).changeopsize(S_XMM);
  14349. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14350. if (cs_opt_size in current_settings.optimizerswitches) then
  14351. begin
  14352. { Change input registers to %xmm0 to reduce size. Note that
  14353. there's a risk of a false dependency doing this, so only
  14354. optimise for size here }
  14355. XReg := NR_XMM0;
  14356. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14357. end
  14358. else
  14359. begin
  14360. setsubreg(XReg, R_SUBMMX);
  14361. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14362. end;
  14363. taicpu(p).oper[0]^.reg := XReg;
  14364. taicpu(p).oper[1]^.reg := XReg;
  14365. Result := True;
  14366. end;
  14367. end;
  14368. end;
  14369. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14370. var
  14371. OperIdx: Integer;
  14372. begin
  14373. for OperIdx := 0 to p.ops - 1 do
  14374. if p.oper[OperIdx]^.typ = top_ref then
  14375. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14376. end;
  14377. end.