aoptx86.pas 772 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration,
  34. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. { returns true if any of the registers in ref are modified by any
  73. instruction between p1 and p2, or if those instructions write to the
  74. reference }
  75. function RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  76. private
  77. function SkipSimpleInstructions(var hp1: tai): Boolean;
  78. protected
  79. class function IsMOVZXAcceptable: Boolean; static; inline;
  80. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  81. { Attempts to allocate a volatile integer register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { Attempts to allocate a volatile MM register for use between p and hp,
  86. using AUsedRegs for the current register usage information. Returns NR_NO
  87. if no free register could be found }
  88. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  89. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  90. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  91. { checks whether reading the value in reg1 depends on the value of reg2. This
  92. is very similar to SuperRegisterEquals, except it takes into account that
  93. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  94. depend on the value in AH). }
  95. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  96. { Replaces all references to AOldReg in a memory reference to ANewReg }
  97. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Replaces all references to AOldReg in an operand to ANewReg }
  99. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  100. { Replaces all references to AOldReg in an instruction to ANewReg,
  101. except where the register is being written }
  102. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  103. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  104. or writes to a global symbol }
  105. class function IsRefSafe(const ref: PReference): Boolean; static;
  106. { Returns true if the given MOV instruction can be safely converted to CMOV }
  107. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  108. { Like UpdateUsedRegs, but ignores deallocations }
  109. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  110. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  111. class function IsBTXAcceptable(p : tai) : boolean; static;
  112. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  113. conversion was successful }
  114. function ConvertLEA(const p : taicpu): Boolean;
  115. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  116. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  117. {$ifdef x86_64}
  118. { If a "mov %reg1d,%reg2d; and %reg1d,%reg1d" is found, we can possibly
  119. replace %reg2q with %reg1q in later instructions }
  120. function DoZeroUpper32Opt(var mov_p: tai; var and_p: tai): Boolean;
  121. {$endif x86_64}
  122. procedure DebugMsg(const s : string; p : tai);inline;
  123. class function IsExitCode(p : tai) : boolean; static;
  124. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  125. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  126. procedure RemoveLastDeallocForFuncRes(p : tai);
  127. function DoArithCombineOpt(var p : tai) : Boolean;
  128. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  129. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  130. function HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  131. function PrePeepholeOptSxx(var p : tai) : boolean;
  132. function PrePeepholeOptIMUL(var p : tai) : boolean;
  133. function PrePeepholeOptAND(var p : tai) : boolean;
  134. function OptPass1Test(var p: tai): boolean;
  135. function OptPass1Add(var p: tai): boolean;
  136. function OptPass1AND(var p : tai) : boolean;
  137. function OptPass1CMOVcc(var p: tai): Boolean;
  138. function OptPass1_V_MOVAP(var p : tai) : boolean;
  139. function OptPass1VOP(var p : tai) : boolean;
  140. function OptPass1MOV(var p : tai) : boolean;
  141. function OptPass1MOVD(var p : tai) : boolean;
  142. function OptPass1Movx(var p : tai) : boolean;
  143. function OptPass1MOVXX(var p : tai) : boolean;
  144. function OptPass1OP(var p : tai) : boolean;
  145. function OptPass1LEA(var p : tai) : boolean;
  146. function OptPass1Sub(var p : tai) : boolean;
  147. function OptPass1SHLSAL(var p : tai) : boolean;
  148. function OptPass1SHR(var p : tai) : boolean;
  149. function OptPass1FSTP(var p : tai) : boolean;
  150. function OptPass1FLD(var p : tai) : boolean;
  151. function OptPass1Cmp(var p : tai) : boolean;
  152. function OptPass1PXor(var p : tai) : boolean;
  153. function OptPass1VPXor(var p: tai): boolean;
  154. function OptPass1Imul(var p : tai) : boolean;
  155. function OptPass1Jcc(var p : tai) : boolean;
  156. function OptPass1SHXX(var p: tai): boolean;
  157. function OptPass1VMOVDQ(var p: tai): Boolean;
  158. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  159. function OptPass1STCCLC(var p: tai): Boolean;
  160. function OptPass2STCCLC(var p: tai): Boolean;
  161. function OptPass2CMOVcc(var p: tai): Boolean;
  162. function OptPass2Movx(var p : tai): Boolean;
  163. function OptPass2MOV(var p : tai) : boolean;
  164. function OptPass2Imul(var p : tai) : boolean;
  165. function OptPass2Jmp(var p : tai) : boolean;
  166. function OptPass2Jcc(var p : tai) : boolean;
  167. function OptPass2Lea(var p: tai): Boolean;
  168. function OptPass2SUB(var p: tai): Boolean;
  169. function OptPass2ADD(var p : tai): Boolean;
  170. function OptPass2SETcc(var p : tai) : boolean;
  171. function OptPass2Cmp(var p: tai): Boolean;
  172. function OptPass2Test(var p: tai): Boolean;
  173. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  174. function PostPeepholeOptMov(var p : tai) : Boolean;
  175. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  176. function PostPeepholeOptXor(var p : tai) : Boolean;
  177. function PostPeepholeOptAnd(var p : tai) : boolean;
  178. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  179. function PostPeepholeOptCmp(var p : tai) : Boolean;
  180. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  181. function PostPeepholeOptCall(var p : tai) : Boolean;
  182. function PostPeepholeOptLea(var p : tai) : Boolean;
  183. function PostPeepholeOptPush(var p: tai): Boolean;
  184. function PostPeepholeOptShr(var p : tai) : boolean;
  185. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  186. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  187. function PostPeepholeOptRET(var p: tai): Boolean;
  188. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  189. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  190. function TrySwapMovOp(var p, hp1: tai): Boolean;
  191. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  192. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  193. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  194. { Processor-dependent reference optimisation }
  195. class procedure OptimizeRefs(var p: taicpu); static;
  196. end;
  197. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  198. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  199. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  200. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  201. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  202. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  203. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  204. {$if max_operands>2}
  205. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  206. {$endif max_operands>2}
  207. function RefsEqual(const r1, r2: treference): boolean;
  208. { Like RefsEqual, but doesn't compare the offsets }
  209. function RefsAlmostEqual(const r1, r2: treference): boolean;
  210. { Note that Result is set to True if the references COULD overlap but the
  211. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  212. might still overlap because %reg2 could be equal to %reg1-4 }
  213. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  214. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  215. { returns true, if ref is a reference using only the registers passed as base and index
  216. and having an offset }
  217. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  218. implementation
  219. uses
  220. cutils,verbose,
  221. systems,
  222. globals,
  223. cpuinfo,
  224. procinfo,
  225. paramgr,
  226. aasmbase,
  227. aoptbase,aoptutils,
  228. symconst,symsym,
  229. cgx86,
  230. itcpugas;
  231. {$ifndef 8086}
  232. const
  233. MAX_CMOV_INSTRUCTIONS = 4;
  234. MAX_CMOV_REGISTERS = 8;
  235. type
  236. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  237. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  238. tsProcessed);
  239. { For OptPass2Jcc }
  240. TCMOVTracking = object
  241. private
  242. CMOVScore, ConstCount: LongInt;
  243. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  244. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  245. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  246. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  247. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  248. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  249. fOptimizer: TX86AsmOptimizer;
  250. fLabel: TAsmSymbol;
  251. fInsertionPoint,
  252. fCondition,
  253. fInitialJump,
  254. fFirstMovBlock,
  255. fFirstMovBlockStop,
  256. fSecondJump,
  257. fThirdJump,
  258. fSecondMovBlock,
  259. fSecondMovBlockStop,
  260. fMidLabel,
  261. fEndLabel,
  262. fAllocationRange: tai;
  263. fState: TCMovTrackingState;
  264. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  265. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  266. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  267. public
  268. RegisterTracking: TAllUsedRegs;
  269. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  270. destructor Done;
  271. procedure Process(out new_p: tai);
  272. property State: TCMovTrackingState read fState;
  273. end;
  274. PCMOVTracking = ^TCMOVTracking;
  275. {$endif 8086}
  276. {$ifdef DEBUG_AOPTCPU}
  277. const
  278. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  279. {$else DEBUG_AOPTCPU}
  280. { Empty strings help the optimizer to remove string concatenations that won't
  281. ever appear to the user on release builds. [Kit] }
  282. const
  283. SPeepholeOptimization = '';
  284. {$endif DEBUG_AOPTCPU}
  285. LIST_STEP_SIZE = 4;
  286. type
  287. TJumpTrackingItem = class(TLinkedListItem)
  288. private
  289. FSymbol: TAsmSymbol;
  290. FRefs: LongInt;
  291. public
  292. constructor Create(ASymbol: TAsmSymbol);
  293. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  294. property Symbol: TAsmSymbol read FSymbol;
  295. property Refs: LongInt read FRefs;
  296. end;
  297. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  298. begin
  299. inherited Create;
  300. FSymbol := ASymbol;
  301. FRefs := 0;
  302. end;
  303. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  304. begin
  305. Inc(FRefs);
  306. end;
  307. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  308. begin
  309. result :=
  310. (instr.typ = ait_instruction) and
  311. (taicpu(instr).opcode = op) and
  312. ((opsize = []) or (taicpu(instr).opsize in opsize));
  313. end;
  314. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  315. begin
  316. result :=
  317. (instr.typ = ait_instruction) and
  318. ((taicpu(instr).opcode = op1) or
  319. (taicpu(instr).opcode = op2)
  320. ) and
  321. ((opsize = []) or (taicpu(instr).opsize in opsize));
  322. end;
  323. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  324. begin
  325. result :=
  326. (instr.typ = ait_instruction) and
  327. ((taicpu(instr).opcode = op1) or
  328. (taicpu(instr).opcode = op2) or
  329. (taicpu(instr).opcode = op3)
  330. ) and
  331. ((opsize = []) or (taicpu(instr).opsize in opsize));
  332. end;
  333. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  334. const opsize : topsizes) : boolean;
  335. var
  336. op : TAsmOp;
  337. begin
  338. result:=false;
  339. if (instr.typ <> ait_instruction) or
  340. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  341. exit;
  342. for op in ops do
  343. begin
  344. if taicpu(instr).opcode = op then
  345. begin
  346. result:=true;
  347. exit;
  348. end;
  349. end;
  350. end;
  351. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  352. begin
  353. result := (oper.typ = top_reg) and (oper.reg = reg);
  354. end;
  355. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  356. begin
  357. result := (oper.typ = top_const) and (oper.val = a);
  358. end;
  359. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  360. begin
  361. result := oper1.typ = oper2.typ;
  362. if result then
  363. case oper1.typ of
  364. top_const:
  365. Result:=oper1.val = oper2.val;
  366. top_reg:
  367. Result:=oper1.reg = oper2.reg;
  368. top_ref:
  369. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  370. else
  371. internalerror(2013102801);
  372. end
  373. end;
  374. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  375. begin
  376. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  377. if result then
  378. case oper1.typ of
  379. top_const:
  380. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  381. top_reg:
  382. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  383. top_ref:
  384. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  385. else
  386. internalerror(2020052401);
  387. end
  388. end;
  389. function RefsEqual(const r1, r2: treference): boolean;
  390. begin
  391. RefsEqual :=
  392. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  393. (r1.relsymbol = r2.relsymbol) and
  394. (r1.segment = r2.segment) and (r1.base = r2.base) and
  395. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  396. (r1.offset = r2.offset) and
  397. (r1.volatility + r2.volatility = []);
  398. end;
  399. function RefsAlmostEqual(const r1, r2: treference): boolean;
  400. begin
  401. RefsAlmostEqual :=
  402. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  403. (r1.relsymbol = r2.relsymbol) and
  404. (r1.segment = r2.segment) and (r1.base = r2.base) and
  405. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  406. { Don't compare the offsets }
  407. (r1.volatility + r2.volatility = []);
  408. end;
  409. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  410. begin
  411. if (r1.symbol<>r2.symbol) then
  412. { If the index registers are different, there's a chance one could
  413. be set so it equals the other symbol }
  414. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  415. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  416. (r1.relsymbol = r2.relsymbol) and
  417. (r1.segment = r2.segment) and (r1.base = r2.base) and
  418. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  419. (r1.volatility + r2.volatility = []) then
  420. { In this case, it all depends on the offsets }
  421. Exit(abs(r1.offset - r2.offset) < Range);
  422. { There's a chance things MIGHT overlap, so take no chances }
  423. Result := True;
  424. end;
  425. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  426. begin
  427. Result:=(ref.offset=0) and
  428. (ref.scalefactor in [0,1]) and
  429. (ref.segment=NR_NO) and
  430. (ref.symbol=nil) and
  431. (ref.relsymbol=nil) and
  432. ((base=NR_INVALID) or
  433. (ref.base=base)) and
  434. ((index=NR_INVALID) or
  435. (ref.index=index)) and
  436. (ref.volatility=[]);
  437. end;
  438. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  439. begin
  440. Result:=(ref.scalefactor in [0,1]) and
  441. (ref.segment=NR_NO) and
  442. (ref.symbol=nil) and
  443. (ref.relsymbol=nil) and
  444. ((base=NR_INVALID) or
  445. (ref.base=base)) and
  446. ((index=NR_INVALID) or
  447. (ref.index=index)) and
  448. (ref.volatility=[]);
  449. end;
  450. function InstrReadsFlags(p: tai): boolean;
  451. begin
  452. InstrReadsFlags := true;
  453. case p.typ of
  454. ait_instruction:
  455. if InsProp[taicpu(p).opcode].Ch*
  456. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  457. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  458. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  459. exit;
  460. ait_label:
  461. exit;
  462. else
  463. ;
  464. end;
  465. InstrReadsFlags := false;
  466. end;
  467. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  468. begin
  469. Next:=Current;
  470. repeat
  471. Result:=GetNextInstruction(Next,Next);
  472. until not (Result) or
  473. not(cs_opt_level3 in current_settings.optimizerswitches) or
  474. (Next.typ<>ait_instruction) or
  475. RegInInstruction(reg,Next) or
  476. is_calljmp(taicpu(Next).opcode);
  477. end;
  478. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  479. var
  480. GetNextResult: Boolean;
  481. begin
  482. Result:=0;
  483. Next:=Current;
  484. repeat
  485. GetNextResult := GetNextInstruction(Next,Next);
  486. if GetNextResult then
  487. Inc(Result)
  488. else
  489. { Must return zero upon hitting the end of the linked list without a match }
  490. Result := 0;
  491. until not (GetNextResult) or
  492. not(cs_opt_level3 in current_settings.optimizerswitches) or
  493. (Next.typ<>ait_instruction) or
  494. RegInInstruction(reg,Next) or
  495. is_calljmp(taicpu(Next).opcode);
  496. end;
  497. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  498. procedure TrackJump(Symbol: TAsmSymbol);
  499. var
  500. Search: TJumpTrackingItem;
  501. begin
  502. { See if an entry already exists in our jump tracking list
  503. (faster to search backwards due to the higher chance of
  504. matching destinations) }
  505. Search := TJumpTrackingItem(JumpTracking.Last);
  506. while Assigned(Search) do
  507. begin
  508. if Search.Symbol = Symbol then
  509. begin
  510. { Found it - remove it so it can be pushed to the front }
  511. JumpTracking.Remove(Search);
  512. Break;
  513. end;
  514. Search := TJumpTrackingItem(Search.Previous);
  515. end;
  516. if not Assigned(Search) then
  517. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  518. JumpTracking.Concat(Search);
  519. Search.IncRefs;
  520. end;
  521. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  522. var
  523. Search: TJumpTrackingItem;
  524. begin
  525. Result := False;
  526. { See if this label appears in the tracking list }
  527. Search := TJumpTrackingItem(JumpTracking.Last);
  528. while Assigned(Search) do
  529. begin
  530. if Search.Symbol = Symbol then
  531. begin
  532. { Found it - let's see what we can discover }
  533. if Search.Symbol.getrefs = Search.Refs then
  534. begin
  535. { Success - all the references are accounted for }
  536. JumpTracking.Remove(Search);
  537. Search.Free;
  538. { It is logically impossible for CrossJump to be false here
  539. because we must have run into a conditional jump for
  540. this label at some point }
  541. if not CrossJump then
  542. InternalError(2022041710);
  543. if JumpTracking.First = nil then
  544. { Tracking list is now empty - no more cross jumps }
  545. CrossJump := False;
  546. Result := True;
  547. Exit;
  548. end;
  549. { If the references don't match, it's possible to enter
  550. this label through other means, so drop out }
  551. Exit;
  552. end;
  553. Search := TJumpTrackingItem(Search.Previous);
  554. end;
  555. end;
  556. var
  557. Next_Label: tai;
  558. begin
  559. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  560. Next := Current;
  561. repeat
  562. Result := GetNextInstruction(Next,Next);
  563. if not Result then
  564. Break;
  565. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  566. if is_calljmpuncondret(taicpu(Next).opcode) then
  567. begin
  568. if (taicpu(Next).opcode = A_JMP) and
  569. { Remove dead code now to save time }
  570. RemoveDeadCodeAfterJump(taicpu(Next)) then
  571. { A jump was removed, but not the current instruction, and
  572. Result doesn't necessarily translate into an optimisation
  573. routine's Result, so use the "Force New Iteration" flag so
  574. mark a new pass }
  575. Include(OptsToCheck, aoc_ForceNewIteration);
  576. if not Assigned(JumpTracking) then
  577. begin
  578. { Cross-label optimisations often causes other optimisations
  579. to perform worse because they're not given the chance to
  580. optimise locally. In this case, don't do the cross-label
  581. optimisations yet, but flag them as a potential possibility
  582. for the next iteration of Pass 1 }
  583. if not NotFirstIteration then
  584. Include(OptsToCheck, aoc_ForceNewIteration);
  585. end
  586. else if IsJumpToLabel(taicpu(Next)) and
  587. GetNextInstruction(Next, Next_Label) then
  588. begin
  589. { If we have JMP .lbl, and the label after it has all of its
  590. references tracked, then this is probably an if-else style of
  591. block and we can keep tracking. If the label for this jump
  592. then appears later and is fully tracked, then it's the end
  593. of the if-else blocks and the code paths converge (thus
  594. marking the end of the cross-jump) }
  595. if (Next_Label.typ = ait_label) then
  596. begin
  597. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  598. begin
  599. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  600. Next := Next_Label;
  601. { CrossJump gets set to false by LabelAccountedFor if the
  602. list is completely emptied (as it indicates that all
  603. code paths have converged). We could avoid this nuance
  604. by moving the TrackJump call to before the
  605. LabelAccountedFor call, but this is slower in situations
  606. where LabelAccountedFor would return False due to the
  607. creation of a new object that is not used and destroyed
  608. soon after. }
  609. CrossJump := True;
  610. Continue;
  611. end;
  612. end
  613. else if (Next_Label.typ <> ait_marker) then
  614. { We just did a RemoveDeadCodeAfterJump, so either we find
  615. a label, the end of the procedure or some kind of marker}
  616. InternalError(2022041720);
  617. end;
  618. Result := False;
  619. Exit;
  620. end
  621. else
  622. begin
  623. if not Assigned(JumpTracking) then
  624. begin
  625. { Cross-label optimisations often causes other optimisations
  626. to perform worse because they're not given the chance to
  627. optimise locally. In this case, don't do the cross-label
  628. optimisations yet, but flag them as a potential possibility
  629. for the next iteration of Pass 1 }
  630. if not NotFirstIteration then
  631. Include(OptsToCheck, aoc_ForceNewIteration);
  632. end
  633. else if IsJumpToLabel(taicpu(Next)) then
  634. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  635. else
  636. { Conditional jumps should always be a jump to label }
  637. InternalError(2022041701);
  638. CrossJump := True;
  639. Continue;
  640. end;
  641. if Next.typ = ait_label then
  642. begin
  643. if not Assigned(JumpTracking) then
  644. begin
  645. { Cross-label optimisations often causes other optimisations
  646. to perform worse because they're not given the chance to
  647. optimise locally. In this case, don't do the cross-label
  648. optimisations yet, but flag them as a potential possibility
  649. for the next iteration of Pass 1 }
  650. if not NotFirstIteration then
  651. Include(OptsToCheck, aoc_ForceNewIteration);
  652. end
  653. else if LabelAccountedFor(tai_label(Next).labsym) then
  654. Continue;
  655. { If we reach here, we're at a label that hasn't been seen before
  656. (or JumpTracking was nil) }
  657. Break;
  658. end;
  659. until not Result or
  660. not (cs_opt_level3 in current_settings.optimizerswitches) or
  661. not (Next.typ in [ait_label, ait_instruction]) or
  662. RegInInstruction(reg,Next);
  663. end;
  664. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  665. begin
  666. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  667. begin
  668. Result:=GetNextInstruction(Current,Next);
  669. exit;
  670. end;
  671. Next:=tai(Current.Next);
  672. Result:=false;
  673. while assigned(Next) do
  674. begin
  675. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  676. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  677. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  678. exit
  679. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  680. begin
  681. Result:=true;
  682. exit;
  683. end;
  684. Next:=tai(Next.Next);
  685. end;
  686. end;
  687. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  688. begin
  689. Result:=RegReadByInstruction(reg,hp);
  690. end;
  691. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  692. var
  693. p: taicpu;
  694. opcount: longint;
  695. begin
  696. RegReadByInstruction := false;
  697. if hp.typ <> ait_instruction then
  698. exit;
  699. p := taicpu(hp);
  700. case p.opcode of
  701. A_CALL:
  702. regreadbyinstruction := true;
  703. A_IMUL:
  704. case p.ops of
  705. 1:
  706. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  707. (
  708. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  709. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  710. );
  711. 2,3:
  712. regReadByInstruction :=
  713. reginop(reg,p.oper[0]^) or
  714. reginop(reg,p.oper[1]^);
  715. else
  716. InternalError(2019112801);
  717. end;
  718. A_MUL:
  719. begin
  720. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  721. (
  722. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  723. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  724. );
  725. end;
  726. A_IDIV,A_DIV:
  727. begin
  728. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  729. (
  730. (getregtype(reg)=R_INTREGISTER) and
  731. (
  732. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  733. )
  734. );
  735. end;
  736. else
  737. begin
  738. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  739. begin
  740. RegReadByInstruction := false;
  741. exit;
  742. end;
  743. for opcount := 0 to p.ops-1 do
  744. if (p.oper[opCount]^.typ = top_ref) and
  745. RegInRef(reg,p.oper[opcount]^.ref^) then
  746. begin
  747. RegReadByInstruction := true;
  748. exit
  749. end;
  750. { special handling for SSE MOVSD }
  751. if (p.opcode=A_MOVSD) and (p.ops>0) then
  752. begin
  753. if p.ops<>2 then
  754. internalerror(2017042702);
  755. regReadByInstruction := reginop(reg,p.oper[0]^) or
  756. (
  757. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  758. );
  759. exit;
  760. end;
  761. with insprop[p.opcode] do
  762. begin
  763. case getregtype(reg) of
  764. R_INTREGISTER:
  765. begin
  766. case getsupreg(reg) of
  767. RS_EAX:
  768. if [Ch_REAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  769. begin
  770. RegReadByInstruction := true;
  771. exit
  772. end;
  773. RS_ECX:
  774. if [Ch_RECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  775. begin
  776. RegReadByInstruction := true;
  777. exit
  778. end;
  779. RS_EDX:
  780. if [Ch_REDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  781. begin
  782. RegReadByInstruction := true;
  783. exit
  784. end;
  785. RS_EBX:
  786. if [Ch_REBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  787. begin
  788. RegReadByInstruction := true;
  789. exit
  790. end;
  791. RS_ESP:
  792. if [Ch_RESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  793. begin
  794. RegReadByInstruction := true;
  795. exit
  796. end;
  797. RS_EBP:
  798. if [Ch_REBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  799. begin
  800. RegReadByInstruction := true;
  801. exit
  802. end;
  803. RS_ESI:
  804. if [Ch_RESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  805. begin
  806. RegReadByInstruction := true;
  807. exit
  808. end;
  809. RS_EDI:
  810. if [Ch_REDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  811. begin
  812. RegReadByInstruction := true;
  813. exit
  814. end;
  815. end;
  816. end;
  817. R_MMREGISTER:
  818. begin
  819. case getsupreg(reg) of
  820. RS_XMM0:
  821. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  822. begin
  823. RegReadByInstruction := true;
  824. exit
  825. end;
  826. end;
  827. end;
  828. else
  829. ;
  830. end;
  831. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  832. begin
  833. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  834. begin
  835. case p.condition of
  836. C_A,C_NBE, { CF=0 and ZF=0 }
  837. C_BE,C_NA: { CF=1 or ZF=1 }
  838. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  839. C_AE,C_NB,C_NC, { CF=0 }
  840. C_B,C_NAE,C_C: { CF=1 }
  841. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  842. C_NE,C_NZ, { ZF=0 }
  843. C_E,C_Z: { ZF=1 }
  844. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  845. C_G,C_NLE, { ZF=0 and SF=OF }
  846. C_LE,C_NG: { ZF=1 or SF<>OF }
  847. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  848. C_GE,C_NL, { SF=OF }
  849. C_L,C_NGE: { SF<>OF }
  850. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  851. C_NO, { OF=0 }
  852. C_O: { OF=1 }
  853. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  854. C_NP,C_PO, { PF=0 }
  855. C_P,C_PE: { PF=1 }
  856. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  857. C_NS, { SF=0 }
  858. C_S: { SF=1 }
  859. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  860. else
  861. internalerror(2017042701);
  862. end;
  863. if RegReadByInstruction then
  864. exit;
  865. end;
  866. case getsubreg(reg) of
  867. R_SUBW,R_SUBD,R_SUBQ:
  868. RegReadByInstruction :=
  869. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  870. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  871. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  872. R_SUBFLAGCARRY:
  873. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  874. R_SUBFLAGPARITY:
  875. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  876. R_SUBFLAGAUXILIARY:
  877. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  878. R_SUBFLAGZERO:
  879. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  880. R_SUBFLAGSIGN:
  881. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  882. R_SUBFLAGOVERFLOW:
  883. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  884. R_SUBFLAGINTERRUPT:
  885. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  886. R_SUBFLAGDIRECTION:
  887. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  888. else
  889. internalerror(2017042601);
  890. end;
  891. exit;
  892. end;
  893. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  894. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  895. (p.oper[0]^.reg=p.oper[1]^.reg) then
  896. exit;
  897. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  898. begin
  899. RegReadByInstruction := true;
  900. exit
  901. end;
  902. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  903. begin
  904. RegReadByInstruction := true;
  905. exit
  906. end;
  907. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  908. begin
  909. RegReadByInstruction := true;
  910. exit
  911. end;
  912. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  913. begin
  914. RegReadByInstruction := true;
  915. exit
  916. end;
  917. end;
  918. end;
  919. end;
  920. end;
  921. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  922. begin
  923. result:=false;
  924. if p1.typ<>ait_instruction then
  925. exit;
  926. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  927. exit(true);
  928. if (getregtype(reg)=R_INTREGISTER) and
  929. { change information for xmm movsd are not correct }
  930. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  931. begin
  932. { Handle instructions that behave differently depending on the size and operand count }
  933. case taicpu(p1).opcode of
  934. A_MUL, A_DIV, A_IDIV:
  935. if taicpu(p1).opsize = S_B then
  936. Result := (getsupreg(Reg) = RS_EAX)
  937. else
  938. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  939. A_IMUL:
  940. if taicpu(p1).ops = 1 then
  941. begin
  942. if taicpu(p1).opsize = S_B then
  943. Result := (getsupreg(Reg) = RS_EAX)
  944. else
  945. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  946. end;
  947. { If ops are greater than 1, call inherited method }
  948. else
  949. case getsupreg(reg) of
  950. { RS_EAX = RS_RAX on x86-64 }
  951. RS_EAX:
  952. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  953. RS_ECX:
  954. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  955. RS_EDX:
  956. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  957. RS_EBX:
  958. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  959. RS_ESP:
  960. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  961. RS_EBP:
  962. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  963. RS_ESI:
  964. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  965. RS_EDI:
  966. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  967. else
  968. ;
  969. end;
  970. end;
  971. if result then
  972. exit;
  973. end
  974. else if getregtype(reg)=R_MMREGISTER then
  975. begin
  976. case getsupreg(reg) of
  977. RS_XMM0:
  978. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  979. else
  980. ;
  981. end;
  982. if result then
  983. exit;
  984. end
  985. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  986. begin
  987. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  988. exit(true);
  989. case getsubreg(reg) of
  990. R_SUBFLAGCARRY:
  991. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  992. R_SUBFLAGPARITY:
  993. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  994. R_SUBFLAGAUXILIARY:
  995. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  996. R_SUBFLAGZERO:
  997. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  998. R_SUBFLAGSIGN:
  999. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  1000. R_SUBFLAGOVERFLOW:
  1001. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  1002. R_SUBFLAGINTERRUPT:
  1003. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  1004. R_SUBFLAGDIRECTION:
  1005. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  1006. R_SUBW,R_SUBD,R_SUBQ:
  1007. { Everything except the direction bits }
  1008. Result:=
  1009. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1010. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1011. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1012. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1013. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1014. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1015. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1016. else
  1017. ;
  1018. end;
  1019. if result then
  1020. exit;
  1021. end
  1022. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1023. exit(true);
  1024. Result:=inherited RegInInstruction(Reg, p1);
  1025. end;
  1026. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1027. const
  1028. WriteOps: array[0..3] of set of TInsChange =
  1029. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1030. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1031. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1032. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1033. var
  1034. OperIdx: Integer;
  1035. begin
  1036. Result := False;
  1037. if p1.typ <> ait_instruction then
  1038. exit;
  1039. with insprop[taicpu(p1).opcode] do
  1040. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1041. begin
  1042. case getsubreg(reg) of
  1043. R_SUBW,R_SUBD,R_SUBQ:
  1044. Result :=
  1045. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1046. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1047. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1048. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1049. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1050. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1051. R_SUBFLAGCARRY:
  1052. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1053. R_SUBFLAGPARITY:
  1054. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1055. R_SUBFLAGAUXILIARY:
  1056. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1057. R_SUBFLAGZERO:
  1058. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1059. R_SUBFLAGSIGN:
  1060. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1061. R_SUBFLAGOVERFLOW:
  1062. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1063. R_SUBFLAGINTERRUPT:
  1064. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1065. R_SUBFLAGDIRECTION:
  1066. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1067. else
  1068. internalerror(2017042602);
  1069. end;
  1070. exit;
  1071. end;
  1072. case taicpu(p1).opcode of
  1073. A_CALL:
  1074. { We could potentially set Result to False if the register in
  1075. question is non-volatile for the subroutine's calling convention,
  1076. but this would require detecting the calling convention in use and
  1077. also assuming that the routine doesn't contain malformed assembly
  1078. language, for example... so it could only be done under -O4 as it
  1079. would be considered a side-effect. [Kit] }
  1080. Result := True;
  1081. A_MOVSD:
  1082. { special handling for SSE MOVSD }
  1083. if (taicpu(p1).ops>0) then
  1084. begin
  1085. if taicpu(p1).ops<>2 then
  1086. internalerror(2017042703);
  1087. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1088. end;
  1089. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1090. so fix it here (FK)
  1091. }
  1092. A_VMOVSS,
  1093. A_VMOVSD:
  1094. begin
  1095. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1096. exit;
  1097. end;
  1098. A_MUL, A_DIV, A_IDIV:
  1099. begin
  1100. if taicpu(p1).opsize = S_B then
  1101. Result := (getsupreg(Reg) = RS_EAX)
  1102. else
  1103. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1104. end;
  1105. A_IMUL:
  1106. begin
  1107. if taicpu(p1).ops = 1 then
  1108. begin
  1109. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1110. end
  1111. else
  1112. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1113. Exit;
  1114. end;
  1115. else
  1116. ;
  1117. end;
  1118. if Result then
  1119. exit;
  1120. with insprop[taicpu(p1).opcode] do
  1121. begin
  1122. if getregtype(reg)=R_INTREGISTER then
  1123. begin
  1124. case getsupreg(reg) of
  1125. RS_EAX:
  1126. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1127. begin
  1128. Result := True;
  1129. exit
  1130. end;
  1131. RS_ECX:
  1132. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1133. begin
  1134. Result := True;
  1135. exit
  1136. end;
  1137. RS_EDX:
  1138. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1139. begin
  1140. Result := True;
  1141. exit
  1142. end;
  1143. RS_EBX:
  1144. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1145. begin
  1146. Result := True;
  1147. exit
  1148. end;
  1149. RS_ESP:
  1150. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1151. begin
  1152. Result := True;
  1153. exit
  1154. end;
  1155. RS_EBP:
  1156. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1157. begin
  1158. Result := True;
  1159. exit
  1160. end;
  1161. RS_ESI:
  1162. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1163. begin
  1164. Result := True;
  1165. exit
  1166. end;
  1167. RS_EDI:
  1168. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1169. begin
  1170. Result := True;
  1171. exit
  1172. end;
  1173. end;
  1174. end;
  1175. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1176. if (WriteOps[OperIdx]*Ch<>[]) and
  1177. { The register doesn't get modified inside a reference }
  1178. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1179. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1180. begin
  1181. Result := true;
  1182. exit
  1183. end;
  1184. end;
  1185. end;
  1186. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1187. const
  1188. WriteOps: array[0..3] of set of TInsChange =
  1189. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1190. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1191. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1192. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1193. var
  1194. X: Integer;
  1195. CurrentP1Size: asizeint;
  1196. begin
  1197. Result := (
  1198. (Ref.base <> NR_NO) and
  1199. {$ifdef x86_64}
  1200. (Ref.base <> NR_RIP) and
  1201. {$endif x86_64}
  1202. RegModifiedBetween(Ref.base, p1, p2)
  1203. ) or
  1204. (
  1205. (Ref.index <> NR_NO) and
  1206. (Ref.index <> Ref.base) and
  1207. RegModifiedBetween(Ref.index, p1, p2)
  1208. );
  1209. { Now check to see if the memory itself is written to }
  1210. if not Result then
  1211. begin
  1212. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1213. if p1.typ = ait_instruction then
  1214. begin
  1215. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1216. with insprop[taicpu(p1).opcode] do
  1217. for X := 0 to taicpu(p1).ops - 1 do
  1218. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1219. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1220. { Catch any potential overlaps }
  1221. (
  1222. (RefSize = 0) or
  1223. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1224. ) and
  1225. (
  1226. (CurrentP1Size = 0) or
  1227. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1228. ) and
  1229. { Reference is used, but does the instruction write to it? }
  1230. (
  1231. (Ch_All in Ch) or
  1232. ((WriteOps[X] * Ch) <> [])
  1233. ) then
  1234. begin
  1235. Result := True;
  1236. Break;
  1237. end;
  1238. end;
  1239. end;
  1240. end;
  1241. {$ifdef DEBUG_AOPTCPU}
  1242. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1243. begin
  1244. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1245. end;
  1246. function debug_tostr(i: tcgint): string; inline;
  1247. begin
  1248. Result := tostr(i);
  1249. end;
  1250. function debug_hexstr(i: tcgint): string;
  1251. begin
  1252. Result := '0x';
  1253. case i of
  1254. 0..$FF:
  1255. Result := Result + hexstr(i, 2);
  1256. $100..$FFFF:
  1257. Result := Result + hexstr(i, 4);
  1258. $10000..$FFFFFF:
  1259. Result := Result + hexstr(i, 6);
  1260. $1000000..$FFFFFFFF:
  1261. Result := Result + hexstr(i, 8);
  1262. else
  1263. Result := Result + hexstr(i, 16);
  1264. end;
  1265. end;
  1266. function debug_regname(r: TRegister): string; inline;
  1267. begin
  1268. Result := '%' + std_regname(r);
  1269. end;
  1270. { Debug output function - creates a string representation of an operator }
  1271. function debug_operstr(oper: TOper): string;
  1272. begin
  1273. case oper.typ of
  1274. top_const:
  1275. Result := '$' + debug_tostr(oper.val);
  1276. top_reg:
  1277. Result := debug_regname(oper.reg);
  1278. top_ref:
  1279. begin
  1280. if oper.ref^.offset <> 0 then
  1281. Result := debug_tostr(oper.ref^.offset) + '('
  1282. else
  1283. Result := '(';
  1284. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1285. begin
  1286. Result := Result + debug_regname(oper.ref^.base);
  1287. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1288. Result := Result + ',' + debug_regname(oper.ref^.index);
  1289. end
  1290. else
  1291. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1292. Result := Result + debug_regname(oper.ref^.index);
  1293. if (oper.ref^.scalefactor > 1) then
  1294. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1295. else
  1296. Result := Result + ')';
  1297. end;
  1298. else
  1299. Result := '[UNKNOWN]';
  1300. end;
  1301. end;
  1302. function debug_op2str(opcode: tasmop): string; inline;
  1303. begin
  1304. Result := std_op2str[opcode];
  1305. end;
  1306. function debug_opsize2str(opsize: topsize): string; inline;
  1307. begin
  1308. Result := gas_opsize2str[opsize];
  1309. end;
  1310. {$else DEBUG_AOPTCPU}
  1311. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1312. begin
  1313. end;
  1314. function debug_tostr(i: tcgint): string; inline;
  1315. begin
  1316. Result := '';
  1317. end;
  1318. function debug_hexstr(i: tcgint): string; inline;
  1319. begin
  1320. Result := '';
  1321. end;
  1322. function debug_regname(r: TRegister): string; inline;
  1323. begin
  1324. Result := '';
  1325. end;
  1326. function debug_operstr(oper: TOper): string; inline;
  1327. begin
  1328. Result := '';
  1329. end;
  1330. function debug_op2str(opcode: tasmop): string; inline;
  1331. begin
  1332. Result := '';
  1333. end;
  1334. function debug_opsize2str(opsize: topsize): string; inline;
  1335. begin
  1336. Result := '';
  1337. end;
  1338. {$endif DEBUG_AOPTCPU}
  1339. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1340. begin
  1341. {$ifdef x86_64}
  1342. { Always fine on x86-64 }
  1343. Result := True;
  1344. {$else x86_64}
  1345. Result :=
  1346. {$ifdef i8086}
  1347. (current_settings.cputype >= cpu_386) and
  1348. {$endif i8086}
  1349. (
  1350. { Always accept if optimising for size }
  1351. (cs_opt_size in current_settings.optimizerswitches) or
  1352. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1353. (current_settings.optimizecputype >= cpu_Pentium2)
  1354. );
  1355. {$endif x86_64}
  1356. end;
  1357. { Attempts to allocate a volatile integer register for use between p and hp,
  1358. using AUsedRegs for the current register usage information. Returns NR_NO
  1359. if no free register could be found }
  1360. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1361. var
  1362. RegSet: TCPURegisterSet;
  1363. CurrentSuperReg: Integer;
  1364. CurrentReg: TRegister;
  1365. Currentp: tai;
  1366. Breakout: Boolean;
  1367. begin
  1368. Result := NR_NO;
  1369. RegSet :=
  1370. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1371. current_procinfo.saved_regs_int;
  1372. (*
  1373. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1374. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1375. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1376. *)
  1377. for CurrentSuperReg in RegSet do
  1378. begin
  1379. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1380. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1381. {$if defined(i386) or defined(i8086)}
  1382. { If the target size is 8-bit, make sure we can actually encode it }
  1383. and (
  1384. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1385. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1386. )
  1387. {$endif i386 or i8086}
  1388. then
  1389. begin
  1390. Currentp := p;
  1391. Breakout := False;
  1392. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1393. begin
  1394. case Currentp.typ of
  1395. ait_instruction:
  1396. begin
  1397. if RegInInstruction(CurrentReg, Currentp) then
  1398. begin
  1399. Breakout := True;
  1400. Break;
  1401. end;
  1402. { Cannot allocate across an unconditional jump }
  1403. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1404. Exit;
  1405. end;
  1406. ait_marker:
  1407. { Don't try anything more if a marker is hit }
  1408. Exit;
  1409. ait_regalloc:
  1410. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1411. begin
  1412. Breakout := True;
  1413. Break;
  1414. end;
  1415. else
  1416. ;
  1417. end;
  1418. end;
  1419. if Breakout then
  1420. { Try the next register }
  1421. Continue;
  1422. { We have a free register available }
  1423. Result := CurrentReg;
  1424. if not DontAlloc then
  1425. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1426. Exit;
  1427. end;
  1428. end;
  1429. end;
  1430. { Attempts to allocate a volatile MM register for use between p and hp,
  1431. using AUsedRegs for the current register usage information. Returns NR_NO
  1432. if no free register could be found }
  1433. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1434. var
  1435. RegSet: TCPURegisterSet;
  1436. CurrentSuperReg: Integer;
  1437. CurrentReg: TRegister;
  1438. Currentp: tai;
  1439. Breakout: Boolean;
  1440. begin
  1441. Result := NR_NO;
  1442. RegSet :=
  1443. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1444. current_procinfo.saved_regs_mm;
  1445. for CurrentSuperReg in RegSet do
  1446. begin
  1447. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1448. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1449. begin
  1450. Currentp := p;
  1451. Breakout := False;
  1452. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1453. begin
  1454. case Currentp.typ of
  1455. ait_instruction:
  1456. begin
  1457. if RegInInstruction(CurrentReg, Currentp) then
  1458. begin
  1459. Breakout := True;
  1460. Break;
  1461. end;
  1462. { Cannot allocate across an unconditional jump }
  1463. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1464. Exit;
  1465. end;
  1466. ait_marker:
  1467. { Don't try anything more if a marker is hit }
  1468. Exit;
  1469. ait_regalloc:
  1470. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1471. begin
  1472. Breakout := True;
  1473. Break;
  1474. end;
  1475. else
  1476. ;
  1477. end;
  1478. end;
  1479. if Breakout then
  1480. { Try the next register }
  1481. Continue;
  1482. { We have a free register available }
  1483. Result := CurrentReg;
  1484. if not DontAlloc then
  1485. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1486. Exit;
  1487. end;
  1488. end;
  1489. end;
  1490. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1491. begin
  1492. if not SuperRegistersEqual(reg1,reg2) then
  1493. exit(false);
  1494. if getregtype(reg1)<>R_INTREGISTER then
  1495. exit(true); {because SuperRegisterEqual is true}
  1496. case getsubreg(reg1) of
  1497. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1498. higher, it preserves the high bits, so the new value depends on
  1499. reg2's previous value. In other words, it is equivalent to doing:
  1500. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1501. R_SUBL:
  1502. exit(getsubreg(reg2)=R_SUBL);
  1503. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1504. higher, it actually does a:
  1505. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1506. R_SUBH:
  1507. exit(getsubreg(reg2)=R_SUBH);
  1508. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1509. bits of reg2:
  1510. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1511. R_SUBW:
  1512. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1513. { a write to R_SUBD always overwrites every other subregister,
  1514. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1515. R_SUBD,
  1516. R_SUBQ:
  1517. exit(true);
  1518. else
  1519. internalerror(2017042801);
  1520. end;
  1521. end;
  1522. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1523. begin
  1524. if not SuperRegistersEqual(reg1,reg2) then
  1525. exit(false);
  1526. if getregtype(reg1)<>R_INTREGISTER then
  1527. exit(true); {because SuperRegisterEqual is true}
  1528. case getsubreg(reg1) of
  1529. R_SUBL:
  1530. exit(getsubreg(reg2)<>R_SUBH);
  1531. R_SUBH:
  1532. exit(getsubreg(reg2)<>R_SUBL);
  1533. R_SUBW,
  1534. R_SUBD,
  1535. R_SUBQ:
  1536. exit(true);
  1537. else
  1538. internalerror(2017042802);
  1539. end;
  1540. end;
  1541. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1542. var
  1543. hp1 : tai;
  1544. l : TCGInt;
  1545. begin
  1546. result:=false;
  1547. if not(GetNextInstruction(p, hp1)) then
  1548. exit;
  1549. { changes the code sequence
  1550. shr/sar const1, x
  1551. shl const2, x
  1552. to
  1553. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1554. if (taicpu(p).oper[0]^.typ = top_const) and
  1555. MatchInstruction(hp1,A_SHL,[]) and
  1556. (taicpu(hp1).oper[0]^.typ = top_const) and
  1557. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1558. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1559. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1560. begin
  1561. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1562. not(cs_opt_size in current_settings.optimizerswitches)
  1563. {$ifdef x86_64}
  1564. and (
  1565. (taicpu(p).opsize <> S_Q) or
  1566. { 64-bit AND can only store signed 32-bit immediates }
  1567. (taicpu(p).oper[0]^.val < 32)
  1568. )
  1569. {$endif x86_64}
  1570. then
  1571. begin
  1572. { shr/sar const1, %reg
  1573. shl const2, %reg
  1574. with const1 > const2 }
  1575. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1576. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1577. taicpu(hp1).opcode := A_AND;
  1578. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1579. case taicpu(p).opsize Of
  1580. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1581. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1582. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1583. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1584. else
  1585. Internalerror(2017050703)
  1586. end;
  1587. end
  1588. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1589. not(cs_opt_size in current_settings.optimizerswitches)
  1590. {$ifdef x86_64}
  1591. and (
  1592. (taicpu(p).opsize <> S_Q) or
  1593. { 64-bit AND can only store signed 32-bit immediates }
  1594. (taicpu(p).oper[0]^.val < 32)
  1595. )
  1596. {$endif x86_64}
  1597. then
  1598. begin
  1599. { shr/sar const1, %reg
  1600. shl const2, %reg
  1601. with const1 < const2 }
  1602. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1603. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1604. taicpu(p).opcode := A_AND;
  1605. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1606. case taicpu(p).opsize Of
  1607. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1608. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1609. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1610. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1611. else
  1612. Internalerror(2017050702)
  1613. end;
  1614. end
  1615. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val)
  1616. {$ifdef x86_64}
  1617. and (
  1618. (taicpu(p).opsize <> S_Q) or
  1619. { 64-bit AND can only store signed 32-bit immediates }
  1620. (taicpu(p).oper[0]^.val < 32)
  1621. )
  1622. {$endif x86_64}
  1623. then
  1624. begin
  1625. { shr/sar const1, %reg
  1626. shl const2, %reg
  1627. with const1 = const2 }
  1628. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1629. taicpu(p).opcode := A_AND;
  1630. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1631. case taicpu(p).opsize Of
  1632. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1633. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1634. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1635. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1636. else
  1637. Internalerror(2017050701)
  1638. end;
  1639. RemoveInstruction(hp1);
  1640. end;
  1641. end;
  1642. end;
  1643. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1644. var
  1645. opsize : topsize;
  1646. hp1, hp2 : tai;
  1647. tmpref : treference;
  1648. ShiftValue : Cardinal;
  1649. BaseValue : TCGInt;
  1650. begin
  1651. result:=false;
  1652. opsize:=taicpu(p).opsize;
  1653. { changes certain "imul const, %reg"'s to lea sequences }
  1654. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1655. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1656. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1657. if (taicpu(p).oper[0]^.val = 1) then
  1658. if (taicpu(p).ops = 2) then
  1659. { remove "imul $1, reg" }
  1660. begin
  1661. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1662. Result := RemoveCurrentP(p);
  1663. end
  1664. else
  1665. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1666. begin
  1667. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1668. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1669. asml.InsertAfter(hp1, p);
  1670. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1671. RemoveCurrentP(p, hp1);
  1672. Result := True;
  1673. end
  1674. else if ((taicpu(p).ops <= 2) or
  1675. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1676. not(cs_opt_size in current_settings.optimizerswitches) and
  1677. (not(GetNextInstruction(p, hp1)) or
  1678. not((tai(hp1).typ = ait_instruction) and
  1679. ((taicpu(hp1).opcode=A_Jcc) and
  1680. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1681. begin
  1682. {
  1683. imul X, reg1, reg2 to
  1684. lea (reg1,reg1,Y), reg2
  1685. shl ZZ,reg2
  1686. imul XX, reg1 to
  1687. lea (reg1,reg1,YY), reg1
  1688. shl ZZ,reg2
  1689. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1690. it does not exist as a separate optimization target in FPC though.
  1691. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1692. at most two zeros
  1693. }
  1694. reference_reset(tmpref,1,[]);
  1695. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1696. begin
  1697. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1698. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1699. TmpRef.base := taicpu(p).oper[1]^.reg;
  1700. TmpRef.index := taicpu(p).oper[1]^.reg;
  1701. if not(BaseValue in [3,5,9]) then
  1702. Internalerror(2018110101);
  1703. TmpRef.ScaleFactor := BaseValue-1;
  1704. if (taicpu(p).ops = 2) then
  1705. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1706. else
  1707. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1708. AsmL.InsertAfter(hp1,p);
  1709. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1710. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1711. RemoveCurrentP(p, hp1);
  1712. if ShiftValue>0 then
  1713. begin
  1714. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1715. AsmL.InsertAfter(hp2,hp1);
  1716. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1717. end;
  1718. Result := True;
  1719. end;
  1720. end;
  1721. end;
  1722. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1723. begin
  1724. Result := False;
  1725. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1726. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1727. begin
  1728. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1729. taicpu(p).opcode := A_MOV;
  1730. Result := True;
  1731. end;
  1732. end;
  1733. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1734. var
  1735. p: taicpu absolute hp; { Implicit typecast }
  1736. i: Integer;
  1737. begin
  1738. Result := False;
  1739. if not assigned(hp) or
  1740. (hp.typ <> ait_instruction) then
  1741. Exit;
  1742. Prefetch(insprop[p.opcode]);
  1743. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1744. with insprop[p.opcode] do
  1745. begin
  1746. case getsubreg(reg) of
  1747. R_SUBW,R_SUBD,R_SUBQ:
  1748. Result:=
  1749. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1750. uncommon flags are checked first }
  1751. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1752. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1753. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1754. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1755. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1756. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1757. R_SUBFLAGCARRY:
  1758. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1759. R_SUBFLAGPARITY:
  1760. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1761. R_SUBFLAGAUXILIARY:
  1762. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1763. R_SUBFLAGZERO:
  1764. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1765. R_SUBFLAGSIGN:
  1766. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1767. R_SUBFLAGOVERFLOW:
  1768. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1769. R_SUBFLAGINTERRUPT:
  1770. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1771. R_SUBFLAGDIRECTION:
  1772. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1773. else
  1774. internalerror(2017050501);
  1775. end;
  1776. exit;
  1777. end;
  1778. { Handle special cases first }
  1779. case p.opcode of
  1780. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1781. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1782. begin
  1783. Result :=
  1784. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1785. (p.oper[1]^.typ = top_reg) and
  1786. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1787. (
  1788. (p.oper[0]^.typ = top_const) or
  1789. (
  1790. (p.oper[0]^.typ = top_reg) and
  1791. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1792. ) or (
  1793. (p.oper[0]^.typ = top_ref) and
  1794. not RegInRef(reg,p.oper[0]^.ref^)
  1795. )
  1796. );
  1797. end;
  1798. A_MUL, A_IMUL:
  1799. Result :=
  1800. (
  1801. (p.ops=3) and { IMUL only }
  1802. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1803. (
  1804. (
  1805. (p.oper[1]^.typ=top_reg) and
  1806. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1807. ) or (
  1808. (p.oper[1]^.typ=top_ref) and
  1809. not RegInRef(reg,p.oper[1]^.ref^)
  1810. )
  1811. )
  1812. ) or (
  1813. (
  1814. (p.ops=1) and
  1815. (
  1816. (
  1817. (
  1818. (p.oper[0]^.typ=top_reg) and
  1819. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1820. )
  1821. ) or (
  1822. (p.oper[0]^.typ=top_ref) and
  1823. not RegInRef(reg,p.oper[0]^.ref^)
  1824. )
  1825. ) and (
  1826. (
  1827. (p.opsize=S_B) and
  1828. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1829. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1830. ) or (
  1831. (p.opsize=S_W) and
  1832. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1833. ) or (
  1834. (p.opsize=S_L) and
  1835. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1836. {$ifdef x86_64}
  1837. ) or (
  1838. (p.opsize=S_Q) and
  1839. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1840. {$endif x86_64}
  1841. )
  1842. )
  1843. )
  1844. );
  1845. A_CBW:
  1846. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1847. {$ifndef x86_64}
  1848. A_LDS:
  1849. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1850. A_LES:
  1851. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1852. {$endif not x86_64}
  1853. A_LFS:
  1854. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1855. A_LGS:
  1856. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1857. A_LSS:
  1858. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1859. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1860. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1861. A_LODSB:
  1862. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1863. A_LODSW:
  1864. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1865. {$ifdef x86_64}
  1866. A_LODSQ:
  1867. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1868. {$endif x86_64}
  1869. A_LODSD:
  1870. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1871. A_FSTSW, A_FNSTSW:
  1872. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1873. else
  1874. begin
  1875. with insprop[p.opcode] do
  1876. begin
  1877. if (
  1878. { xor %reg,%reg etc. is classed as a new value }
  1879. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1880. MatchOpType(p, top_reg, top_reg) and
  1881. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1882. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1883. ) then
  1884. begin
  1885. Result := True;
  1886. Exit;
  1887. end;
  1888. { Make sure the entire register is overwritten }
  1889. if (getregtype(reg) = R_INTREGISTER) then
  1890. begin
  1891. if (p.ops > 0) then
  1892. begin
  1893. if RegInOp(reg, p.oper[0]^) then
  1894. begin
  1895. if (p.oper[0]^.typ = top_ref) then
  1896. begin
  1897. if RegInRef(reg, p.oper[0]^.ref^) then
  1898. begin
  1899. Result := False;
  1900. Exit;
  1901. end;
  1902. end
  1903. else if (p.oper[0]^.typ = top_reg) then
  1904. begin
  1905. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1906. begin
  1907. Result := False;
  1908. Exit;
  1909. end
  1910. else if ([Ch_WOp1]*Ch<>[]) then
  1911. begin
  1912. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1913. Result := True
  1914. else
  1915. begin
  1916. Result := False;
  1917. Exit;
  1918. end;
  1919. end;
  1920. end;
  1921. end;
  1922. if (p.ops > 1) then
  1923. begin
  1924. if RegInOp(reg, p.oper[1]^) then
  1925. begin
  1926. if (p.oper[1]^.typ = top_ref) then
  1927. begin
  1928. if RegInRef(reg, p.oper[1]^.ref^) then
  1929. begin
  1930. Result := False;
  1931. Exit;
  1932. end;
  1933. end
  1934. else if (p.oper[1]^.typ = top_reg) then
  1935. begin
  1936. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1937. begin
  1938. Result := False;
  1939. Exit;
  1940. end
  1941. else if ([Ch_WOp2]*Ch<>[]) then
  1942. begin
  1943. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1944. Result := True
  1945. else
  1946. begin
  1947. Result := False;
  1948. Exit;
  1949. end;
  1950. end;
  1951. end;
  1952. end;
  1953. if (p.ops > 2) then
  1954. begin
  1955. if RegInOp(reg, p.oper[2]^) then
  1956. begin
  1957. if (p.oper[2]^.typ = top_ref) then
  1958. begin
  1959. if RegInRef(reg, p.oper[2]^.ref^) then
  1960. begin
  1961. Result := False;
  1962. Exit;
  1963. end;
  1964. end
  1965. else if (p.oper[2]^.typ = top_reg) then
  1966. begin
  1967. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1968. begin
  1969. Result := False;
  1970. Exit;
  1971. end
  1972. else if ([Ch_WOp3]*Ch<>[]) then
  1973. begin
  1974. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1975. Result := True
  1976. else
  1977. begin
  1978. Result := False;
  1979. Exit;
  1980. end;
  1981. end;
  1982. end;
  1983. end;
  1984. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1985. begin
  1986. if (p.oper[3]^.typ = top_ref) then
  1987. begin
  1988. if RegInRef(reg, p.oper[3]^.ref^) then
  1989. begin
  1990. Result := False;
  1991. Exit;
  1992. end;
  1993. end
  1994. else if (p.oper[3]^.typ = top_reg) then
  1995. begin
  1996. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1997. begin
  1998. Result := False;
  1999. Exit;
  2000. end
  2001. else if ([Ch_WOp4]*Ch<>[]) then
  2002. begin
  2003. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  2004. Result := True
  2005. else
  2006. begin
  2007. Result := False;
  2008. Exit;
  2009. end;
  2010. end;
  2011. end;
  2012. end;
  2013. end;
  2014. end;
  2015. end;
  2016. { Don't do these ones first in case an input operand is equal to an explicit output register }
  2017. case getsupreg(reg) of
  2018. RS_EAX:
  2019. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  2020. begin
  2021. Result := True;
  2022. Exit;
  2023. end;
  2024. RS_ECX:
  2025. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  2026. begin
  2027. Result := True;
  2028. Exit;
  2029. end;
  2030. RS_EDX:
  2031. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2032. begin
  2033. Result := True;
  2034. Exit;
  2035. end;
  2036. RS_EBX:
  2037. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2038. begin
  2039. Result := True;
  2040. Exit;
  2041. end;
  2042. RS_ESP:
  2043. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2044. begin
  2045. Result := True;
  2046. Exit;
  2047. end;
  2048. RS_EBP:
  2049. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2050. begin
  2051. Result := True;
  2052. Exit;
  2053. end;
  2054. RS_ESI:
  2055. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2056. begin
  2057. Result := True;
  2058. Exit;
  2059. end;
  2060. RS_EDI:
  2061. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2062. begin
  2063. Result := True;
  2064. Exit;
  2065. end;
  2066. else
  2067. ;
  2068. end;
  2069. end;
  2070. end;
  2071. end;
  2072. end;
  2073. end;
  2074. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2075. var
  2076. hp2,hp3 : tai;
  2077. begin
  2078. { some x86-64 issue a NOP before the real exit code }
  2079. if MatchInstruction(p,A_NOP,[]) then
  2080. GetNextInstruction(p,p);
  2081. result:=assigned(p) and (p.typ=ait_instruction) and
  2082. ((taicpu(p).opcode = A_RET) or
  2083. ((taicpu(p).opcode=A_LEAVE) and
  2084. GetNextInstruction(p,hp2) and
  2085. MatchInstruction(hp2,A_RET,[S_NO])
  2086. ) or
  2087. (((taicpu(p).opcode=A_LEA) and
  2088. MatchOpType(taicpu(p),top_ref,top_reg) and
  2089. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2090. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2091. ) and
  2092. GetNextInstruction(p,hp2) and
  2093. MatchInstruction(hp2,A_RET,[S_NO])
  2094. ) or
  2095. ((((taicpu(p).opcode=A_MOV) and
  2096. MatchOpType(taicpu(p),top_reg,top_reg) and
  2097. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2098. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2099. ((taicpu(p).opcode=A_LEA) and
  2100. MatchOpType(taicpu(p),top_ref,top_reg) and
  2101. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2102. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2103. )
  2104. ) and
  2105. GetNextInstruction(p,hp2) and
  2106. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2107. MatchOpType(taicpu(hp2),top_reg) and
  2108. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2109. GetNextInstruction(hp2,hp3) and
  2110. MatchInstruction(hp3,A_RET,[S_NO])
  2111. )
  2112. );
  2113. end;
  2114. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2115. begin
  2116. isFoldableArithOp := False;
  2117. case hp1.opcode of
  2118. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2119. isFoldableArithOp :=
  2120. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2121. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2122. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2123. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2124. (taicpu(hp1).oper[1]^.reg = reg);
  2125. A_INC,A_DEC,A_NEG,A_NOT:
  2126. isFoldableArithOp :=
  2127. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2128. (taicpu(hp1).oper[0]^.reg = reg);
  2129. else
  2130. ;
  2131. end;
  2132. end;
  2133. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2134. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2135. var
  2136. hp2: tai;
  2137. begin
  2138. hp2 := p;
  2139. repeat
  2140. hp2 := tai(hp2.previous);
  2141. if assigned(hp2) and
  2142. (hp2.typ = ait_regalloc) and
  2143. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2144. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2145. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2146. begin
  2147. RemoveInstruction(hp2);
  2148. break;
  2149. end;
  2150. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2151. end;
  2152. begin
  2153. case current_procinfo.procdef.returndef.typ of
  2154. arraydef,recorddef,pointerdef,
  2155. stringdef,enumdef,procdef,objectdef,errordef,
  2156. filedef,setdef,procvardef,
  2157. classrefdef,forwarddef:
  2158. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2159. orddef:
  2160. if current_procinfo.procdef.returndef.size <> 0 then
  2161. begin
  2162. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2163. { for int64/qword }
  2164. if current_procinfo.procdef.returndef.size = 8 then
  2165. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2166. end;
  2167. else
  2168. ;
  2169. end;
  2170. end;
  2171. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2172. var
  2173. hp1: tai;
  2174. operswap: poper;
  2175. begin
  2176. Result := False;
  2177. { Optimise:
  2178. cmov(c) %reg1,%reg2
  2179. mov %reg2,%reg1
  2180. (%reg2 dealloc.)
  2181. To:
  2182. cmov(~c) %reg2,%reg1
  2183. }
  2184. if (taicpu(p).oper[0]^.typ = top_reg) then
  2185. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2186. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2187. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2188. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2189. begin
  2190. TransferUsedRegs(TmpUsedRegs);
  2191. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2192. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2193. begin
  2194. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2195. { Save time by swapping the pointers (they're both registers, so
  2196. we don't need to worry about reference counts) }
  2197. operswap := taicpu(p).oper[0];
  2198. taicpu(p).oper[0] := taicpu(p).oper[1];
  2199. taicpu(p).oper[1] := operswap;
  2200. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2201. RemoveInstruction(hp1);
  2202. { It's still a CMOV, so we can look further ahead }
  2203. Include(OptsToCheck, aoc_ForceNewIteration);
  2204. { But first, let's see if this will get optimised again
  2205. (probably won't happen, but best to be sure) }
  2206. Continue;
  2207. end;
  2208. Break;
  2209. end;
  2210. end;
  2211. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2212. var
  2213. hp1,hp2 : tai;
  2214. begin
  2215. result:=false;
  2216. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2217. begin
  2218. { vmova* reg1,reg1
  2219. =>
  2220. <nop> }
  2221. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2222. begin
  2223. RemoveCurrentP(p);
  2224. result:=true;
  2225. exit;
  2226. end;
  2227. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2228. (hp1.typ = ait_instruction) and
  2229. (
  2230. { Under -O2 and below, the instructions are always adjacent }
  2231. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2232. (taicpu(hp1).ops <= 1) or
  2233. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2234. { If reg1 = reg3, reg1 must not be modified in between }
  2235. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2236. ) then
  2237. begin
  2238. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2239. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2240. begin
  2241. { vmova* reg1,reg2
  2242. ...
  2243. vmova* reg2,reg3
  2244. dealloc reg2
  2245. =>
  2246. vmova* reg1,reg3 }
  2247. TransferUsedRegs(TmpUsedRegs);
  2248. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2249. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2250. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2251. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2252. begin
  2253. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2254. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2255. TransferUsedRegs(TmpUsedRegs);
  2256. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2257. RemoveInstruction(hp1);
  2258. result:=true;
  2259. exit;
  2260. end;
  2261. { special case:
  2262. vmova* reg1,<op>
  2263. ...
  2264. vmova* <op>,reg1
  2265. =>
  2266. vmova* reg1,<op> }
  2267. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2268. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2269. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2270. ) then
  2271. begin
  2272. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2273. RemoveInstruction(hp1);
  2274. result:=true;
  2275. exit;
  2276. end
  2277. end
  2278. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2279. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2280. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2281. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2282. ) and
  2283. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2284. begin
  2285. { vmova* reg1,reg2
  2286. ...
  2287. vmovs* reg2,<op>
  2288. dealloc reg2
  2289. =>
  2290. vmovs* reg1,<op> }
  2291. TransferUsedRegs(TmpUsedRegs);
  2292. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2293. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2294. begin
  2295. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2296. taicpu(p).opcode:=taicpu(hp1).opcode;
  2297. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2298. TransferUsedRegs(TmpUsedRegs);
  2299. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2300. RemoveInstruction(hp1);
  2301. result:=true;
  2302. exit;
  2303. end
  2304. end;
  2305. if MatchInstruction(hp1,[A_VFMADDPD,
  2306. A_VFMADD132PD,
  2307. A_VFMADD132PS,
  2308. A_VFMADD132SD,
  2309. A_VFMADD132SS,
  2310. A_VFMADD213PD,
  2311. A_VFMADD213PS,
  2312. A_VFMADD213SD,
  2313. A_VFMADD213SS,
  2314. A_VFMADD231PD,
  2315. A_VFMADD231PS,
  2316. A_VFMADD231SD,
  2317. A_VFMADD231SS,
  2318. A_VFMADDSUB132PD,
  2319. A_VFMADDSUB132PS,
  2320. A_VFMADDSUB213PD,
  2321. A_VFMADDSUB213PS,
  2322. A_VFMADDSUB231PD,
  2323. A_VFMADDSUB231PS,
  2324. A_VFMSUB132PD,
  2325. A_VFMSUB132PS,
  2326. A_VFMSUB132SD,
  2327. A_VFMSUB132SS,
  2328. A_VFMSUB213PD,
  2329. A_VFMSUB213PS,
  2330. A_VFMSUB213SD,
  2331. A_VFMSUB213SS,
  2332. A_VFMSUB231PD,
  2333. A_VFMSUB231PS,
  2334. A_VFMSUB231SD,
  2335. A_VFMSUB231SS,
  2336. A_VFMSUBADD132PD,
  2337. A_VFMSUBADD132PS,
  2338. A_VFMSUBADD213PD,
  2339. A_VFMSUBADD213PS,
  2340. A_VFMSUBADD231PD,
  2341. A_VFMSUBADD231PS,
  2342. A_VFNMADD132PD,
  2343. A_VFNMADD132PS,
  2344. A_VFNMADD132SD,
  2345. A_VFNMADD132SS,
  2346. A_VFNMADD213PD,
  2347. A_VFNMADD213PS,
  2348. A_VFNMADD213SD,
  2349. A_VFNMADD213SS,
  2350. A_VFNMADD231PD,
  2351. A_VFNMADD231PS,
  2352. A_VFNMADD231SD,
  2353. A_VFNMADD231SS,
  2354. A_VFNMSUB132PD,
  2355. A_VFNMSUB132PS,
  2356. A_VFNMSUB132SD,
  2357. A_VFNMSUB132SS,
  2358. A_VFNMSUB213PD,
  2359. A_VFNMSUB213PS,
  2360. A_VFNMSUB213SD,
  2361. A_VFNMSUB213SS,
  2362. A_VFNMSUB231PD,
  2363. A_VFNMSUB231PS,
  2364. A_VFNMSUB231SD,
  2365. A_VFNMSUB231SS],[S_NO]) and
  2366. { we mix single and double opperations here because we assume that the compiler
  2367. generates vmovapd only after double operations and vmovaps only after single operations }
  2368. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2369. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2370. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2371. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2372. begin
  2373. TransferUsedRegs(TmpUsedRegs);
  2374. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2375. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2376. begin
  2377. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2378. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2379. RemoveCurrentP(p)
  2380. else
  2381. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2382. RemoveInstruction(hp2);
  2383. end;
  2384. end
  2385. else if (hp1.typ = ait_instruction) and
  2386. (((taicpu(p).opcode=A_MOVAPS) and
  2387. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2388. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2389. ((taicpu(p).opcode=A_MOVAPD) and
  2390. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2391. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2392. ) and
  2393. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2394. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2395. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2396. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2397. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2398. { change
  2399. movapX reg,reg2
  2400. addsX/subsX/... reg3, reg2
  2401. movapX reg2,reg
  2402. to
  2403. addsX/subsX/... reg3,reg
  2404. }
  2405. begin
  2406. TransferUsedRegs(TmpUsedRegs);
  2407. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2408. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2409. begin
  2410. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2411. debug_op2str(taicpu(p).opcode)+' '+
  2412. debug_op2str(taicpu(hp1).opcode)+' '+
  2413. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2414. { we cannot eliminate the first move if
  2415. the operations uses the same register for source and dest }
  2416. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2417. { Remember that hp1 is not necessarily the immediate
  2418. next instruction }
  2419. RemoveCurrentP(p);
  2420. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2421. RemoveInstruction(hp2);
  2422. result:=true;
  2423. end;
  2424. end
  2425. else if (hp1.typ = ait_instruction) and
  2426. (((taicpu(p).opcode=A_VMOVAPD) and
  2427. (taicpu(hp1).opcode=A_VCOMISD)) or
  2428. ((taicpu(p).opcode=A_VMOVAPS) and
  2429. ((taicpu(hp1).opcode=A_VCOMISS))
  2430. )
  2431. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2432. { change
  2433. movapX reg,reg1
  2434. vcomisX reg1,reg1
  2435. to
  2436. vcomisX reg,reg
  2437. }
  2438. begin
  2439. TransferUsedRegs(TmpUsedRegs);
  2440. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2441. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2442. begin
  2443. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2444. debug_op2str(taicpu(p).opcode)+' '+
  2445. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2446. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2447. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2448. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2449. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2450. RemoveCurrentP(p);
  2451. result:=true;
  2452. exit;
  2453. end;
  2454. end
  2455. end;
  2456. end;
  2457. end;
  2458. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2459. var
  2460. hp1 : tai;
  2461. begin
  2462. result:=false;
  2463. { replace
  2464. V<Op>X %mreg1,%mreg2,%mreg3
  2465. VMovX %mreg3,%mreg4
  2466. dealloc %mreg3
  2467. by
  2468. V<Op>X %mreg1,%mreg2,%mreg4
  2469. ?
  2470. }
  2471. if GetNextInstruction(p,hp1) and
  2472. { we mix single and double operations here because we assume that the compiler
  2473. generates vmovapd only after double operations and vmovaps only after single operations }
  2474. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2475. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2476. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2477. begin
  2478. TransferUsedRegs(TmpUsedRegs);
  2479. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2480. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2481. begin
  2482. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2483. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2484. RemoveInstruction(hp1);
  2485. result:=true;
  2486. end;
  2487. end;
  2488. end;
  2489. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2490. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2491. begin
  2492. Result := False;
  2493. { For safety reasons, only check for exact register matches }
  2494. { Check base register }
  2495. if (ref.base = AOldReg) then
  2496. begin
  2497. ref.base := ANewReg;
  2498. Result := True;
  2499. end;
  2500. { Check index register }
  2501. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2502. begin
  2503. ref.index := ANewReg;
  2504. Result := True;
  2505. end;
  2506. end;
  2507. { Replaces all references to AOldReg in an operand to ANewReg }
  2508. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2509. var
  2510. OldSupReg, NewSupReg: TSuperRegister;
  2511. OldSubReg, NewSubReg: TSubRegister;
  2512. OldRegType: TRegisterType;
  2513. ThisOper: POper;
  2514. begin
  2515. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2516. Result := False;
  2517. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2518. InternalError(2020011801);
  2519. OldSupReg := getsupreg(AOldReg);
  2520. OldSubReg := getsubreg(AOldReg);
  2521. OldRegType := getregtype(AOldReg);
  2522. NewSupReg := getsupreg(ANewReg);
  2523. NewSubReg := getsubreg(ANewReg);
  2524. if OldRegType <> getregtype(ANewReg) then
  2525. InternalError(2020011802);
  2526. if OldSubReg <> NewSubReg then
  2527. InternalError(2020011803);
  2528. case ThisOper^.typ of
  2529. top_reg:
  2530. if (
  2531. (ThisOper^.reg = AOldReg) or
  2532. (
  2533. (OldRegType = R_INTREGISTER) and
  2534. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2535. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2536. (
  2537. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2538. {$ifndef x86_64}
  2539. and (
  2540. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2541. don't have an 8-bit representation }
  2542. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2543. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2544. )
  2545. {$endif x86_64}
  2546. )
  2547. )
  2548. ) then
  2549. begin
  2550. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2551. Result := True;
  2552. end;
  2553. top_ref:
  2554. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2555. Result := True;
  2556. else
  2557. ;
  2558. end;
  2559. end;
  2560. { Replaces all references to AOldReg in an instruction to ANewReg }
  2561. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2562. const
  2563. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2564. var
  2565. OperIdx: Integer;
  2566. begin
  2567. Result := False;
  2568. for OperIdx := 0 to p.ops - 1 do
  2569. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2570. begin
  2571. { The shift and rotate instructions can only use CL }
  2572. if not (
  2573. (OperIdx = 0) and
  2574. { This second condition just helps to avoid unnecessarily
  2575. calling MatchInstruction for 10 different opcodes }
  2576. (p.oper[0]^.reg = NR_CL) and
  2577. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2578. ) then
  2579. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2580. end
  2581. else if p.oper[OperIdx]^.typ = top_ref then
  2582. { It's okay to replace registers in references that get written to }
  2583. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2584. end;
  2585. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2586. begin
  2587. Result :=
  2588. (ref^.index = NR_NO) and
  2589. (
  2590. {$ifdef x86_64}
  2591. (
  2592. (ref^.base = NR_RIP) and
  2593. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2594. ) or
  2595. {$endif x86_64}
  2596. (ref^.refaddr = addr_full) or
  2597. (ref^.base = NR_STACK_POINTER_REG) or
  2598. (ref^.base = current_procinfo.framepointer)
  2599. );
  2600. end;
  2601. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2602. var
  2603. l: asizeint;
  2604. begin
  2605. Result := False;
  2606. { Should have been checked previously }
  2607. if p.opcode <> A_LEA then
  2608. InternalError(2020072501);
  2609. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2610. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2611. not(cs_opt_size in current_settings.optimizerswitches) then
  2612. exit;
  2613. with p.oper[0]^.ref^ do
  2614. begin
  2615. if (base <> p.oper[1]^.reg) or
  2616. (index <> NR_NO) or
  2617. assigned(symbol) then
  2618. exit;
  2619. l:=offset;
  2620. if (l=1) and UseIncDec then
  2621. begin
  2622. p.opcode:=A_INC;
  2623. p.loadreg(0,p.oper[1]^.reg);
  2624. p.ops:=1;
  2625. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2626. end
  2627. else if (l=-1) and UseIncDec then
  2628. begin
  2629. p.opcode:=A_DEC;
  2630. p.loadreg(0,p.oper[1]^.reg);
  2631. p.ops:=1;
  2632. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2633. end
  2634. else
  2635. begin
  2636. if (l<0) and (l<>-2147483648) then
  2637. begin
  2638. p.opcode:=A_SUB;
  2639. p.loadConst(0,-l);
  2640. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2641. end
  2642. else
  2643. begin
  2644. p.opcode:=A_ADD;
  2645. p.loadConst(0,l);
  2646. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2647. end;
  2648. end;
  2649. end;
  2650. Result := True;
  2651. end;
  2652. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2653. var
  2654. CurrentReg, ReplaceReg: TRegister;
  2655. begin
  2656. Result := False;
  2657. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2658. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2659. case hp.opcode of
  2660. A_FSTSW, A_FNSTSW,
  2661. A_IN, A_INS, A_OUT, A_OUTS,
  2662. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2663. { These routines have explicit operands, but they are restricted in
  2664. what they can be (e.g. IN and OUT can only read from AL, AX or
  2665. EAX. }
  2666. Exit;
  2667. A_IMUL:
  2668. begin
  2669. { The 1-operand version writes to implicit registers
  2670. The 2-operand version reads from the first operator, and reads
  2671. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2672. the 3-operand version reads from a register that it doesn't write to
  2673. }
  2674. case hp.ops of
  2675. 1:
  2676. if (
  2677. (
  2678. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2679. ) or
  2680. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2681. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2682. begin
  2683. Result := True;
  2684. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2685. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2686. end;
  2687. 2:
  2688. { Only modify the first parameter }
  2689. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2690. begin
  2691. Result := True;
  2692. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2693. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2694. end;
  2695. 3:
  2696. { Only modify the second parameter }
  2697. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2698. begin
  2699. Result := True;
  2700. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2701. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2702. end;
  2703. else
  2704. InternalError(2020012901);
  2705. end;
  2706. end;
  2707. else
  2708. if (hp.ops > 0) and
  2709. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2710. begin
  2711. Result := True;
  2712. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2713. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2714. end;
  2715. end;
  2716. end;
  2717. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2718. var
  2719. hp2, hp_regalloc: tai;
  2720. p_SourceReg, p_TargetReg: TRegister;
  2721. begin
  2722. Result := False;
  2723. { Backward optimisation. If we have:
  2724. func. %reg1,%reg2
  2725. mov %reg2,%reg3
  2726. (dealloc %reg2)
  2727. Change to:
  2728. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2729. Perform similar optimisations with 1, 3 and 4-operand instructions
  2730. that only have one output.
  2731. }
  2732. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2733. begin
  2734. p_SourceReg := taicpu(p).oper[0]^.reg;
  2735. p_TargetReg := taicpu(p).oper[1]^.reg;
  2736. TransferUsedRegs(TmpUsedRegs);
  2737. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2738. GetLastInstruction(p, hp2) and
  2739. (hp2.typ = ait_instruction) and
  2740. { Have to make sure it's an instruction that only reads from
  2741. the first operands and only writes (not reads or modifies) to
  2742. the last one; in essence, a pure function such as BSR, POPCNT
  2743. or ANDN }
  2744. (
  2745. (
  2746. (taicpu(hp2).ops = 1) and
  2747. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2748. ) or
  2749. (
  2750. (taicpu(hp2).ops = 2) and
  2751. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2752. ) or
  2753. (
  2754. (taicpu(hp2).ops = 3) and
  2755. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2756. ) or
  2757. (
  2758. (taicpu(hp2).ops = 4) and
  2759. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2760. )
  2761. ) and
  2762. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2763. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2764. begin
  2765. case taicpu(hp2).opcode of
  2766. A_FSTSW, A_FNSTSW,
  2767. A_IN, A_INS, A_OUT, A_OUTS,
  2768. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2769. { These routines have explicit operands, but they are restricted in
  2770. what they can be (e.g. IN and OUT can only read from AL, AX or
  2771. EAX. }
  2772. ;
  2773. else
  2774. begin
  2775. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2776. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2777. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2778. if Assigned(hp_regalloc) then
  2779. begin
  2780. Asml.Remove(hp_regalloc);
  2781. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2782. begin
  2783. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2784. hp_regalloc.Free;
  2785. end
  2786. else
  2787. { If the register is not explicitly deallocated, it's
  2788. being reused, so move the allocation to after func. }
  2789. AsmL.InsertAfter(hp_regalloc, hp2);
  2790. end;
  2791. if not RegInInstruction(p_TargetReg, hp2) then
  2792. begin
  2793. TransferUsedRegs(TmpUsedRegs);
  2794. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2795. end;
  2796. { Actually make the changes }
  2797. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2798. RemoveCurrentp(p, hp1);
  2799. { If the Func was another MOV instruction, we might get
  2800. "mov %reg,%reg" that doesn't get removed in Pass 2
  2801. otherwise, so deal with it here (also do something
  2802. similar with lea (%reg),%reg}
  2803. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2804. begin
  2805. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2806. if p = hp2 then
  2807. RemoveCurrentp(p)
  2808. else
  2809. RemoveInstruction(hp2);
  2810. end;
  2811. Result := True;
  2812. Exit;
  2813. end;
  2814. end;
  2815. end;
  2816. end;
  2817. end;
  2818. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2819. begin
  2820. Result := False;
  2821. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2822. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2823. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2824. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2825. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2826. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2827. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2828. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2829. begin
  2830. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2831. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2832. Result := True;
  2833. Include(OptsToCheck, aoc_ForceNewIteration);
  2834. end;
  2835. end;
  2836. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2837. var
  2838. hp1, hp2, hp3, hp4, last_hp1: tai;
  2839. GetNextInstruction_p, DoOptimisation, TempBool: Boolean;
  2840. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2841. {$ifdef x86_64}
  2842. NewConst: TCGInt;
  2843. {$endif x86_64}
  2844. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2845. begin
  2846. if taicpu(hp1).opcode = signed_movop then
  2847. begin
  2848. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2849. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2850. end
  2851. else
  2852. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2853. end;
  2854. function GetNextHp1(const in_p: tai): Boolean;
  2855. begin
  2856. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2857. GetNextInstruction_p := GetNextInstructionUsingReg(in_p, hp1, p_TargetReg)
  2858. else
  2859. GetNextInstruction_p := GetNextInstruction(in_p, hp1);
  2860. Result := GetNextInstruction_p and (hp1.typ = ait_instruction);
  2861. end;
  2862. function TryConstMerge(var p1, p2: tai): Boolean;
  2863. var
  2864. ThisRef: TReference;
  2865. begin
  2866. Result := False;
  2867. ThisRef := taicpu(p2).oper[1]^.ref^;
  2868. { Only permit writes to the stack, since we can guarantee alignment with that }
  2869. if (ThisRef.index = NR_NO) and
  2870. (
  2871. (ThisRef.base = NR_STACK_POINTER_REG) or
  2872. (ThisRef.base = current_procinfo.framepointer)
  2873. ) then
  2874. begin
  2875. case taicpu(p).opsize of
  2876. S_B:
  2877. begin
  2878. { Word writes must be on a 2-byte boundary }
  2879. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2880. begin
  2881. { Reduce offset of second reference to see if it is sequential with the first }
  2882. Dec(ThisRef.offset, 1);
  2883. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2884. begin
  2885. { Make sure the constants aren't represented as a
  2886. negative number, as these won't merge properly }
  2887. taicpu(p1).opsize := S_W;
  2888. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2889. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2890. RemoveInstruction(p2);
  2891. Result := True;
  2892. end;
  2893. end;
  2894. end;
  2895. S_W:
  2896. begin
  2897. { Longword writes must be on a 4-byte boundary }
  2898. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2899. begin
  2900. { Reduce offset of second reference to see if it is sequential with the first }
  2901. Dec(ThisRef.offset, 2);
  2902. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2903. begin
  2904. { Make sure the constants aren't represented as a
  2905. negative number, as these won't merge properly }
  2906. taicpu(p1).opsize := S_L;
  2907. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2908. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2909. RemoveInstruction(p2);
  2910. Result := True;
  2911. end;
  2912. end;
  2913. end;
  2914. {$ifdef x86_64}
  2915. S_L:
  2916. begin
  2917. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2918. see if the constants can be encoded this way. }
  2919. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2920. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2921. { Quadword writes must be on an 8-byte boundary }
  2922. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2923. begin
  2924. { Reduce offset of second reference to see if it is sequential with the first }
  2925. Dec(ThisRef.offset, 4);
  2926. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2927. begin
  2928. { Make sure the constants aren't represented as a
  2929. negative number, as these won't merge properly }
  2930. taicpu(p1).opsize := S_Q;
  2931. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2932. taicpu(p1).oper[0]^.val := NewConst;
  2933. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2934. RemoveInstruction(p2);
  2935. Result := True;
  2936. end;
  2937. end;
  2938. end;
  2939. {$endif x86_64}
  2940. else
  2941. ;
  2942. end;
  2943. end;
  2944. end;
  2945. var
  2946. TempRegUsed, CrossJump: Boolean;
  2947. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2948. NewSize: topsize; NewOffset: asizeint;
  2949. SourceRef, TargetRef: TReference;
  2950. MovAligned, MovUnaligned: TAsmOp;
  2951. JumpTracking: TLinkedList;
  2952. begin
  2953. Result:=false;
  2954. { remove mov reg1,reg1? }
  2955. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2956. then
  2957. begin
  2958. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2959. { take care of the register (de)allocs following p }
  2960. RemoveCurrentP(p);
  2961. Result := True;
  2962. exit;
  2963. end;
  2964. { Prevent compiler warnings }
  2965. p_SourceReg := NR_NO;
  2966. p_TargetReg := NR_NO;
  2967. hp1 := nil;
  2968. if taicpu(p).oper[1]^.typ = top_reg then
  2969. begin
  2970. { Saves on a large number of dereferences }
  2971. p_TargetReg := taicpu(p).oper[1]^.reg;
  2972. TransferUsedRegs(TmpUsedRegs);
  2973. last_hp1 := p;
  2974. if GetNextHp1(p) then
  2975. while True do
  2976. begin
  2977. if (taicpu(hp1).opcode = A_AND) and
  2978. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2979. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[1]^.reg) then
  2980. begin
  2981. UpdateUsedRegsBetween(TmpUsedRegs, last_hp1, hp1);
  2982. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2983. (taicpu(hp1).oper[0]^.typ = top_const) and
  2984. (taicpu(p).opsize = taicpu(hp1).opsize) then
  2985. begin
  2986. case taicpu(p).opsize of
  2987. S_L:
  2988. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2989. begin
  2990. { Optimize out:
  2991. mov x, %reg
  2992. and ffffffffh, %reg
  2993. }
  2994. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2995. hp2 := tai(hp1.Previous);
  2996. RemoveInstruction(hp1);
  2997. //Include(OptsToCheck, aoc_ForceNewIteration);
  2998. if GetNextHp1(hp2) then
  2999. Continue
  3000. else
  3001. Exit;
  3002. end;
  3003. S_Q: { TODO: Confirm if this is even possible }
  3004. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  3005. begin
  3006. { Optimize out:
  3007. mov x, %reg
  3008. and ffffffffffffffffh, %reg
  3009. }
  3010. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  3011. hp2 := tai(hp1.Previous);
  3012. RemoveInstruction(hp1);
  3013. //Include(OptsToCheck, aoc_ForceNewIteration);
  3014. if GetNextHp1(hp2) then
  3015. Continue
  3016. else
  3017. Exit;
  3018. end;
  3019. else
  3020. ;
  3021. end;
  3022. if (
  3023. { Make sure that if a reference is used, its registers
  3024. are not modified in between }
  3025. (
  3026. (taicpu(p).oper[0]^.typ = top_reg) and
  3027. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  3028. ) or
  3029. (
  3030. (taicpu(p).oper[0]^.typ = top_ref) and
  3031. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  3032. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  3033. )
  3034. ) and
  3035. GetNextInstruction(hp1,hp2) and
  3036. MatchInstruction(hp2,A_TEST,[]) and
  3037. (
  3038. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3039. (
  3040. { If the register being tested is smaller than the one
  3041. that received a bitwise AND, permit it if the constant
  3042. fits into the smaller size }
  3043. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3044. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3045. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3046. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3047. (
  3048. (
  3049. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3050. (taicpu(hp1).oper[0]^.val <= $FF)
  3051. ) or
  3052. (
  3053. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3054. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3055. {$ifdef x86_64}
  3056. ) or
  3057. (
  3058. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3059. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3060. {$endif x86_64}
  3061. )
  3062. )
  3063. )
  3064. ) and
  3065. (
  3066. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3067. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3068. ) and
  3069. GetNextInstruction(hp2,hp3) and
  3070. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3071. (taicpu(hp3).condition in [C_E,C_NE]) then
  3072. begin
  3073. TransferUsedRegs(TmpUsedRegs);
  3074. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3075. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3076. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3077. begin
  3078. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3079. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3080. taicpu(hp1).opcode:=A_TEST;
  3081. { Shrink the TEST instruction down to the smallest possible size }
  3082. case taicpu(hp1).oper[0]^.val of
  3083. 0..255:
  3084. if (taicpu(hp1).opsize <> S_B)
  3085. {$ifndef x86_64}
  3086. and (
  3087. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3088. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3089. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3090. )
  3091. {$endif x86_64}
  3092. then
  3093. begin
  3094. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3095. { Only print debug message if the TEST instruction
  3096. is a different size before and after }
  3097. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3098. taicpu(hp1).opsize := S_B;
  3099. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3100. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3101. end;
  3102. 256..65535:
  3103. if (taicpu(hp1).opsize <> S_W) then
  3104. begin
  3105. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3106. { Only print debug message if the TEST instruction
  3107. is a different size before and after }
  3108. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3109. taicpu(hp1).opsize := S_W;
  3110. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3111. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3112. end;
  3113. {$ifdef x86_64}
  3114. 65536..$7FFFFFFF:
  3115. if (taicpu(hp1).opsize <> S_L) then
  3116. begin
  3117. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3118. { Only print debug message if the TEST instruction
  3119. is a different size before and after }
  3120. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3121. taicpu(hp1).opsize := S_L;
  3122. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3123. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3124. end;
  3125. {$endif x86_64}
  3126. else
  3127. ;
  3128. end;
  3129. RemoveInstruction(hp2);
  3130. RemoveCurrentP(p);
  3131. Result:=true;
  3132. exit;
  3133. end;
  3134. end;
  3135. end;
  3136. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3137. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3138. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  3139. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^) and
  3140. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) and
  3141. (
  3142. not (cs_opt_level3 in current_settings.optimizerswitches) or
  3143. (taicpu(hp1).oper[0]^.typ = top_const) or
  3144. not RegModifiedBetween(taicpu(hp1).oper[0]^.reg, p, hp1)
  3145. ) then
  3146. begin
  3147. { With:
  3148. mov %reg1,%reg2
  3149. ...
  3150. and %reg1,%reg2
  3151. Or:
  3152. mov $x,%reg2
  3153. ...
  3154. and $x,%reg2
  3155. Remove the 'and' instruction
  3156. }
  3157. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 4 done',hp1);
  3158. hp2 := tai(hp1.Previous);
  3159. RemoveInstruction(hp1);
  3160. //Include(OptsToCheck, aoc_ForceNewIteration);
  3161. if GetNextHp1(hp2) then
  3162. Continue
  3163. else
  3164. Exit;
  3165. end;
  3166. if IsMOVZXAcceptable and
  3167. (taicpu(p).oper[0]^.typ <> top_const) then { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3168. begin
  3169. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3170. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3171. case taicpu(p).opsize of
  3172. S_B:
  3173. if (taicpu(hp1).oper[0]^.val = $ff) then
  3174. begin
  3175. { Convert:
  3176. movb x, %regl movb x, %regl
  3177. andw ffh, %regw andl ffh, %regd
  3178. To:
  3179. movzbw x, %regd movzbl x, %regd
  3180. (Identical registers, just different sizes)
  3181. }
  3182. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3183. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3184. case taicpu(hp1).opsize of
  3185. S_W: NewSize := S_BW;
  3186. S_L: NewSize := S_BL;
  3187. {$ifdef x86_64}
  3188. S_Q: NewSize := S_BQ;
  3189. {$endif x86_64}
  3190. else
  3191. InternalError(2018011510);
  3192. end;
  3193. end
  3194. else
  3195. NewSize := S_NO;
  3196. S_W:
  3197. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3198. begin
  3199. { Convert:
  3200. movw x, %regw
  3201. andl ffffh, %regd
  3202. To:
  3203. movzwl x, %regd
  3204. (Identical registers, just different sizes)
  3205. }
  3206. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3207. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3208. case taicpu(hp1).opsize of
  3209. S_L: NewSize := S_WL;
  3210. {$ifdef x86_64}
  3211. S_Q: NewSize := S_WQ;
  3212. {$endif x86_64}
  3213. else
  3214. InternalError(2018011511);
  3215. end;
  3216. end
  3217. else
  3218. NewSize := S_NO;
  3219. else
  3220. NewSize := S_NO;
  3221. end;
  3222. if NewSize <> S_NO then
  3223. begin
  3224. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3225. { The actual optimization }
  3226. taicpu(p).opcode := A_MOVZX;
  3227. taicpu(p).changeopsize(NewSize);
  3228. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3229. { Make sure we deal with any reference counts that were increased }
  3230. if taicpu(hp1).oper[1]^.typ = top_ref then
  3231. begin
  3232. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3233. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3234. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3235. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3236. end;
  3237. { Safeguard if "and" is followed by a conditional command }
  3238. TransferUsedRegs(TmpUsedRegs);
  3239. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3240. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3241. begin
  3242. { At this point, the "and" command is effectively equivalent to
  3243. "test %reg,%reg". This will be handled separately by the
  3244. Peephole Optimizer. [Kit] }
  3245. DebugMsg(SPeepholeOptimization + PreMessage +
  3246. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3247. end
  3248. else
  3249. begin
  3250. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3251. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3252. RemoveInstruction(hp1);
  3253. end;
  3254. Result := True;
  3255. Exit;
  3256. { Go through DeepMOVOpt again (jump to "while True do") }
  3257. Continue;
  3258. end;
  3259. end;
  3260. end;
  3261. if taicpu(p).oper[0]^.typ = top_reg then
  3262. begin
  3263. p_SourceReg := taicpu(p).oper[0]^.reg;
  3264. { Look for:
  3265. mov %reg1,%reg2
  3266. ??? %reg2,r/m
  3267. Change to:
  3268. mov %reg1,%reg2
  3269. ??? %reg1,r/m
  3270. }
  3271. if RegReadByInstruction(p_TargetReg, hp1) and
  3272. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3273. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3274. begin
  3275. { A change has occurred, just not in p }
  3276. Include(OptsToCheck, aoc_ForceNewIteration);
  3277. TransferUsedRegs(TmpUsedRegs);
  3278. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3279. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3280. { Just in case something didn't get modified (e.g. an
  3281. implicit register) }
  3282. not RegReadByInstruction(p_TargetReg, hp1) then
  3283. begin
  3284. { We can remove the original MOV }
  3285. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3286. RemoveCurrentP(p);
  3287. { UsedRegs got updated by RemoveCurrentp }
  3288. Result := True;
  3289. Exit;
  3290. end;
  3291. { If we know a MOV instruction has become a null operation, we might as well
  3292. get rid of it now to save time. }
  3293. if (taicpu(hp1).opcode = A_MOV) and
  3294. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3295. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3296. { Just being a register is enough to confirm it's a null operation }
  3297. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3298. begin
  3299. Result := True;
  3300. { Speed-up to reduce a pipeline stall... if we had something like...
  3301. movl %eax,%edx
  3302. movw %dx,%ax
  3303. ... the second instruction would change to movw %ax,%ax, but
  3304. given that it is now %ax that's active rather than %eax,
  3305. penalties might occur due to a partial register write, so instead,
  3306. change it to a MOVZX instruction when optimising for speed.
  3307. }
  3308. if not (cs_opt_size in current_settings.optimizerswitches) and
  3309. IsMOVZXAcceptable and
  3310. (taicpu(hp1).opsize < taicpu(p).opsize)
  3311. {$ifdef x86_64}
  3312. { operations already implicitly set the upper 64 bits to zero }
  3313. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3314. {$endif x86_64}
  3315. then
  3316. begin
  3317. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3318. case taicpu(p).opsize of
  3319. S_W:
  3320. if taicpu(hp1).opsize = S_B then
  3321. taicpu(hp1).opsize := S_BL
  3322. else
  3323. InternalError(2020012911);
  3324. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3325. case taicpu(hp1).opsize of
  3326. S_B:
  3327. taicpu(hp1).opsize := S_BL;
  3328. S_W:
  3329. taicpu(hp1).opsize := S_WL;
  3330. else
  3331. InternalError(2020012912);
  3332. end;
  3333. else
  3334. InternalError(2020012910);
  3335. end;
  3336. taicpu(hp1).opcode := A_MOVZX;
  3337. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3338. end
  3339. else
  3340. begin
  3341. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3342. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3343. RemoveInstruction(hp1);
  3344. { The instruction after what was hp1 is now the immediate next instruction,
  3345. so we can continue to make optimisations if it's present }
  3346. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3347. Exit;
  3348. hp1 := hp2;
  3349. end;
  3350. end;
  3351. end;
  3352. {$ifdef x86_64}
  3353. { Change:
  3354. movl %reg1l,%reg2l
  3355. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3356. To:
  3357. movl %reg1l,%reg2l
  3358. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3359. If %reg1 = %reg3, convert to:
  3360. movl %reg1l,%reg2l
  3361. andl %reg1l,%reg1l
  3362. }
  3363. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3364. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3365. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3366. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg) then
  3367. begin
  3368. TransferUsedRegs(TmpUsedRegs);
  3369. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3370. taicpu(hp1).opsize := S_L;
  3371. taicpu(hp1).loadreg(0, p_SourceReg);
  3372. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3373. AllocRegBetween(p_SourceReg, p, hp1, UsedRegs);
  3374. if (p_SourceReg = taicpu(hp1).oper[1]^.reg) then
  3375. begin
  3376. { %reg1 = %reg3 }
  3377. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3378. taicpu(hp1).opcode := A_AND;
  3379. { We may be able to do more and replace references
  3380. to %reg2q with %reg1q etc. }
  3381. if (cs_opt_level3 in current_settings.optimizerswitches) and
  3382. { p_TargetReg is not used between, otherwise the earlier
  3383. GetNextInstructionUsingReg would have stopped sooner }
  3384. DoZeroUpper32Opt(p,hp1) then
  3385. begin
  3386. Result := True;
  3387. Exit;
  3388. end;
  3389. end
  3390. else
  3391. begin
  3392. { %reg1 <> %reg3 }
  3393. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3394. end;
  3395. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3396. begin
  3397. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3398. RemoveCurrentP(p);
  3399. Result := True;
  3400. Exit;
  3401. end
  3402. else
  3403. begin
  3404. { Initial instruction wasn't actually changed }
  3405. Include(OptsToCheck, aoc_ForceNewIteration);
  3406. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3407. appears below since %reg1 has technically changed }
  3408. if taicpu(hp1).opcode = A_AND then
  3409. Exit;
  3410. end;
  3411. end;
  3412. {
  3413. If we have the following already in the code...
  3414. movl %reg1l,%reg2l
  3415. andl %reg1l,%reg1l
  3416. ...we may be able to do more and replace references to
  3417. %reg2q with %reg1q etc. (program flow won't reach this
  3418. point if the second instruction was originally a MOV
  3419. and just got changed to AND)
  3420. }
  3421. if (cs_opt_level3 in current_settings.optimizerswitches) and
  3422. (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_AND,[S_L]) and
  3423. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3424. { p_TargetReg is not used between, otherwise the earlier
  3425. GetNextInstructionUsingReg would have stopped sooner }
  3426. MatchOperand(taicpu(hp1).oper[1]^, p_SourceReg) and
  3427. (
  3428. MatchOperand(taicpu(hp1).oper[0]^, p_SourceReg) or
  3429. MatchOperand(taicpu(hp1).oper[0]^, $ffffffff)
  3430. ) and
  3431. DoZeroUpper32Opt(p,hp1) then
  3432. begin
  3433. Result := True;
  3434. Exit;
  3435. end;
  3436. {$endif x86_64}
  3437. end
  3438. else if taicpu(p).oper[0]^.typ = top_const then
  3439. begin
  3440. if (taicpu(hp1).opcode = A_OR) and
  3441. (taicpu(p).oper[1]^.typ = top_reg) and
  3442. MatchOperand(taicpu(p).oper[0]^, 0) and
  3443. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3444. begin
  3445. { mov 0, %reg
  3446. or ###,%reg
  3447. Change to (only if the flags are not used):
  3448. mov ###,%reg
  3449. }
  3450. TransferUsedRegs(TmpUsedRegs);
  3451. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3452. DoOptimisation := True;
  3453. { Even if the flags are used, we might be able to do the optimisation
  3454. if the conditions are predictable }
  3455. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3456. begin
  3457. { Only perform if ### = %reg (the same register) or equal to 0,
  3458. so %reg is guaranteed to still have a value of zero }
  3459. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3460. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3461. begin
  3462. hp2 := hp1;
  3463. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3464. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3465. GetNextInstruction(hp2, hp3) do
  3466. begin
  3467. { Don't continue modifying if the flags state is getting changed }
  3468. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3469. Break;
  3470. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3471. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3472. begin
  3473. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3474. begin
  3475. { Condition is always true }
  3476. case taicpu(hp3).opcode of
  3477. A_Jcc:
  3478. begin
  3479. { Check for jump shortcuts before we destroy the condition }
  3480. hp4 := hp3;
  3481. DoJumpOptimizations(hp3, TempBool);
  3482. { Make sure hp3 hasn't changed }
  3483. if (hp4 = hp3) then
  3484. begin
  3485. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3486. MakeUnconditional(taicpu(hp3));
  3487. end;
  3488. Result := True;
  3489. end;
  3490. A_CMOVcc:
  3491. begin
  3492. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3493. taicpu(hp3).opcode := A_MOV;
  3494. taicpu(hp3).condition := C_None;
  3495. Result := True;
  3496. end;
  3497. A_SETcc:
  3498. begin
  3499. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3500. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3501. taicpu(hp3).opcode := A_MOV;
  3502. taicpu(hp3).ops := 2;
  3503. taicpu(hp3).condition := C_None;
  3504. taicpu(hp3).opsize := S_B;
  3505. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3506. taicpu(hp3).loadconst(0, 1);
  3507. Result := True;
  3508. end;
  3509. else
  3510. InternalError(2021090701);
  3511. end;
  3512. end
  3513. 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
  3514. begin
  3515. { Condition is always false }
  3516. case taicpu(hp3).opcode of
  3517. A_Jcc:
  3518. begin
  3519. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3520. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3521. RemoveInstruction(hp3);
  3522. Result := True;
  3523. { Since hp3 was deleted, hp2 must not be updated }
  3524. Continue;
  3525. end;
  3526. A_CMOVcc:
  3527. begin
  3528. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3529. RemoveInstruction(hp3);
  3530. Result := True;
  3531. { Since hp3 was deleted, hp2 must not be updated }
  3532. Continue;
  3533. end;
  3534. A_SETcc:
  3535. begin
  3536. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3537. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3538. taicpu(hp3).opcode := A_MOV;
  3539. taicpu(hp3).ops := 2;
  3540. taicpu(hp3).condition := C_None;
  3541. taicpu(hp3).opsize := S_B;
  3542. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3543. taicpu(hp3).loadconst(0, 0);
  3544. Result := True;
  3545. end;
  3546. else
  3547. InternalError(2021090702);
  3548. end;
  3549. end
  3550. else
  3551. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3552. DoOptimisation := False;
  3553. end;
  3554. hp2 := hp3;
  3555. end;
  3556. if DoOptimisation then
  3557. begin
  3558. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3559. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3560. { Flags are still in use - don't optimise }
  3561. DoOptimisation := False;
  3562. end;
  3563. end
  3564. else
  3565. DoOptimisation := False;
  3566. end;
  3567. if DoOptimisation then
  3568. begin
  3569. {$ifdef x86_64}
  3570. { OR only supports 32-bit sign-extended constants for 64-bit
  3571. instructions, so compensate for this if the constant is
  3572. encoded as a value greater than or equal to 2^31 }
  3573. if (taicpu(hp1).opsize = S_Q) and
  3574. (taicpu(hp1).oper[0]^.typ = top_const) and
  3575. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3576. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3577. {$endif x86_64}
  3578. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3579. taicpu(hp1).opcode := A_MOV;
  3580. RemoveCurrentP(p);
  3581. Result := True;
  3582. Exit;
  3583. end;
  3584. end;
  3585. end
  3586. else if
  3587. { oper[0] is a reference }
  3588. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) then
  3589. begin
  3590. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  3591. begin
  3592. if ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3593. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3594. ) or
  3595. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3596. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3597. )
  3598. ) and
  3599. not RegModifiedBetween(Taicpu(hp1).oper[1]^.reg, p, hp1) then
  3600. { mov ref,reg1
  3601. lea (reg1,reg2),reg2
  3602. to
  3603. add ref,reg2 }
  3604. begin
  3605. TransferUsedRegs(TmpUsedRegs);
  3606. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3607. { If the flags register is in use, don't change the instruction to an
  3608. ADD otherwise this will scramble the flags. [Kit] }
  3609. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3610. { reg1 may not be used afterwards }
  3611. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3612. begin
  3613. Taicpu(hp1).opcode:=A_ADD;
  3614. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3615. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3616. RemoveCurrentp(p);
  3617. result:=true;
  3618. exit;
  3619. end;
  3620. end;
  3621. { If the LEA instruction can be converted into an arithmetic instruction,
  3622. it may be possible to then fold it in the next optimisation. }
  3623. if ConvertLEA(taicpu(hp1)) then
  3624. Include(OptsToCheck, aoc_ForceNewIteration);
  3625. end;
  3626. {
  3627. mov ref,reg0
  3628. <op> reg0,reg1
  3629. dealloc reg0
  3630. to
  3631. <op> ref,reg1
  3632. }
  3633. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3634. (taicpu(hp1).oper[0]^.reg = p_TargetReg) and
  3635. MatchInstruction(hp1, [A_AND, A_OR, A_XOR, A_ADD, A_SUB, A_CMP, A_TEST, A_CMOVcc, A_BSR, A_BSF, A_POPCNT, A_LZCNT], [taicpu(p).opsize]) and
  3636. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, p_TargetReg) and
  3637. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3638. begin
  3639. TransferUsedRegs(TmpUsedRegs);
  3640. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3641. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3642. begin
  3643. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  3644. { loadref increases the reference count, so decrement it again }
  3645. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3646. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3647. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3648. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3649. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3650. { See if we can remove the allocation of reg0 }
  3651. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3652. TryRemoveRegAlloc(p_TargetReg, p, hp1);
  3653. RemoveCurrentp(p);
  3654. Result:=true;
  3655. exit;
  3656. end;
  3657. end;
  3658. end;
  3659. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3660. overwrites the original destination register. e.g.
  3661. movl ###,%reg2d
  3662. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3663. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3664. }
  3665. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3666. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3667. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3668. begin
  3669. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3670. begin
  3671. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3672. case taicpu(p).oper[0]^.typ of
  3673. top_const:
  3674. { We have something like:
  3675. movb $x, %regb
  3676. movzbl %regb,%regd
  3677. Change to:
  3678. movl $x, %regd
  3679. }
  3680. begin
  3681. case taicpu(hp1).opsize of
  3682. S_BW:
  3683. begin
  3684. convert_mov_value(A_MOVSX, $FF);
  3685. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3686. taicpu(p).opsize := S_W;
  3687. end;
  3688. S_BL:
  3689. begin
  3690. convert_mov_value(A_MOVSX, $FF);
  3691. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3692. taicpu(p).opsize := S_L;
  3693. end;
  3694. S_WL:
  3695. begin
  3696. convert_mov_value(A_MOVSX, $FFFF);
  3697. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3698. taicpu(p).opsize := S_L;
  3699. end;
  3700. {$ifdef x86_64}
  3701. S_BQ:
  3702. begin
  3703. convert_mov_value(A_MOVSX, $FF);
  3704. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3705. taicpu(p).opsize := S_Q;
  3706. end;
  3707. S_WQ:
  3708. begin
  3709. convert_mov_value(A_MOVSX, $FFFF);
  3710. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3711. taicpu(p).opsize := S_Q;
  3712. end;
  3713. S_LQ:
  3714. begin
  3715. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3716. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3717. taicpu(p).opsize := S_Q;
  3718. end;
  3719. {$endif x86_64}
  3720. else
  3721. { If hp1 was a MOV instruction, it should have been
  3722. optimised already }
  3723. InternalError(2020021001);
  3724. end;
  3725. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3726. RemoveInstruction(hp1);
  3727. Result := True;
  3728. Exit;
  3729. end;
  3730. top_ref:
  3731. begin
  3732. { We have something like:
  3733. movb mem, %regb
  3734. movzbl %regb,%regd
  3735. Change to:
  3736. movzbl mem, %regd
  3737. }
  3738. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3739. begin
  3740. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3741. taicpu(p).opcode := taicpu(hp1).opcode;
  3742. taicpu(p).opsize := taicpu(hp1).opsize;
  3743. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3744. RemoveInstruction(hp1);
  3745. Result := True;
  3746. Exit;
  3747. end;
  3748. end;
  3749. else
  3750. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3751. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3752. Exit;
  3753. end;
  3754. end
  3755. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3756. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3757. optimised }
  3758. else
  3759. begin
  3760. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3761. RemoveCurrentP(p);
  3762. Result := True;
  3763. Exit;
  3764. end;
  3765. end;
  3766. if (taicpu(hp1).opcode = A_MOV) and
  3767. (
  3768. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  3769. {$ifdef x86_64}
  3770. or (
  3771. { Permit zero extension from 32- to 64-bit when writing
  3772. a constant (it will be checked to see if it fits into
  3773. a signed 32-bit integer) }
  3774. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3775. (
  3776. { Valid situations... writing an unsigned 32-bit
  3777. immediate, or the destination is a 64-bit register }
  3778. (taicpu(p).oper[0]^.typ = top_const) or
  3779. (taicpu(hp1).oper[1]^.typ = top_reg)
  3780. ) and
  3781. (taicpu(hp1).oper[0]^.typ = top_reg) and
  3782. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg)
  3783. )
  3784. {$endif x86_64}
  3785. ) then
  3786. begin
  3787. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3788. TransferUsedRegs(TmpUsedRegs);
  3789. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3790. { we have
  3791. mov x, %treg
  3792. mov %treg, y
  3793. }
  3794. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3795. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3796. begin
  3797. { we've got
  3798. mov x, %treg
  3799. mov %treg, y
  3800. with %treg is not used after }
  3801. case taicpu(p).oper[0]^.typ Of
  3802. { top_reg is covered by DeepMOVOpt }
  3803. top_const:
  3804. begin
  3805. { change
  3806. mov const, %treg
  3807. mov %treg, y
  3808. to
  3809. mov const, y
  3810. }
  3811. {$ifdef x86_64}
  3812. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3813. (
  3814. { For 32-to-64-bit zero-extension, the immediate
  3815. must be between 0 and 2^31 - 1}
  3816. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3817. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3818. ) or
  3819. (
  3820. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3821. (
  3822. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3823. )
  3824. ) then
  3825. {$endif x86_64}
  3826. begin
  3827. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3828. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3829. RemoveCurrentP(p);
  3830. Result := True;
  3831. Exit;
  3832. end;
  3833. end;
  3834. top_ref:
  3835. case taicpu(hp1).oper[1]^.typ of
  3836. top_reg:
  3837. { change
  3838. mov mem, %treg
  3839. mov %treg, %reg
  3840. to
  3841. mov mem, %reg"
  3842. }
  3843. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3844. begin
  3845. {$ifdef x86_64}
  3846. { If zero extending from 32-bit to 64-bit,
  3847. we have to make sure the replaced
  3848. register is the right size }
  3849. taicpu(p).loadreg(1, newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),getsubreg(p_TargetReg)));
  3850. {$else}
  3851. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3852. {$endif x86_64}
  3853. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3854. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3855. RemoveInstruction(hp1);
  3856. Result := True;
  3857. Exit;
  3858. end
  3859. else if
  3860. { Make sure that if a reference is used, its
  3861. registers are not modified in between }
  3862. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3863. begin
  3864. if (taicpu(p).oper[0]^.ref^.base <> NR_NO){$ifdef x86_64} and (taicpu(p).oper[0]^.ref^.base <> NR_RIP){$endif x86_64} then
  3865. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3866. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3867. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3868. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3869. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3870. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3871. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3872. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3873. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3874. RemoveCurrentP(p);
  3875. Result := True;
  3876. Exit;
  3877. end;
  3878. top_ref:
  3879. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3880. begin
  3881. {$ifdef x86_64}
  3882. { Look for the following to simplify:
  3883. mov x(mem1), %reg
  3884. mov %reg, y(mem2)
  3885. mov x+8(mem1), %reg
  3886. mov %reg, y+8(mem2)
  3887. Change to:
  3888. movdqu x(mem1), %xmmreg
  3889. movdqu %xmmreg, y(mem2)
  3890. ...but only as long as the memory blocks don't overlap
  3891. }
  3892. SourceRef := taicpu(p).oper[0]^.ref^;
  3893. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3894. if (taicpu(p).opsize = S_Q) and
  3895. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3896. GetNextInstruction(hp1, hp2) and
  3897. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3898. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3899. begin
  3900. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3901. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3902. Inc(SourceRef.offset, 8);
  3903. if UseAVX then
  3904. begin
  3905. MovAligned := A_VMOVDQA;
  3906. MovUnaligned := A_VMOVDQU;
  3907. end
  3908. else
  3909. begin
  3910. MovAligned := A_MOVDQA;
  3911. MovUnaligned := A_MOVDQU;
  3912. end;
  3913. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3914. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3915. begin
  3916. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3917. Inc(TargetRef.offset, 8);
  3918. if GetNextInstruction(hp2, hp3) and
  3919. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3920. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3921. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3922. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3923. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3924. begin
  3925. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3926. if NewMMReg <> NR_NO then
  3927. begin
  3928. { Remember that the offsets are 8 ahead }
  3929. if ((SourceRef.offset mod 16) = 8) and
  3930. (
  3931. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3932. (SourceRef.base = current_procinfo.framepointer) or
  3933. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3934. ) then
  3935. taicpu(p).opcode := MovAligned
  3936. else
  3937. taicpu(p).opcode := MovUnaligned;
  3938. taicpu(p).opsize := S_XMM;
  3939. taicpu(p).oper[1]^.reg := NewMMReg;
  3940. if ((TargetRef.offset mod 16) = 8) and
  3941. (
  3942. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3943. (TargetRef.base = current_procinfo.framepointer) or
  3944. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3945. ) then
  3946. taicpu(hp1).opcode := MovAligned
  3947. else
  3948. taicpu(hp1).opcode := MovUnaligned;
  3949. taicpu(hp1).opsize := S_XMM;
  3950. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3951. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3952. RemoveInstruction(hp2);
  3953. RemoveInstruction(hp3);
  3954. Result := True;
  3955. Exit;
  3956. end;
  3957. end;
  3958. end
  3959. else
  3960. begin
  3961. { See if the next references are 8 less rather than 8 greater }
  3962. Dec(SourceRef.offset, 16); { -8 the other way }
  3963. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3964. begin
  3965. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3966. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3967. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3968. GetNextInstruction(hp2, hp3) and
  3969. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3970. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3971. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3972. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3973. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3974. begin
  3975. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3976. if NewMMReg <> NR_NO then
  3977. begin
  3978. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3979. if ((SourceRef.offset mod 16) = 0) and
  3980. (
  3981. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3982. (SourceRef.base = current_procinfo.framepointer) or
  3983. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3984. ) then
  3985. taicpu(hp2).opcode := MovAligned
  3986. else
  3987. taicpu(hp2).opcode := MovUnaligned;
  3988. taicpu(hp2).opsize := S_XMM;
  3989. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3990. if ((TargetRef.offset mod 16) = 0) and
  3991. (
  3992. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3993. (TargetRef.base = current_procinfo.framepointer) or
  3994. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3995. ) then
  3996. taicpu(hp3).opcode := MovAligned
  3997. else
  3998. taicpu(hp3).opcode := MovUnaligned;
  3999. taicpu(hp3).opsize := S_XMM;
  4000. taicpu(hp3).oper[0]^.reg := NewMMReg;
  4001. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  4002. RemoveInstruction(hp1);
  4003. RemoveCurrentP(p);
  4004. Result := True;
  4005. Exit;
  4006. end;
  4007. end;
  4008. end;
  4009. end;
  4010. end;
  4011. {$endif x86_64}
  4012. end;
  4013. else
  4014. { The write target should be a reg or a ref }
  4015. InternalError(2021091601);
  4016. end;
  4017. else
  4018. ;
  4019. end;
  4020. end
  4021. else if (taicpu(p).oper[0]^.typ = top_const) and
  4022. { %treg is used afterwards, but all eventualities other
  4023. than the first MOV instruction being a constant are
  4024. covered by DeepMOVOpt, so only check for that }
  4025. (
  4026. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  4027. not (cs_opt_size in current_settings.optimizerswitches) or
  4028. (taicpu(hp1).opsize = S_B)
  4029. ) and
  4030. (
  4031. (taicpu(hp1).oper[1]^.typ=top_reg) or
  4032. (
  4033. { For 32-to-64-bit zero-extension, the immediate
  4034. must be between 0 and 2^31 - 1}
  4035. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  4036. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  4037. ) or
  4038. (
  4039. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  4040. (
  4041. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  4042. )
  4043. )
  4044. ) then
  4045. begin
  4046. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  4047. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  4048. Include(OptsToCheck, aoc_ForceNewIteration);
  4049. end;
  4050. end;
  4051. Break;
  4052. end;
  4053. end;
  4054. if taicpu(p).oper[0]^.typ = top_reg then
  4055. begin
  4056. { oper[1] is a reference }
  4057. { Saves on a large number of dereferences }
  4058. p_SourceReg := taicpu(p).oper[0]^.reg;
  4059. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  4060. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_SourceReg)
  4061. else
  4062. GetNextInstruction_p := GetNextInstruction(p, hp1);
  4063. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  4064. begin
  4065. if taicpu(p).oper[1]^.typ = top_reg then
  4066. begin
  4067. p_TargetReg := taicpu(p).oper[1]^.reg;
  4068. { Change:
  4069. movl %reg1,%reg2
  4070. ...
  4071. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  4072. ...
  4073. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  4074. To:
  4075. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  4076. ...
  4077. movl x(%reg1),%reg1
  4078. ...
  4079. movl %reg1,%regX
  4080. }
  4081. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4082. (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4083. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  4084. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  4085. not RegModifiedBetween(p_TargetReg, p, hp1) and
  4086. GetNextInstructionUsingReg(hp1, hp2, p_TargetReg) and
  4087. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  4088. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4089. not RegModifiedBetween(p_SourceReg, hp1, hp2) then
  4090. begin
  4091. SourceRef := taicpu(hp2).oper[0]^.ref^;
  4092. if RegInRef(p_TargetReg, SourceRef) and
  4093. { If %reg1 also appears in the second reference, then it will
  4094. not refer to the same memory block as the first reference }
  4095. not RegInRef(p_SourceReg, SourceRef) then
  4096. begin
  4097. { Check to see if the references match if %reg2 is changed to %reg1 }
  4098. if SourceRef.base = p_TargetReg then
  4099. SourceRef.base := p_SourceReg;
  4100. if SourceRef.index = p_TargetReg then
  4101. SourceRef.index := p_SourceReg;
  4102. { RefsEqual also checks to ensure both references are non-volatile }
  4103. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  4104. begin
  4105. taicpu(hp2).loadreg(0, p_SourceReg);
  4106. TransferUsedRegs(TmpUsedRegs);
  4107. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  4108. { Make sure the register is allocated between these instructions
  4109. even though it doesn't change value, since it may cause
  4110. optimisations on a later pass to behave incorrectly. (Fixes #41155) }
  4111. AllocRegBetween(p_SourceReg, hp1, hp2, TmpUsedRegs);
  4112. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  4113. Result := True;
  4114. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  4115. begin
  4116. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  4117. RemoveCurrentP(p);
  4118. Exit;
  4119. end
  4120. else
  4121. begin
  4122. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  4123. begin
  4124. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  4125. RemoveCurrentP(p);
  4126. Exit;
  4127. end;
  4128. end;
  4129. { If we reach this point, p and hp1 weren't actually modified,
  4130. so we can do a bit more work on this pass }
  4131. end;
  4132. end;
  4133. end;
  4134. end;
  4135. end;
  4136. end;
  4137. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  4138. { All the next optimisations require a next instruction }
  4139. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  4140. Exit;
  4141. { Change:
  4142. movl/q (ref), %reg
  4143. movd/q %reg, %xmm0
  4144. (dealloc %reg)
  4145. To:
  4146. movd/q (ref), %xmm0
  4147. }
  4148. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4149. MatchInstruction(hp1,[A_MOVD,A_VMOVD{$ifdef x86_64},A_MOVQ,A_VMOVQ{$endif x86_64}],[]) and
  4150. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^.reg) and
  4151. (taicpu(hp1).oper[1]^.typ=top_reg) and
  4152. (GetRegType(taicpu(hp1).oper[1]^.reg)=R_MMREGISTER) then
  4153. begin
  4154. TransferUsedRegs(TmpUsedRegs);
  4155. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4156. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs) then
  4157. begin
  4158. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  4159. { loadref increases the reference count, so decrement it again }
  4160. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  4161. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  4162. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  4163. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  4164. DebugMsg(SPeepholeOptimization+'Merged MOV and (V)MOVD/(V)MOVQ to eliminate intermediate register (MovMovD/Q2MovD/Q)',p);
  4165. RemoveCurrentP(p,hp1);
  4166. Result:=True;
  4167. Exit;
  4168. end;
  4169. end;
  4170. { Next instruction is also a MOV ? }
  4171. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  4172. begin
  4173. if MatchOpType(taicpu(p), top_const, top_ref) and
  4174. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4175. TryConstMerge(p, hp1) then
  4176. begin
  4177. Result := True;
  4178. { In case we have four byte writes in a row, check for 2 more
  4179. right now so we don't have to wait for another iteration of
  4180. pass 1
  4181. }
  4182. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  4183. case taicpu(p).opsize of
  4184. S_W:
  4185. begin
  4186. if GetNextInstruction(p, hp1) and
  4187. MatchInstruction(hp1, A_MOV, [S_B]) and
  4188. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4189. GetNextInstruction(hp1, hp2) and
  4190. MatchInstruction(hp2, A_MOV, [S_B]) and
  4191. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4192. { Try to merge the two bytes }
  4193. TryConstMerge(hp1, hp2) then
  4194. { Now try to merge the two words (hp2 will get deleted) }
  4195. TryConstMerge(p, hp1);
  4196. end;
  4197. S_L:
  4198. begin
  4199. { Though this only really benefits x86_64 and not i386, it
  4200. gets a potential optimisation done faster and hence
  4201. reduces the number of times OptPass1MOV is entered }
  4202. if GetNextInstruction(p, hp1) and
  4203. MatchInstruction(hp1, A_MOV, [S_W]) and
  4204. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4205. GetNextInstruction(hp1, hp2) and
  4206. MatchInstruction(hp2, A_MOV, [S_W]) and
  4207. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4208. { Try to merge the two words }
  4209. TryConstMerge(hp1, hp2) then
  4210. { This will always fail on i386, so don't bother
  4211. calling it unless we're doing x86_64 }
  4212. {$ifdef x86_64}
  4213. { Now try to merge the two longwords (hp2 will get deleted) }
  4214. TryConstMerge(p, hp1)
  4215. {$endif x86_64}
  4216. ;
  4217. end;
  4218. else
  4219. ;
  4220. end;
  4221. Exit;
  4222. end;
  4223. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4224. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4225. { mov reg1, mem1 or mov mem1, reg1
  4226. mov mem2, reg2 mov reg2, mem2}
  4227. begin
  4228. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4229. { mov reg1, mem1 or mov mem1, reg1
  4230. mov mem2, reg1 mov reg2, mem1}
  4231. begin
  4232. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4233. { Removes the second statement from
  4234. mov reg1, mem1/reg2
  4235. mov mem1/reg2, reg1 }
  4236. begin
  4237. if taicpu(p).oper[0]^.typ=top_reg then
  4238. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4239. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  4240. RemoveInstruction(hp1);
  4241. Result:=true;
  4242. if (taicpu(p).oper[1]^.typ = top_reg) then
  4243. begin
  4244. TransferUsedRegs(TmpUsedRegs);
  4245. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, p, TmpUsedRegs) then
  4246. begin
  4247. { reg2 is no longer in use }
  4248. DebugMsg(SPeepholeOptimization + 'Mov2Nop 6 done',p);
  4249. RemoveCurrentP(p);
  4250. end;
  4251. end;
  4252. exit;
  4253. end
  4254. else
  4255. begin
  4256. TransferUsedRegs(TmpUsedRegs);
  4257. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4258. if (taicpu(p).oper[1]^.typ = top_ref) and
  4259. { mov reg1, mem1
  4260. mov mem2, reg1 }
  4261. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4262. GetNextInstruction(hp1, hp2) and
  4263. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4264. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4265. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4266. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4267. { change to
  4268. mov reg1, mem1 mov reg1, mem1
  4269. mov mem2, reg1 cmp reg1, mem2
  4270. cmp mem1, reg1
  4271. }
  4272. begin
  4273. RemoveInstruction(hp2);
  4274. taicpu(hp1).opcode := A_CMP;
  4275. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4276. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4277. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4278. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4279. end;
  4280. end;
  4281. end
  4282. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4283. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4284. begin
  4285. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4286. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4287. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4288. end
  4289. else
  4290. begin
  4291. TransferUsedRegs(TmpUsedRegs);
  4292. if GetNextInstruction(hp1, hp2) and
  4293. MatchOpType(taicpu(p),top_ref,top_reg) and
  4294. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4295. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4296. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4297. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4298. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4299. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4300. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4301. { mov mem1, %reg1
  4302. mov %reg1, mem2
  4303. mov mem2, reg2
  4304. to:
  4305. mov mem1, reg2
  4306. mov reg2, mem2}
  4307. begin
  4308. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4309. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4310. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4311. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4312. RemoveInstruction(hp2);
  4313. Result := True;
  4314. end
  4315. {$ifdef i386}
  4316. { this is enabled for i386 only, as the rules to create the reg sets below
  4317. are too complicated for x86-64, so this makes this code too error prone
  4318. on x86-64
  4319. }
  4320. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4321. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4322. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4323. { mov mem1, reg1 mov mem1, reg1
  4324. mov reg1, mem2 mov reg1, mem2
  4325. mov mem2, reg2 mov mem2, reg1
  4326. to: to:
  4327. mov mem1, reg1 mov mem1, reg1
  4328. mov mem1, reg2 mov reg1, mem2
  4329. mov reg1, mem2
  4330. or (if mem1 depends on reg1
  4331. and/or if mem2 depends on reg2)
  4332. to:
  4333. mov mem1, reg1
  4334. mov reg1, mem2
  4335. mov reg1, reg2
  4336. }
  4337. begin
  4338. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4339. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4340. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4341. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4342. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4343. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4344. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4345. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4346. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4347. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4348. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4349. end
  4350. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4351. begin
  4352. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4353. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4354. end
  4355. else
  4356. begin
  4357. RemoveInstruction(hp2);
  4358. end
  4359. {$endif i386}
  4360. ;
  4361. end;
  4362. end
  4363. { movl [mem1],reg1
  4364. movl [mem1],reg2
  4365. to
  4366. movl [mem1],reg1
  4367. movl reg1,reg2
  4368. }
  4369. else if not CheckMovMov2MovMov2(p, hp1) and
  4370. { movl const1,[mem1]
  4371. movl [mem1],reg1
  4372. to
  4373. movl const1,reg1
  4374. movl reg1,[mem1]
  4375. }
  4376. MatchOpType(Taicpu(p),top_const,top_ref) and
  4377. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4378. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4379. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4380. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4381. begin
  4382. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4383. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4384. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4385. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4386. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4387. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4388. Result:=true;
  4389. exit;
  4390. end;
  4391. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4392. end;
  4393. { search further than the next instruction for a mov (as long as it's not a jump) }
  4394. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4395. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4396. (taicpu(p).oper[1]^.typ = top_reg) and
  4397. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4398. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4399. begin
  4400. { we work with hp2 here, so hp1 can be still used later on when
  4401. checking for GetNextInstruction_p }
  4402. hp3 := hp1;
  4403. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4404. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4405. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4406. TransferUsedRegs(TmpUsedRegs);
  4407. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4408. if NotFirstIteration then
  4409. JumpTracking := TLinkedList.Create
  4410. else
  4411. JumpTracking := nil;
  4412. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4413. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4414. (hp2.typ=ait_instruction) do
  4415. begin
  4416. case taicpu(hp2).opcode of
  4417. A_POP:
  4418. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4419. begin
  4420. if not CrossJump and
  4421. not RegUsedBetween(p_TargetReg, p, hp2) then
  4422. begin
  4423. { We can remove the original MOV since the register
  4424. wasn't used between it and its popping from the stack }
  4425. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4426. RemoveCurrentp(p, hp1);
  4427. Result := True;
  4428. JumpTracking.Free;
  4429. Exit;
  4430. end;
  4431. { Can't go any further }
  4432. Break;
  4433. end;
  4434. A_MOV:
  4435. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4436. ((taicpu(p).oper[0]^.typ=top_const) or
  4437. ((taicpu(p).oper[0]^.typ=top_reg) and
  4438. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4439. )
  4440. ) then
  4441. begin
  4442. { we have
  4443. mov x, %treg
  4444. mov %treg, y
  4445. }
  4446. { We don't need to call UpdateUsedRegs for every instruction between
  4447. p and hp2 because the register we're concerned about will not
  4448. become deallocated (otherwise GetNextInstructionUsingReg would
  4449. have stopped at an earlier instruction). [Kit] }
  4450. TempRegUsed :=
  4451. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4452. RegReadByInstruction(p_TargetReg, hp3) or
  4453. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4454. case taicpu(p).oper[0]^.typ Of
  4455. top_reg:
  4456. begin
  4457. { change
  4458. mov %reg, %treg
  4459. mov %treg, y
  4460. to
  4461. mov %reg, y
  4462. }
  4463. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4464. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4465. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4466. begin
  4467. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4468. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4469. if TempRegUsed then
  4470. begin
  4471. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4472. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4473. { Set the start of the next GetNextInstructionUsingRegCond search
  4474. to start at the entry right before hp2 (which is about to be removed) }
  4475. hp3 := tai(hp2.Previous);
  4476. RemoveInstruction(hp2);
  4477. Include(OptsToCheck, aoc_ForceNewIteration);
  4478. { See if there's more we can optimise }
  4479. Continue;
  4480. end
  4481. else
  4482. begin
  4483. RemoveInstruction(hp2);
  4484. { We can remove the original MOV too }
  4485. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4486. RemoveCurrentP(p, hp1);
  4487. Result:=true;
  4488. JumpTracking.Free;
  4489. Exit;
  4490. end;
  4491. end
  4492. else
  4493. begin
  4494. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4495. taicpu(hp2).loadReg(0, p_SourceReg);
  4496. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4497. { Check to see if the register also appears in the reference }
  4498. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4499. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4500. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4501. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4502. begin
  4503. { Don't remove the first instruction if the temporary register is in use }
  4504. if not TempRegUsed then
  4505. begin
  4506. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4507. RemoveCurrentP(p, hp1);
  4508. Result:=true;
  4509. JumpTracking.Free;
  4510. Exit;
  4511. end;
  4512. { No need to set Result to True here. If there's another instruction later
  4513. on that can be optimised, it will be detected when the main Pass 1 loop
  4514. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4515. hp3 := hp2;
  4516. Continue;
  4517. end;
  4518. end;
  4519. end;
  4520. top_const:
  4521. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4522. begin
  4523. { change
  4524. mov const, %treg
  4525. mov %treg, y
  4526. to
  4527. mov const, y
  4528. }
  4529. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4530. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4531. begin
  4532. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4533. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4534. if TempRegUsed then
  4535. begin
  4536. { Don't remove the first instruction if the temporary register is in use }
  4537. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4538. { No need to set Result to True. If there's another instruction later on
  4539. that can be optimised, it will be detected when the main Pass 1 loop
  4540. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4541. end
  4542. else
  4543. begin
  4544. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4545. RemoveCurrentP(p, hp1);
  4546. Result:=true;
  4547. Exit;
  4548. end;
  4549. end;
  4550. end;
  4551. else
  4552. Internalerror(2019103001);
  4553. end;
  4554. end
  4555. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4556. begin
  4557. if not CrossJump and
  4558. not RegUsedBetween(p_TargetReg, p, hp2) and
  4559. not RegReadByInstruction(p_TargetReg, hp2) then
  4560. begin
  4561. { Register is not used before it is overwritten }
  4562. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4563. RemoveCurrentp(p, hp1);
  4564. Result := True;
  4565. Exit;
  4566. end;
  4567. if (taicpu(p).oper[0]^.typ = top_const) and
  4568. (taicpu(hp2).oper[0]^.typ = top_const) then
  4569. begin
  4570. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4571. begin
  4572. { Same value - register hasn't changed }
  4573. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4574. RemoveInstruction(hp2);
  4575. Include(OptsToCheck, aoc_ForceNewIteration);
  4576. { See if there's more we can optimise }
  4577. Continue;
  4578. end;
  4579. end;
  4580. {$ifdef x86_64}
  4581. end
  4582. { Change:
  4583. movl %reg1l,%reg2l
  4584. ...
  4585. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4586. To:
  4587. movl %reg1l,%reg2l
  4588. ...
  4589. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4590. If %reg1 = %reg3, convert to:
  4591. movl %reg1l,%reg2l
  4592. ...
  4593. andl %reg1l,%reg1l
  4594. }
  4595. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4596. (taicpu(p).oper[0]^.typ = top_reg) and
  4597. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4598. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4599. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4600. begin
  4601. TempRegUsed :=
  4602. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4603. RegReadByInstruction(p_TargetReg, hp3) or
  4604. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4605. taicpu(hp2).opsize := S_L;
  4606. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4607. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4608. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4609. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4610. begin
  4611. { %reg1 = %reg3 }
  4612. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4613. taicpu(hp2).opcode := A_AND;
  4614. end
  4615. else
  4616. begin
  4617. { %reg1 <> %reg3 }
  4618. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4619. end;
  4620. if not TempRegUsed then
  4621. begin
  4622. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4623. RemoveCurrentP(p, hp1);
  4624. Result := True;
  4625. Exit;
  4626. end
  4627. else
  4628. begin
  4629. { Initial instruction wasn't actually changed }
  4630. Include(OptsToCheck, aoc_ForceNewIteration);
  4631. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4632. appears below since %reg1 has technically changed }
  4633. if taicpu(hp2).opcode = A_AND then
  4634. Break;
  4635. end;
  4636. {$endif x86_64}
  4637. end
  4638. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4639. GetNextInstruction(hp2, hp4) and
  4640. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4641. { Optimise the following first:
  4642. movl [mem1],reg1
  4643. movl [mem1],reg2
  4644. to
  4645. movl [mem1],reg1
  4646. movl reg1,reg2
  4647. If [mem1] contains the target register and reg1 is the
  4648. the source register, this optimisation will get missed
  4649. and produce less efficient code later on.
  4650. }
  4651. if CheckMovMov2MovMov2(hp2, hp4) then
  4652. { Initial instruction wasn't actually changed }
  4653. Include(OptsToCheck, aoc_ForceNewIteration);
  4654. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4655. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4656. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4657. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4658. begin
  4659. {
  4660. Change from:
  4661. mov ###, %reg
  4662. ...
  4663. movs/z %reg,%reg (Same register, just different sizes)
  4664. To:
  4665. movs/z ###, %reg (Longer version)
  4666. ...
  4667. (remove)
  4668. }
  4669. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4670. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4671. { Keep the first instruction as mov if ### is a constant }
  4672. if taicpu(p).oper[0]^.typ = top_const then
  4673. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4674. else
  4675. begin
  4676. taicpu(p).opcode := taicpu(hp2).opcode;
  4677. taicpu(p).opsize := taicpu(hp2).opsize;
  4678. end;
  4679. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4680. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4681. RemoveInstruction(hp2);
  4682. Result := True;
  4683. JumpTracking.Free;
  4684. Exit;
  4685. end;
  4686. else
  4687. { Move down to the if-block below };
  4688. end;
  4689. { Also catches MOV/S/Z instructions that aren't modified }
  4690. if taicpu(p).oper[0]^.typ = top_reg then
  4691. begin
  4692. p_SourceReg := taicpu(p).oper[0]^.reg;
  4693. if
  4694. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4695. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4696. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4697. begin
  4698. Result := True;
  4699. { Just in case something didn't get modified (e.g. an
  4700. implicit register). Also, if it does read from this
  4701. register, then there's no longer an advantage to
  4702. changing the register on subsequent instructions.}
  4703. if not RegReadByInstruction(p_TargetReg, hp2) then
  4704. begin
  4705. { If a conditional jump was crossed, do not delete
  4706. the original MOV no matter what }
  4707. if not CrossJump and
  4708. { RegEndOfLife returns True if the register is
  4709. deallocated before the next instruction or has
  4710. been loaded with a new value }
  4711. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4712. begin
  4713. { We can remove the original MOV }
  4714. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4715. RemoveCurrentp(p, hp1);
  4716. JumpTracking.Free;
  4717. Result := True;
  4718. Exit;
  4719. end;
  4720. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4721. begin
  4722. { See if there's more we can optimise }
  4723. hp3 := hp2;
  4724. Continue;
  4725. end;
  4726. end;
  4727. end;
  4728. end;
  4729. { Break out of the while loop under normal circumstances }
  4730. Break;
  4731. end;
  4732. JumpTracking.Free;
  4733. end;
  4734. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4735. (taicpu(p).oper[1]^.typ = top_reg) and
  4736. (taicpu(p).opsize = S_L) and
  4737. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4738. (hp2.typ = ait_instruction) and
  4739. (taicpu(hp2).opcode = A_AND) and
  4740. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4741. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4742. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4743. ) then
  4744. begin
  4745. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4746. begin
  4747. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4748. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4749. begin
  4750. { Optimize out:
  4751. mov x, %reg
  4752. and ffffffffh, %reg
  4753. }
  4754. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4755. RemoveInstruction(hp2);
  4756. Result:=true;
  4757. exit;
  4758. end;
  4759. end;
  4760. end;
  4761. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4762. x >= RetOffset) as it doesn't do anything (it writes either to a
  4763. parameter or to the temporary storage room for the function
  4764. result)
  4765. }
  4766. if IsExitCode(hp1) and
  4767. (taicpu(p).oper[1]^.typ = top_ref) and
  4768. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4769. (
  4770. (
  4771. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4772. not (
  4773. assigned(current_procinfo.procdef.funcretsym) and
  4774. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4775. )
  4776. ) or
  4777. { Also discard writes to the stack that are below the base pointer,
  4778. as this is temporary storage rather than a function result on the
  4779. stack, say. }
  4780. (
  4781. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4782. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4783. )
  4784. ) then
  4785. begin
  4786. RemoveCurrentp(p, hp1);
  4787. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4788. RemoveLastDeallocForFuncRes(p);
  4789. Result:=true;
  4790. exit;
  4791. end;
  4792. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4793. begin
  4794. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4795. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4796. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4797. begin
  4798. { change
  4799. mov reg1, mem1
  4800. test/cmp x, mem1
  4801. to
  4802. mov reg1, mem1
  4803. test/cmp x, reg1
  4804. }
  4805. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4806. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4807. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4808. Result := True;
  4809. Exit;
  4810. end;
  4811. if DoMovCmpMemOpt(p, hp1) then
  4812. begin
  4813. Result := True;
  4814. Exit;
  4815. end;
  4816. end;
  4817. if (taicpu(p).oper[1]^.typ = top_reg) and
  4818. (hp1.typ = ait_instruction) and
  4819. GetNextInstruction(hp1, hp2) and
  4820. MatchInstruction(hp2,A_MOV,[]) and
  4821. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4822. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4823. (
  4824. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4825. {$ifdef x86_64}
  4826. or
  4827. (
  4828. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4829. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4830. )
  4831. {$endif x86_64}
  4832. ) then
  4833. begin
  4834. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4835. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4836. { change movsX/movzX reg/ref, reg2
  4837. add/sub/or/... reg3/$const, reg2
  4838. mov reg2 reg/ref
  4839. dealloc reg2
  4840. to
  4841. add/sub/or/... reg3/$const, reg/ref }
  4842. begin
  4843. TransferUsedRegs(TmpUsedRegs);
  4844. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4845. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4846. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4847. begin
  4848. { by example:
  4849. movswl %si,%eax movswl %si,%eax p
  4850. decl %eax addl %edx,%eax hp1
  4851. movw %ax,%si movw %ax,%si hp2
  4852. ->
  4853. movswl %si,%eax movswl %si,%eax p
  4854. decw %eax addw %edx,%eax hp1
  4855. movw %ax,%si movw %ax,%si hp2
  4856. }
  4857. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4858. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4859. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4860. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4861. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4862. {
  4863. ->
  4864. movswl %si,%eax movswl %si,%eax p
  4865. decw %si addw %dx,%si hp1
  4866. movw %ax,%si movw %ax,%si hp2
  4867. }
  4868. case taicpu(hp1).ops of
  4869. 1:
  4870. begin
  4871. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4872. if taicpu(hp1).oper[0]^.typ=top_reg then
  4873. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4874. end;
  4875. 2:
  4876. begin
  4877. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4878. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4879. (taicpu(hp1).opcode<>A_SHL) and
  4880. (taicpu(hp1).opcode<>A_SHR) and
  4881. (taicpu(hp1).opcode<>A_SAR) then
  4882. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4883. end;
  4884. else
  4885. internalerror(2008042701);
  4886. end;
  4887. {
  4888. ->
  4889. decw %si addw %dx,%si p
  4890. }
  4891. RemoveInstruction(hp2);
  4892. RemoveCurrentP(p, hp1);
  4893. Result:=True;
  4894. Exit;
  4895. end;
  4896. end;
  4897. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4898. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4899. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4900. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4901. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4902. ) and
  4903. { if ref contains a symbol, we cannot change its size to a smaller size }
  4904. ((taicpu(p).oper[0]^.typ<>top_ref) or (taicpu(p).oper[0]^.ref^.symbol=nil) or
  4905. (topsize2memsize[taicpu(p).opsize]<=topsize2memsize[taicpu(hp2).opsize])
  4906. )
  4907. {$ifdef i386}
  4908. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4909. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4910. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4911. {$endif i386}
  4912. then
  4913. { change movsX/movzX reg/ref, reg2
  4914. add/sub/or/... regX/$const, reg2
  4915. mov reg2, reg3
  4916. dealloc reg2
  4917. to
  4918. movsX/movzX reg/ref, reg3
  4919. add/sub/or/... reg3/$const, reg3
  4920. }
  4921. begin
  4922. TransferUsedRegs(TmpUsedRegs);
  4923. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4924. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4925. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4926. begin
  4927. { by example:
  4928. movswl %si,%eax movswl %si,%eax p
  4929. decl %eax addl %edx,%eax hp1
  4930. movw %ax,%si movw %ax,%si hp2
  4931. ->
  4932. movswl %si,%eax movswl %si,%eax p
  4933. decw %eax addw %edx,%eax hp1
  4934. movw %ax,%si movw %ax,%si hp2
  4935. }
  4936. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4937. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4938. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4939. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4940. { limit size of constants as well to avoid assembler errors, but
  4941. check opsize to avoid overflow when left shifting the 1 }
  4942. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4943. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4944. {$ifdef x86_64}
  4945. { Be careful of, for example:
  4946. movl %reg1,%reg2
  4947. addl %reg3,%reg2
  4948. movq %reg2,%reg4
  4949. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4950. }
  4951. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4952. begin
  4953. taicpu(hp2).changeopsize(S_L);
  4954. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4955. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4956. end;
  4957. {$endif x86_64}
  4958. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4959. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4960. if taicpu(p).oper[0]^.typ=top_reg then
  4961. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4962. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4963. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4964. {
  4965. ->
  4966. movswl %si,%eax movswl %si,%eax p
  4967. decw %si addw %dx,%si hp1
  4968. movw %ax,%si movw %ax,%si hp2
  4969. }
  4970. case taicpu(hp1).ops of
  4971. 1:
  4972. begin
  4973. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4974. if taicpu(hp1).oper[0]^.typ=top_reg then
  4975. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4976. end;
  4977. 2:
  4978. begin
  4979. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4980. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4981. (taicpu(hp1).opcode<>A_SHL) and
  4982. (taicpu(hp1).opcode<>A_SHR) and
  4983. (taicpu(hp1).opcode<>A_SAR) then
  4984. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4985. end;
  4986. else
  4987. internalerror(2018111801);
  4988. end;
  4989. {
  4990. ->
  4991. decw %si addw %dx,%si p
  4992. }
  4993. RemoveInstruction(hp2);
  4994. end;
  4995. end;
  4996. end;
  4997. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4998. GetNextInstruction(hp1, hp2) and
  4999. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  5000. MatchOperand(Taicpu(p).oper[0]^,0) and
  5001. (Taicpu(p).oper[1]^.typ = top_reg) and
  5002. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  5003. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  5004. { mov reg1,0
  5005. bts reg1,operand1 --> mov reg1,operand2
  5006. or reg1,operand2 bts reg1,operand1}
  5007. begin
  5008. Taicpu(hp2).opcode:=A_MOV;
  5009. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  5010. asml.remove(hp1);
  5011. insertllitem(hp2,hp2.next,hp1);
  5012. RemoveCurrentp(p, hp1);
  5013. Result:=true;
  5014. exit;
  5015. end;
  5016. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  5017. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  5018. GetNextInstruction(hp1, hp2) and
  5019. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  5020. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  5021. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  5022. { change
  5023. mov reg1,reg2
  5024. sub reg3,reg2
  5025. cmp reg3,reg1
  5026. into
  5027. mov reg1,reg2
  5028. sub reg3,reg2
  5029. }
  5030. begin
  5031. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  5032. RemoveInstruction(hp2);
  5033. Result:=true;
  5034. exit;
  5035. end;
  5036. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  5037. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  5038. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5039. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  5040. begin
  5041. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  5042. {$ifdef x86_64}
  5043. { Convert:
  5044. movq x(ref),%reg64
  5045. shrq y,%reg64
  5046. To:
  5047. movl x+4(ref),%reg32
  5048. shrl y-32,%reg32 (Remove if y = 32)
  5049. }
  5050. if (taicpu(p).opsize = S_Q) and
  5051. (taicpu(hp1).opcode = A_SHR) and
  5052. (taicpu(hp1).oper[0]^.val >= 32) then
  5053. begin
  5054. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  5055. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  5056. { Convert to 32-bit }
  5057. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  5058. taicpu(p).opsize := S_L;
  5059. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  5060. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  5061. if (taicpu(hp1).oper[0]^.val = 32) then
  5062. begin
  5063. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  5064. RemoveInstruction(hp1);
  5065. end
  5066. else
  5067. begin
  5068. { This will potentially open up more arithmetic operations since
  5069. the peephole optimizer now has a big hint that only the lower
  5070. 32 bits are currently in use (and opcodes are smaller in size) }
  5071. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  5072. taicpu(hp1).opsize := S_L;
  5073. Dec(taicpu(hp1).oper[0]^.val, 32);
  5074. DebugMsg(SPeepholeOptimization + PreMessage +
  5075. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  5076. end;
  5077. Result := True;
  5078. Exit;
  5079. end;
  5080. {$endif x86_64}
  5081. { Convert:
  5082. movl x(ref),%reg
  5083. shrl $24,%reg
  5084. To:
  5085. movzbl x+3(ref),%reg
  5086. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  5087. Also accept sar instead of shr, but convert to movsx instead of movzx
  5088. }
  5089. if taicpu(hp1).opcode = A_SHR then
  5090. MovUnaligned := A_MOVZX
  5091. else
  5092. MovUnaligned := A_MOVSX;
  5093. NewSize := S_NO;
  5094. NewOffset := 0;
  5095. case taicpu(p).opsize of
  5096. S_B:
  5097. { No valid combinations };
  5098. S_W:
  5099. if (taicpu(hp1).oper[0]^.val = 8) then
  5100. begin
  5101. NewSize := S_BW;
  5102. NewOffset := 1;
  5103. end;
  5104. S_L:
  5105. case taicpu(hp1).oper[0]^.val of
  5106. 16:
  5107. begin
  5108. NewSize := S_WL;
  5109. NewOffset := 2;
  5110. end;
  5111. 24:
  5112. begin
  5113. NewSize := S_BL;
  5114. NewOffset := 3;
  5115. end;
  5116. else
  5117. ;
  5118. end;
  5119. {$ifdef x86_64}
  5120. S_Q:
  5121. case taicpu(hp1).oper[0]^.val of
  5122. 32:
  5123. begin
  5124. if taicpu(hp1).opcode = A_SAR then
  5125. begin
  5126. { 32-bit to 64-bit is a distinct instruction }
  5127. MovUnaligned := A_MOVSXD;
  5128. NewSize := S_LQ;
  5129. NewOffset := 4;
  5130. end
  5131. else
  5132. { Should have been handled by MovShr2Mov above }
  5133. InternalError(2022081811);
  5134. end;
  5135. 48:
  5136. begin
  5137. NewSize := S_WQ;
  5138. NewOffset := 6;
  5139. end;
  5140. 56:
  5141. begin
  5142. NewSize := S_BQ;
  5143. NewOffset := 7;
  5144. end;
  5145. else
  5146. ;
  5147. end;
  5148. {$endif x86_64}
  5149. else
  5150. InternalError(2022081810);
  5151. end;
  5152. if (NewSize <> S_NO) and
  5153. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  5154. begin
  5155. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  5156. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  5157. debug_op2str(MovUnaligned);
  5158. {$ifdef x86_64}
  5159. if MovUnaligned <> A_MOVSXD then
  5160. { Don't add size suffix for MOVSXD }
  5161. {$endif x86_64}
  5162. PreMessage := PreMessage + debug_opsize2str(NewSize);
  5163. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  5164. taicpu(p).opcode := MovUnaligned;
  5165. taicpu(p).opsize := NewSize;
  5166. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  5167. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  5168. RemoveInstruction(hp1);
  5169. Result := True;
  5170. Exit;
  5171. end;
  5172. end;
  5173. { Backward optimisation shared with OptPass2MOV }
  5174. if FuncMov2Func(p, hp1) then
  5175. begin
  5176. Result := True;
  5177. Exit;
  5178. end;
  5179. end;
  5180. function TX86AsmOptimizer.OptPass1MOVD(var p : tai) : boolean;
  5181. { This function also handles the 64-bit version, MOVQ }
  5182. var
  5183. hp1: tai;
  5184. begin
  5185. Result:=false;
  5186. { Change:
  5187. movd/q %xmm0, %reg
  5188. ...
  5189. movl/q %reg, (ref)
  5190. (dealloc %reg)
  5191. To:
  5192. movd/q %xmm0, (ref)
  5193. }
  5194. if MatchOpType(taicpu(p),top_reg,top_reg) and
  5195. (GetRegType(taicpu(p).oper[0]^.reg)=R_MMREGISTER) and
  5196. (GetRegType(taicpu(p).oper[1]^.reg)=R_INTREGISTER) and
  5197. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  5198. MatchInstruction(hp1, A_MOV, []) and
  5199. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^.reg) and
  5200. (taicpu(hp1).oper[1]^.typ=top_ref) and
  5201. not RegInRef(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.ref^) then
  5202. begin
  5203. TransferUsedRegs(TmpUsedRegs);
  5204. UpdateUsedRegsBetween(TmpUsedRegs,p,hp1);
  5205. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs) then
  5206. begin
  5207. if (
  5208. { Instructions are always adjacent under -O2 and under }
  5209. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5210. (
  5211. (
  5212. (taicpu(hp1).oper[1]^.ref^.base=NR_NO) or
  5213. not RegModifiedBetween(taicpu(hp1).oper[1]^.ref^.base,p,hp1)
  5214. ) and
  5215. (
  5216. (taicpu(hp1).oper[1]^.ref^.index=NR_NO) or
  5217. not RegModifiedBetween(taicpu(hp1).oper[1]^.ref^.index,p,hp1)
  5218. )
  5219. )
  5220. ) then
  5221. begin
  5222. DebugMsg(SPeepholeOptimization+'Merged (V)MOVD/(V)MOVQ and MOV to eliminate intermediate register (MovD/QMov2MovD/Q 1a)',p);
  5223. taicpu(p).loadref(1,taicpu(hp1).oper[1]^.ref^);
  5224. { loadref increases the reference count, so decrement it again }
  5225. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  5226. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  5227. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  5228. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  5229. RemoveInstruction(hp1);
  5230. Include(OptsToCheck, aoc_ForceNewIteration);
  5231. end
  5232. else if not RegModifiedBetween(taicpu(p).oper[0]^.reg,p,hp1) then
  5233. begin
  5234. { Still possible to optimise if hp1 is converted instead }
  5235. DebugMsg(SPeepholeOptimization+'Merged (V)MOVD/(V)MOVQ and MOV to eliminate intermediate register (MovD/QMov2MovD/Q 1b)',hp1);
  5236. { Decrement the reference prior to replacing it }
  5237. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  5238. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  5239. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  5240. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  5241. taicpu(hp1).opcode:=taicpu(p).opcode;
  5242. taicpu(hp1).opsize:=taicpu(p).opsize;
  5243. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  5244. TransferUsedRegs(TmpUsedRegs);
  5245. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,TmpUsedRegs);
  5246. RemoveCurrentP(p);
  5247. Result:=True;
  5248. Exit;
  5249. end;
  5250. end;
  5251. end;
  5252. end;
  5253. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  5254. var
  5255. hp1 : tai;
  5256. begin
  5257. Result:=false;
  5258. if taicpu(p).ops <> 2 then
  5259. exit;
  5260. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  5261. GetNextInstruction(p,hp1) then
  5262. begin
  5263. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5264. (taicpu(hp1).ops = 2) then
  5265. begin
  5266. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  5267. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  5268. { movXX reg1, mem1 or movXX mem1, reg1
  5269. movXX mem2, reg2 movXX reg2, mem2}
  5270. begin
  5271. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  5272. { movXX reg1, mem1 or movXX mem1, reg1
  5273. movXX mem2, reg1 movXX reg2, mem1}
  5274. begin
  5275. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5276. begin
  5277. { Removes the second statement from
  5278. movXX reg1, mem1/reg2
  5279. movXX mem1/reg2, reg1
  5280. }
  5281. if taicpu(p).oper[0]^.typ=top_reg then
  5282. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  5283. { Removes the second statement from
  5284. movXX mem1/reg1, reg2
  5285. movXX reg2, mem1/reg1
  5286. }
  5287. if (taicpu(p).oper[1]^.typ=top_reg) and
  5288. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  5289. begin
  5290. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  5291. RemoveInstruction(hp1);
  5292. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5293. Result:=true;
  5294. exit;
  5295. end
  5296. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5297. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5298. begin
  5299. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5300. RemoveInstruction(hp1);
  5301. Result:=true;
  5302. exit;
  5303. end;
  5304. end
  5305. end;
  5306. end;
  5307. end;
  5308. end;
  5309. end;
  5310. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5311. var
  5312. hp1 : tai;
  5313. begin
  5314. result:=false;
  5315. { replace
  5316. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5317. MovX %mreg2,%mreg1
  5318. dealloc %mreg2
  5319. by
  5320. <Op>X %mreg2,%mreg1
  5321. ?
  5322. }
  5323. if GetNextInstruction(p,hp1) and
  5324. { we mix single and double opperations here because we assume that the compiler
  5325. generates vmovapd only after double operations and vmovaps only after single operations }
  5326. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5327. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5328. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5329. (taicpu(p).oper[0]^.typ=top_reg) then
  5330. begin
  5331. TransferUsedRegs(TmpUsedRegs);
  5332. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5333. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5334. begin
  5335. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5336. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5337. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5338. RemoveInstruction(hp1);
  5339. result:=true;
  5340. end;
  5341. end;
  5342. end;
  5343. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5344. var
  5345. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5346. JumpLabel, JumpLabel_dist: TAsmLabel;
  5347. FirstValue, SecondValue: TCGInt;
  5348. function OptimizeJump(var InputP: tai): Boolean;
  5349. var
  5350. TempBool: Boolean;
  5351. begin
  5352. Result := False;
  5353. TempBool := True;
  5354. if DoJumpOptimizations(InputP, TempBool) or
  5355. not TempBool then
  5356. begin
  5357. Result := True;
  5358. if Assigned(InputP) then
  5359. begin
  5360. { CollapseZeroDistJump will be set to the label or an align
  5361. before it after the jump if it optimises, whether or not
  5362. the label is live or dead }
  5363. if (InputP.typ = ait_align) or
  5364. (
  5365. (InputP.typ = ait_label) and
  5366. not (tai_label(InputP).labsym.is_used)
  5367. ) then
  5368. GetNextInstruction(InputP, InputP);
  5369. end;
  5370. Exit;
  5371. end;
  5372. end;
  5373. begin
  5374. Result := False;
  5375. if (taicpu(p).oper[0]^.typ = top_const) and
  5376. (taicpu(p).oper[0]^.val <> -1) then
  5377. begin
  5378. { Convert unsigned maximum constants to -1 to aid optimisation }
  5379. case taicpu(p).opsize of
  5380. S_B:
  5381. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5382. begin
  5383. taicpu(p).oper[0]^.val := -1;
  5384. Result := True;
  5385. Exit;
  5386. end;
  5387. S_W:
  5388. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5389. begin
  5390. taicpu(p).oper[0]^.val := -1;
  5391. Result := True;
  5392. Exit;
  5393. end;
  5394. S_L:
  5395. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5396. begin
  5397. taicpu(p).oper[0]^.val := -1;
  5398. Result := True;
  5399. Exit;
  5400. end;
  5401. {$ifdef x86_64}
  5402. S_Q:
  5403. { Storing anything greater than $7FFFFFFF is not possible so do
  5404. nothing };
  5405. {$endif x86_64}
  5406. else
  5407. InternalError(2021121001);
  5408. end;
  5409. end;
  5410. if GetNextInstruction(p, hp1) and
  5411. TrySwapMovCmp(p, hp1) then
  5412. begin
  5413. Result := True;
  5414. Exit;
  5415. end;
  5416. p_label := nil;
  5417. JumpLabel := nil;
  5418. if MatchInstruction(hp1, A_Jcc, []) then
  5419. begin
  5420. if OptimizeJump(hp1) then
  5421. begin
  5422. Result := True;
  5423. if Assigned(hp1) then
  5424. begin
  5425. { CollapseZeroDistJump will be set to the label or an align
  5426. before it after the jump if it optimises, whether or not
  5427. the label is live or dead }
  5428. if (hp1.typ = ait_align) or
  5429. (
  5430. (hp1.typ = ait_label) and
  5431. not (tai_label(hp1).labsym.is_used)
  5432. ) then
  5433. GetNextInstruction(hp1, hp1);
  5434. end;
  5435. TransferUsedRegs(TmpUsedRegs);
  5436. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5437. if not Assigned(hp1) or
  5438. (
  5439. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5440. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5441. ) then
  5442. begin
  5443. { No more conditional jumps; conditional statement is no longer required }
  5444. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5445. RemoveCurrentP(p);
  5446. end;
  5447. Exit;
  5448. end;
  5449. if IsJumpToLabel(taicpu(hp1)) then
  5450. begin
  5451. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5452. if Assigned(JumpLabel) then
  5453. p_label := getlabelwithsym(JumpLabel);
  5454. end;
  5455. end;
  5456. { Search for:
  5457. test $x,(reg/ref)
  5458. jne @lbl1
  5459. test $y,(reg/ref) (same register or reference)
  5460. jne @lbl1
  5461. Change to:
  5462. test $(x or y),(reg/ref)
  5463. jne @lbl1
  5464. (Note, this doesn't work with je instead of jne)
  5465. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5466. Also search for:
  5467. test $x,(reg/ref)
  5468. je @lbl1
  5469. ...
  5470. test $y,(reg/ref)
  5471. je/jne @lbl2
  5472. If (x or y) = x, then the second jump is deterministic
  5473. }
  5474. if (
  5475. (
  5476. (taicpu(p).oper[0]^.typ = top_const) or
  5477. (
  5478. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5479. (taicpu(p).oper[0]^.typ = top_reg) and
  5480. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5481. )
  5482. ) and
  5483. MatchInstruction(hp1, A_JCC, [])
  5484. ) then
  5485. begin
  5486. if (taicpu(p).oper[0]^.typ = top_reg) and
  5487. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5488. FirstValue := -1
  5489. else
  5490. FirstValue := taicpu(p).oper[0]^.val;
  5491. { If we have several test/jne's in a row, it might be the case that
  5492. the second label doesn't go to the same location, but the one
  5493. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5494. so accommodate for this with a while loop.
  5495. }
  5496. hp1_last := hp1;
  5497. while (
  5498. (
  5499. (taicpu(p).oper[1]^.typ = top_reg) and
  5500. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5501. ) or GetNextInstruction(hp1_last, p_dist)
  5502. ) and (p_dist.typ = ait_instruction) do
  5503. begin
  5504. if (
  5505. (
  5506. (taicpu(p_dist).opcode = A_TEST) and
  5507. (
  5508. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5509. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5510. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5511. )
  5512. ) or
  5513. (
  5514. { cmp 0,%reg = test %reg,%reg }
  5515. (taicpu(p_dist).opcode = A_CMP) and
  5516. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5517. )
  5518. ) and
  5519. { Make sure the destination operands are actually the same }
  5520. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5521. GetNextInstruction(p_dist, hp1_dist) and
  5522. MatchInstruction(hp1_dist, A_JCC, []) then
  5523. begin
  5524. if OptimizeJump(hp1_dist) then
  5525. begin
  5526. Result := True;
  5527. Exit;
  5528. end;
  5529. if
  5530. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5531. (
  5532. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5533. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5534. ) then
  5535. SecondValue := -1
  5536. else
  5537. SecondValue := taicpu(p_dist).oper[0]^.val;
  5538. { If both of the TEST constants are identical, delete the
  5539. second TEST that is unnecessary (be careful though, just
  5540. in case the flags are modified in between) }
  5541. if (FirstValue = SecondValue) then
  5542. begin
  5543. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5544. begin
  5545. { Since the second jump's condition is a subset of the first, we
  5546. know it will never branch because the first jump dominates it.
  5547. Get it out of the way now rather than wait for the jump
  5548. optimisations for a speed boost. }
  5549. if IsJumpToLabel(taicpu(hp1_dist)) then
  5550. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5551. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5552. RemoveInstruction(hp1_dist);
  5553. Result := True;
  5554. end
  5555. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5556. begin
  5557. { If the inverse of the first condition is a subset of the second,
  5558. the second one will definitely branch if the first one doesn't }
  5559. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5560. { We can remove the TEST instruction too }
  5561. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5562. RemoveInstruction(p_dist);
  5563. MakeUnconditional(taicpu(hp1_dist));
  5564. RemoveDeadCodeAfterJump(hp1_dist);
  5565. { Since the jump is now unconditional, we can't
  5566. continue any further with this particular
  5567. optimisation. The original TEST is still intact
  5568. though, so there might be something else we can
  5569. do }
  5570. Include(OptsToCheck, aoc_ForceNewIteration);
  5571. Break;
  5572. end;
  5573. if Result or
  5574. { If a jump wasn't removed or made unconditional, only
  5575. remove the identical TEST instruction if the flags
  5576. weren't modified }
  5577. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5578. begin
  5579. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5580. RemoveInstruction(p_dist);
  5581. { If the jump was removed or made unconditional, we
  5582. don't need to allocate NR_DEFAULTFLAGS over the
  5583. entire range }
  5584. if not Result then
  5585. begin
  5586. { Mark the flags as 'in use' over the entire range }
  5587. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5588. { Speed gain - continue search from the Jcc instruction }
  5589. hp1_last := hp1_dist;
  5590. { Only the TEST instruction was removed, and the
  5591. original was unchanged, so we can safely do
  5592. another iteration of the while loop }
  5593. Include(OptsToCheck, aoc_ForceNewIteration);
  5594. Continue;
  5595. end;
  5596. Exit;
  5597. end;
  5598. end;
  5599. hp1_last := nil;
  5600. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5601. (
  5602. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5603. { Always adjacent under -O2 and under }
  5604. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5605. (
  5606. GetNextInstruction(hp1, hp1_last) and
  5607. (hp1_last = p_dist)
  5608. )
  5609. ) and
  5610. (
  5611. (
  5612. { Test the following variant:
  5613. test $x,(reg/ref)
  5614. jne @lbl1
  5615. test $y,(reg/ref)
  5616. je @lbl2
  5617. @lbl1:
  5618. Becomes:
  5619. test $(x or y),(reg/ref)
  5620. je @lbl2
  5621. @lbl1: (may become a dead label)
  5622. }
  5623. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5624. GetNextInstruction(hp1_dist, hp1_last) and
  5625. (hp1_last = p_label)
  5626. ) or
  5627. (
  5628. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5629. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5630. then the second jump will never branch, so it can also be
  5631. removed regardless of where it goes }
  5632. (
  5633. (FirstValue = -1) or
  5634. (SecondValue = -1) or
  5635. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5636. )
  5637. )
  5638. ) then
  5639. begin
  5640. { Same jump location... can be a register since nothing's changed }
  5641. { If any of the entries are equivalent to test %reg,%reg, then the
  5642. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5643. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5644. if (hp1_last = p_label) then
  5645. begin
  5646. { Variant }
  5647. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5648. RemoveInstruction(p_dist);
  5649. if Assigned(JumpLabel) then
  5650. JumpLabel.decrefs;
  5651. RemoveInstruction(hp1);
  5652. end
  5653. else
  5654. begin
  5655. { Only remove the second test if no jumps or other conditional instructions follow }
  5656. TransferUsedRegs(TmpUsedRegs);
  5657. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5658. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5659. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5660. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5661. begin
  5662. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5663. RemoveInstruction(p_dist);
  5664. { Remove the first jump, not the second, to keep
  5665. any register deallocations between the second
  5666. TEST/JNE pair in the same place. Aids future
  5667. optimisation. }
  5668. if Assigned(JumpLabel) then
  5669. JumpLabel.decrefs;
  5670. RemoveInstruction(hp1);
  5671. end
  5672. else
  5673. begin
  5674. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5675. if IsJumpToLabel(taicpu(hp1_dist)) then
  5676. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5677. { Remove second jump in this instance }
  5678. RemoveInstruction(hp1_dist);
  5679. end;
  5680. end;
  5681. Result := True;
  5682. Exit;
  5683. end;
  5684. end;
  5685. if { If -O2 and under, it may stop on any old instruction }
  5686. (cs_opt_level3 in current_settings.optimizerswitches) and
  5687. (taicpu(p).oper[1]^.typ = top_reg) and
  5688. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5689. begin
  5690. hp1_last := p_dist;
  5691. Continue;
  5692. end;
  5693. Break;
  5694. end;
  5695. end;
  5696. { Search for:
  5697. test %reg,%reg
  5698. j(c1) @lbl1
  5699. ...
  5700. @lbl:
  5701. test %reg,%reg (same register)
  5702. j(c2) @lbl2
  5703. If c2 is a subset of c1, change to:
  5704. test %reg,%reg
  5705. j(c1) @lbl2
  5706. (@lbl1 may become a dead label as a result)
  5707. }
  5708. if (taicpu(p).oper[1]^.typ = top_reg) and
  5709. (taicpu(p).oper[0]^.typ = top_reg) and
  5710. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5711. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5712. Assigned(p_label) and
  5713. GetNextInstruction(p_label, p_dist) and
  5714. MatchInstruction(p_dist, A_TEST, []) and
  5715. { It's fine if the second test uses smaller sub-registers }
  5716. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5717. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5718. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5719. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5720. GetNextInstruction(p_dist, hp1_dist) and
  5721. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5722. begin
  5723. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5724. if JumpLabel = JumpLabel_dist then
  5725. { This is an infinite loop }
  5726. Exit;
  5727. { Best optimisation when the first condition is a subset (or equal) of the second }
  5728. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5729. begin
  5730. { Any registers used here will already be allocated }
  5731. if Assigned(JumpLabel) then
  5732. JumpLabel.DecRefs;
  5733. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5734. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5735. Result := True;
  5736. Exit;
  5737. end;
  5738. end;
  5739. end;
  5740. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5741. var
  5742. hp1, hp2: tai;
  5743. ActiveReg: TRegister;
  5744. OldOffset: asizeint;
  5745. ThisConst: TCGInt;
  5746. function RegDeallocated: Boolean;
  5747. begin
  5748. TransferUsedRegs(TmpUsedRegs);
  5749. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5750. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5751. end;
  5752. begin
  5753. result:=false;
  5754. hp1 := nil;
  5755. { replace
  5756. addX const,%reg1
  5757. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5758. dealloc %reg1
  5759. by
  5760. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5761. }
  5762. if MatchOpType(taicpu(p),top_const,top_reg) then
  5763. begin
  5764. ActiveReg := taicpu(p).oper[1]^.reg;
  5765. { Ensures the entire register was updated }
  5766. if (taicpu(p).opsize >= S_L) and
  5767. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5768. MatchInstruction(hp1,A_LEA,[]) and
  5769. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5770. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5771. (
  5772. { Cover the case where the register in the reference is also the destination register }
  5773. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5774. (
  5775. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5776. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5777. RegDeallocated
  5778. )
  5779. ) then
  5780. begin
  5781. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5782. {$push}
  5783. {$R-}{$Q-}
  5784. { Explicitly disable overflow checking for these offset calculation
  5785. as those do not matter for the final result }
  5786. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5787. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5788. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5789. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5790. {$pop}
  5791. {$ifdef x86_64}
  5792. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5793. begin
  5794. { Overflow; abort }
  5795. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5796. end
  5797. else
  5798. {$endif x86_64}
  5799. begin
  5800. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5801. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5802. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5803. RemoveCurrentP(p, hp1)
  5804. else
  5805. RemoveCurrentP(p);
  5806. result:=true;
  5807. Exit;
  5808. end;
  5809. end;
  5810. if (
  5811. { Save calling GetNextInstructionUsingReg again }
  5812. Assigned(hp1) or
  5813. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5814. ) and
  5815. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5816. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5817. begin
  5818. { Make sure the flags aren't in use by the second operation }
  5819. TransferUsedRegs(TmpUsedRegs);
  5820. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  5821. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5822. begin
  5823. if taicpu(hp1).oper[0]^.typ = top_const then
  5824. begin
  5825. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5826. if taicpu(hp1).opcode = A_ADD then
  5827. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5828. else
  5829. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5830. Result := True;
  5831. { Handle any overflows }
  5832. case taicpu(p).opsize of
  5833. S_B:
  5834. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5835. S_W:
  5836. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5837. S_L:
  5838. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5839. {$ifdef x86_64}
  5840. S_Q:
  5841. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5842. { Overflow; abort }
  5843. Result := False
  5844. else
  5845. taicpu(p).oper[0]^.val := ThisConst;
  5846. {$endif x86_64}
  5847. else
  5848. InternalError(2021102610);
  5849. end;
  5850. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5851. if Result then
  5852. begin
  5853. if (taicpu(p).oper[0]^.val < 0) and
  5854. (
  5855. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5856. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5857. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5858. ) then
  5859. begin
  5860. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5861. taicpu(p).opcode := A_SUB;
  5862. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5863. end
  5864. else
  5865. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5866. RemoveInstruction(hp1);
  5867. end;
  5868. end
  5869. else
  5870. begin
  5871. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5872. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5873. Asml.Remove(p);
  5874. Asml.InsertAfter(p, hp1);
  5875. p := hp1;
  5876. Result := True;
  5877. Exit;
  5878. end;
  5879. end;
  5880. end;
  5881. if DoArithCombineOpt(p) then
  5882. Result:=true;
  5883. end;
  5884. end;
  5885. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5886. var
  5887. hp1, hp2: tai;
  5888. ref: Integer;
  5889. saveref: treference;
  5890. offsetcalc: Int64;
  5891. TempReg: TRegister;
  5892. Multiple: TCGInt;
  5893. Adjacent, IntermediateRegDiscarded: Boolean;
  5894. begin
  5895. Result:=false;
  5896. { play save and throw an error if LEA uses a seg register prefix,
  5897. this is most likely an error somewhere else }
  5898. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5899. internalerror(2022022001);
  5900. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5901. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5902. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5903. (
  5904. { do not mess with leas accessing the stack pointer
  5905. unless it's a null operation }
  5906. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5907. (
  5908. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5909. (taicpu(p).oper[0]^.ref^.offset = 0)
  5910. )
  5911. ) and
  5912. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5913. begin
  5914. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5915. begin
  5916. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5917. begin
  5918. taicpu(p).opcode := A_MOV;
  5919. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5920. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5921. end
  5922. else
  5923. begin
  5924. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5925. RemoveCurrentP(p);
  5926. end;
  5927. Result:=true;
  5928. exit;
  5929. end
  5930. else if (
  5931. { continue to use lea to adjust the stack pointer,
  5932. it is the recommended way, but only if not optimizing for size }
  5933. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5934. (cs_opt_size in current_settings.optimizerswitches)
  5935. ) and
  5936. { If the flags register is in use, don't change the instruction
  5937. to an ADD otherwise this will scramble the flags. [Kit] }
  5938. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5939. ConvertLEA(taicpu(p)) then
  5940. begin
  5941. Result:=true;
  5942. exit;
  5943. end;
  5944. end;
  5945. { Don't optimise if the stack or frame pointer is the destination register }
  5946. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5947. Exit;
  5948. if GetNextInstruction(p,hp1) and
  5949. (hp1.typ=ait_instruction) then
  5950. begin
  5951. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5952. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5953. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5954. begin
  5955. TransferUsedRegs(TmpUsedRegs);
  5956. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5957. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5958. begin
  5959. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5960. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5961. RemoveInstruction(hp1);
  5962. result:=true;
  5963. exit;
  5964. end;
  5965. end;
  5966. { changes
  5967. lea <ref1>, reg1
  5968. <op> ...,<ref. with reg1>,...
  5969. to
  5970. <op> ...,<ref1>,... }
  5971. { find a reference which uses reg1 }
  5972. 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
  5973. ref:=0
  5974. 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
  5975. ref:=1
  5976. else
  5977. ref:=-1;
  5978. if (ref<>-1) and
  5979. { reg1 must be either the base or the index }
  5980. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5981. begin
  5982. { reg1 can be removed from the reference }
  5983. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5984. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5985. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5986. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5987. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5988. else
  5989. Internalerror(2019111201);
  5990. { check if the can insert all data of the lea into the second instruction }
  5991. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5992. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5993. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5994. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5995. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5996. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5997. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5998. {$ifdef x86_64}
  5999. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  6000. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  6001. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  6002. )
  6003. {$endif x86_64}
  6004. then
  6005. begin
  6006. { reg1 might not used by the second instruction after it is remove from the reference }
  6007. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  6008. begin
  6009. TransferUsedRegs(TmpUsedRegs);
  6010. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6011. { reg1 is not updated so it might not be used afterwards }
  6012. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6013. begin
  6014. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  6015. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  6016. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6017. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  6018. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  6019. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  6020. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  6021. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  6022. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  6023. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  6024. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  6025. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6026. RemoveCurrentP(p, hp1);
  6027. result:=true;
  6028. exit;
  6029. end
  6030. end;
  6031. end;
  6032. { recover }
  6033. taicpu(hp1).oper[ref]^.ref^:=saveref;
  6034. end;
  6035. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  6036. if Adjacent or
  6037. { Check further ahead (up to 2 instructions ahead for -O2) }
  6038. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  6039. begin
  6040. { Check common LEA/LEA conditions }
  6041. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  6042. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  6043. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  6044. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  6045. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  6046. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  6047. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  6048. (
  6049. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  6050. calling it (since it calls GetNextInstruction) }
  6051. Adjacent or
  6052. (
  6053. (
  6054. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  6055. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  6056. ) and (
  6057. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  6058. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6059. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  6060. )
  6061. )
  6062. ) then
  6063. begin
  6064. TransferUsedRegs(TmpUsedRegs);
  6065. hp2 := p;
  6066. repeat
  6067. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6068. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  6069. IntermediateRegDiscarded :=
  6070. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  6071. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  6072. { changes
  6073. lea offset1(regX,scale), reg1
  6074. lea offset2(reg1,reg1), reg2
  6075. to
  6076. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  6077. and
  6078. lea offset1(regX,scale1), reg1
  6079. lea offset2(reg1,scale2), reg2
  6080. to
  6081. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  6082. and
  6083. lea offset1(regX,scale1), reg1
  6084. lea offset2(reg3,reg1,scale2), reg2
  6085. to
  6086. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  6087. ... so long as the final scale does not exceed 8
  6088. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  6089. }
  6090. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6091. (
  6092. { Don't optimise if size is a concern and the intermediate register remains in use }
  6093. IntermediateRegDiscarded or
  6094. (
  6095. not (cs_opt_size in current_settings.optimizerswitches) and
  6096. { If the intermediate register is not discarded, it must not
  6097. appear in the first LEA's reference. (Fixes #41166) }
  6098. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  6099. )
  6100. ) and
  6101. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6102. (
  6103. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  6104. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6105. ) and (
  6106. (
  6107. { lea (reg1,scale2), reg2 variant }
  6108. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  6109. (
  6110. Adjacent or
  6111. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  6112. ) and
  6113. (
  6114. (
  6115. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  6116. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  6117. ) or (
  6118. { lea (regX,regX), reg1 variant }
  6119. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  6120. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  6121. )
  6122. )
  6123. ) or (
  6124. { lea (reg1,reg1), reg1 variant }
  6125. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6126. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  6127. )
  6128. ) then
  6129. begin
  6130. { Make everything homogeneous to make calculations easier }
  6131. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  6132. begin
  6133. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  6134. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  6135. taicpu(p).oper[0]^.ref^.scalefactor := 2
  6136. else
  6137. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  6138. taicpu(p).oper[0]^.ref^.base := NR_NO;
  6139. end;
  6140. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6141. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6142. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6143. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6144. begin
  6145. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6146. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  6147. begin
  6148. { Put the register to change in the index register }
  6149. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  6150. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  6151. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  6152. end;
  6153. { Change lea (reg,reg) to lea(,reg,2) }
  6154. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  6155. begin
  6156. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  6157. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  6158. end;
  6159. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  6160. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6161. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  6162. { Just to prevent miscalculations }
  6163. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  6164. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  6165. else
  6166. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  6167. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6168. if IntermediateRegDiscarded then
  6169. begin
  6170. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  6171. RemoveCurrentP(p);
  6172. end
  6173. else
  6174. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  6175. result:=true;
  6176. exit;
  6177. end;
  6178. end;
  6179. { changes
  6180. lea offset1(regX), reg1
  6181. lea offset2(reg1), reg2
  6182. to
  6183. lea offset1+offset2(regX), reg2 }
  6184. if (
  6185. { Don't optimise if size is a concern and the intermediate register remains in use }
  6186. IntermediateRegDiscarded or
  6187. (
  6188. not (cs_opt_size in current_settings.optimizerswitches) and
  6189. { If the intermediate register is not discarded, it must not
  6190. appear in the first LEA's reference. (Fixes #41166) }
  6191. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  6192. )
  6193. ) and
  6194. (
  6195. (
  6196. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6197. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  6198. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  6199. ) or (
  6200. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6201. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  6202. (
  6203. (
  6204. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6205. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  6206. ) or (
  6207. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  6208. (
  6209. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6210. (
  6211. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6212. (
  6213. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  6214. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  6215. )
  6216. )
  6217. )
  6218. )
  6219. )
  6220. )
  6221. ) then
  6222. begin
  6223. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6224. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6225. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6226. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6227. begin
  6228. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  6229. begin
  6230. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  6231. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6232. { if the register is used as index and base, we have to increase for base as well
  6233. and adapt base }
  6234. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  6235. begin
  6236. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6237. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6238. end;
  6239. end
  6240. else
  6241. begin
  6242. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6243. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6244. end;
  6245. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  6246. begin
  6247. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  6248. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  6249. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  6250. { Catch the situation where the base = index
  6251. and treat this as *2. The scalefactor of
  6252. p will be 0 or 1 due to the conditional
  6253. checks above. Fixes i40647 }
  6254. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  6255. else
  6256. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  6257. end;
  6258. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6259. if IntermediateRegDiscarded then
  6260. begin
  6261. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  6262. RemoveCurrentP(p);
  6263. end
  6264. else
  6265. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  6266. result:=true;
  6267. exit;
  6268. end;
  6269. end;
  6270. end;
  6271. { Change:
  6272. leal/q $x(%reg1),%reg2
  6273. ...
  6274. shll/q $y,%reg2
  6275. To:
  6276. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  6277. }
  6278. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6279. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  6280. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6281. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6282. (taicpu(hp1).oper[0]^.val <= 3) then
  6283. begin
  6284. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  6285. TransferUsedRegs(TmpUsedRegs);
  6286. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6287. if
  6288. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  6289. (this works even if scalefactor is zero) }
  6290. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  6291. { Ensure offset doesn't go out of bounds }
  6292. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  6293. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  6294. (
  6295. (
  6296. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  6297. (
  6298. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6299. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6300. (
  6301. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6302. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6303. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6304. )
  6305. )
  6306. ) or (
  6307. (
  6308. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6309. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6310. ) and
  6311. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6312. )
  6313. ) then
  6314. begin
  6315. repeat
  6316. with taicpu(p).oper[0]^.ref^ do
  6317. begin
  6318. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6319. if index = base then
  6320. begin
  6321. if Multiple > 4 then
  6322. { Optimisation will no longer work because resultant
  6323. scale factor will exceed 8 }
  6324. Break;
  6325. base := NR_NO;
  6326. scalefactor := 2;
  6327. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6328. end
  6329. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6330. begin
  6331. { Scale factor only works on the index register }
  6332. index := base;
  6333. base := NR_NO;
  6334. end;
  6335. { For safety }
  6336. if scalefactor <= 1 then
  6337. begin
  6338. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6339. scalefactor := Multiple;
  6340. end
  6341. else
  6342. begin
  6343. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6344. scalefactor := scalefactor * Multiple;
  6345. end;
  6346. offset := offset * Multiple;
  6347. end;
  6348. RemoveInstruction(hp1);
  6349. Result := True;
  6350. Exit;
  6351. { This repeat..until loop exists for the benefit of Break }
  6352. until True;
  6353. end;
  6354. end;
  6355. end;
  6356. end;
  6357. end;
  6358. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6359. var
  6360. hp1 : tai;
  6361. SubInstr: Boolean;
  6362. ThisConst: TCGInt;
  6363. const
  6364. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6365. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6366. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6367. begin
  6368. Result := False;
  6369. if taicpu(p).oper[0]^.typ <> top_const then
  6370. { Should have been confirmed before calling }
  6371. InternalError(2021102601);
  6372. SubInstr := (taicpu(p).opcode = A_SUB);
  6373. if not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  6374. GetLastInstruction(p, hp1) and
  6375. (hp1.typ = ait_instruction) and
  6376. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6377. begin
  6378. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6379. { Bad size }
  6380. InternalError(2022042001);
  6381. case taicpu(hp1).opcode Of
  6382. A_INC:
  6383. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6384. begin
  6385. if SubInstr then
  6386. ThisConst := taicpu(p).oper[0]^.val - 1
  6387. else
  6388. ThisConst := taicpu(p).oper[0]^.val + 1;
  6389. end
  6390. else
  6391. Exit;
  6392. A_DEC:
  6393. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6394. begin
  6395. if SubInstr then
  6396. ThisConst := taicpu(p).oper[0]^.val + 1
  6397. else
  6398. ThisConst := taicpu(p).oper[0]^.val - 1;
  6399. end
  6400. else
  6401. Exit;
  6402. A_SUB:
  6403. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6404. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6405. begin
  6406. if SubInstr then
  6407. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6408. else
  6409. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6410. end
  6411. else
  6412. Exit;
  6413. A_ADD:
  6414. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6415. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6416. begin
  6417. if SubInstr then
  6418. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6419. else
  6420. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6421. end
  6422. else
  6423. Exit;
  6424. else
  6425. Exit;
  6426. end;
  6427. { Check that the values are in range }
  6428. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6429. { Overflow; abort }
  6430. Exit;
  6431. if (ThisConst = 0) then
  6432. begin
  6433. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6434. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6435. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6436. RemoveInstruction(hp1);
  6437. hp1 := tai(p.next);
  6438. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6439. if not GetLastInstruction(hp1, p) then
  6440. p := hp1;
  6441. end
  6442. else
  6443. begin
  6444. if taicpu(hp1).opercnt=1 then
  6445. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6446. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6447. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6448. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6449. else
  6450. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6451. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6452. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6453. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6454. RemoveInstruction(hp1);
  6455. taicpu(p).loadconst(0, ThisConst);
  6456. end;
  6457. Result := True;
  6458. end;
  6459. end;
  6460. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6461. begin
  6462. Result := False;
  6463. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6464. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6465. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6466. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6467. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6468. (
  6469. (
  6470. (taicpu(hp1).opcode = A_TEST)
  6471. ) or (
  6472. (taicpu(hp1).opcode = A_CMP) and
  6473. { A sanity check more than anything }
  6474. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6475. )
  6476. ) then
  6477. begin
  6478. { change
  6479. mov mem, %reg
  6480. ...
  6481. cmp/test x, %reg / test %reg,%reg
  6482. (reg deallocated)
  6483. to
  6484. cmp/test x, mem / cmp 0, mem
  6485. }
  6486. TransferUsedRegs(TmpUsedRegs);
  6487. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6488. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6489. begin
  6490. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6491. if (taicpu(hp1).opcode = A_TEST) and
  6492. (
  6493. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6494. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6495. ) then
  6496. begin
  6497. taicpu(hp1).opcode := A_CMP;
  6498. taicpu(hp1).loadconst(0, 0);
  6499. end;
  6500. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6501. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6502. RemoveCurrentP(p);
  6503. if (p <> hp1) then
  6504. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6505. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6506. { Make sure the flags are allocated across the CMP instruction }
  6507. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6508. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6509. Result := True;
  6510. Exit;
  6511. end;
  6512. end;
  6513. end;
  6514. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6515. var
  6516. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6517. ThisReg, SecondReg: TRegister;
  6518. JumpLoc: TAsmLabel;
  6519. NewSize: TOpSize;
  6520. begin
  6521. Result := False;
  6522. {
  6523. Convert:
  6524. j<c> .L1
  6525. .L2:
  6526. mov 1,reg
  6527. jmp .L3 (or ret, although it might not be a RET yet)
  6528. .L1:
  6529. mov 0,reg
  6530. jmp .L3 (or ret)
  6531. ( As long as .L3 <> .L1 or .L2)
  6532. To:
  6533. mov 0,reg
  6534. set<not(c)> reg
  6535. jmp .L3 (or ret)
  6536. .L2:
  6537. mov 1,reg
  6538. jmp .L3 (or ret)
  6539. .L1:
  6540. mov 0,reg
  6541. jmp .L3 (or ret)
  6542. }
  6543. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6544. Exit;
  6545. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6546. if GetNextInstruction(hp_label, hp2) and
  6547. MatchInstruction(hp2,A_MOV,[]) and
  6548. (taicpu(hp2).oper[0]^.typ = top_const) and
  6549. (
  6550. (
  6551. (taicpu(hp2).oper[1]^.typ = top_reg)
  6552. {$ifdef i386}
  6553. { Under i386, ESI, EDI, EBP and ESP
  6554. don't have an 8-bit representation }
  6555. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6556. {$endif i386}
  6557. ) or (
  6558. {$ifdef i386}
  6559. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6560. {$endif i386}
  6561. (taicpu(hp2).opsize = S_B)
  6562. )
  6563. ) and
  6564. GetNextInstruction(hp2, hp3) and
  6565. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6566. (
  6567. (taicpu(hp3).opcode=A_RET) or
  6568. (
  6569. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6570. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6571. )
  6572. ) and
  6573. GetNextInstruction(hp3, hp4) and
  6574. FindLabel(JumpLoc, hp4) and
  6575. (
  6576. not (cs_opt_size in current_settings.optimizerswitches) or
  6577. { If the initial jump is the label's only reference, then it will
  6578. become a dead label if the other conditions are met and hence
  6579. remove at least 2 instructions, including a jump }
  6580. (JumpLoc.getrefs = 1)
  6581. ) and
  6582. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6583. that will be optimised out }
  6584. GetNextInstruction(hp4, hp5) and
  6585. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6586. (taicpu(hp5).oper[0]^.typ = top_const) and
  6587. (
  6588. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6589. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6590. ) and
  6591. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6592. GetNextInstruction(hp5,hp6) and
  6593. (
  6594. not (hp6.typ in [ait_align, ait_label]) or
  6595. SkipLabels(hp6, hp6)
  6596. ) and
  6597. (hp6.typ=ait_instruction) then
  6598. begin
  6599. { First, let's look at the two jumps that are hp3 and hp6 }
  6600. if not
  6601. (
  6602. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6603. (
  6604. (taicpu(hp6).opcode=A_RET) or
  6605. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6606. )
  6607. ) then
  6608. { If condition is False, then the JMP/RET instructions matched conventionally }
  6609. begin
  6610. { See if one of the jumps can be instantly converted into a RET }
  6611. if (taicpu(hp3).opcode=A_JMP) then
  6612. begin
  6613. { Reuse hp5 }
  6614. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6615. { Make sure hp5 doesn't jump back to .L1 (zero distance jump) or .L2 (infinite loop) }
  6616. if not Assigned(hp5) or (hp5 = hp_label) or (hp5 = hp4) or not GetNextInstruction(hp5, hp5) then
  6617. Exit;
  6618. if MatchInstruction(hp5, A_RET, []) then
  6619. begin
  6620. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6621. ConvertJumpToRET(hp3, hp5);
  6622. Result := True;
  6623. end
  6624. else
  6625. Exit;
  6626. end;
  6627. if (taicpu(hp6).opcode=A_JMP) then
  6628. begin
  6629. { Reuse hp5 }
  6630. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6631. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6632. Exit;
  6633. if MatchInstruction(hp5, A_RET, []) then
  6634. begin
  6635. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6636. ConvertJumpToRET(hp6, hp5);
  6637. Result := True;
  6638. end
  6639. else
  6640. Exit;
  6641. end;
  6642. if not
  6643. (
  6644. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6645. (
  6646. (taicpu(hp6).opcode=A_RET) or
  6647. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6648. )
  6649. ) then
  6650. { Still doesn't match }
  6651. Exit;
  6652. end;
  6653. if (taicpu(hp2).oper[0]^.val = 1) then
  6654. begin
  6655. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6656. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6657. end
  6658. else
  6659. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6660. if taicpu(hp2).opsize=S_B then
  6661. begin
  6662. if taicpu(hp2).oper[1]^.typ = top_reg then
  6663. begin
  6664. SecondReg := taicpu(hp2).oper[1]^.reg;
  6665. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6666. end
  6667. else
  6668. begin
  6669. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6670. SecondReg := NR_NO;
  6671. end;
  6672. hp_pos := p;
  6673. hp_allocstart := hp4;
  6674. end
  6675. else
  6676. begin
  6677. { Will be a register because the size can't be S_B otherwise }
  6678. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6679. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6680. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6681. if (cs_opt_size in current_settings.optimizerswitches) then
  6682. begin
  6683. { Favour using MOVZX when optimising for size }
  6684. case taicpu(hp2).opsize of
  6685. S_W:
  6686. NewSize := S_BW;
  6687. S_L:
  6688. NewSize := S_BL;
  6689. {$ifdef x86_64}
  6690. S_Q:
  6691. begin
  6692. NewSize := S_BL;
  6693. { Will implicitly zero-extend to 64-bit }
  6694. setsubreg(SecondReg, R_SUBD);
  6695. end;
  6696. {$endif x86_64}
  6697. else
  6698. InternalError(2022101301);
  6699. end;
  6700. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6701. { Inserting it right before p will guarantee that the flags are also tracked }
  6702. Asml.InsertBefore(hp5, p);
  6703. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6704. hp_pos := hp5;
  6705. hp_allocstart := hp4;
  6706. end
  6707. else
  6708. begin
  6709. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6710. { Inserting it right before p will guarantee that the flags are also tracked }
  6711. Asml.InsertBefore(hp5, p);
  6712. hp_pos := p;
  6713. hp_allocstart := hp5;
  6714. end;
  6715. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6716. end;
  6717. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6718. taicpu(hp4).condition := taicpu(p).condition;
  6719. asml.InsertBefore(hp4, hp_pos);
  6720. if taicpu(hp3).is_jmp then
  6721. begin
  6722. JumpLoc.decrefs;
  6723. MakeUnconditional(taicpu(p));
  6724. { This also increases the reference count }
  6725. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6726. end
  6727. else
  6728. ConvertJumpToRET(p, hp3);
  6729. if SecondReg <> NR_NO then
  6730. { Ensure the destination register is allocated over this region }
  6731. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6732. if (JumpLoc.getrefs = 0) then
  6733. RemoveDeadCodeAfterJump(hp3);
  6734. Result:=true;
  6735. exit;
  6736. end;
  6737. end;
  6738. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6739. var
  6740. hp1, hp2: tai;
  6741. ActiveReg: TRegister;
  6742. OldOffset: asizeint;
  6743. ThisConst: TCGInt;
  6744. function RegDeallocated: Boolean;
  6745. begin
  6746. TransferUsedRegs(TmpUsedRegs);
  6747. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6748. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6749. end;
  6750. begin
  6751. Result:=false;
  6752. hp1 := nil;
  6753. { replace
  6754. subX const,%reg1
  6755. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6756. dealloc %reg1
  6757. by
  6758. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6759. }
  6760. if MatchOpType(taicpu(p),top_const,top_reg) then
  6761. begin
  6762. ActiveReg := taicpu(p).oper[1]^.reg;
  6763. { Ensures the entire register was updated }
  6764. if (taicpu(p).opsize >= S_L) and
  6765. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6766. MatchInstruction(hp1,A_LEA,[]) and
  6767. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6768. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6769. (
  6770. { Cover the case where the register in the reference is also the destination register }
  6771. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6772. (
  6773. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6774. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6775. RegDeallocated
  6776. )
  6777. ) then
  6778. begin
  6779. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6780. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.base) then
  6781. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6782. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.index) then
  6783. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6784. {$ifdef x86_64}
  6785. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6786. begin
  6787. { Overflow; abort }
  6788. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6789. end
  6790. else
  6791. {$endif x86_64}
  6792. begin
  6793. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6794. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6795. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6796. RemoveCurrentP(p, hp1)
  6797. else
  6798. RemoveCurrentP(p);
  6799. result:=true;
  6800. Exit;
  6801. end;
  6802. end;
  6803. if (
  6804. { Save calling GetNextInstructionUsingReg again }
  6805. Assigned(hp1) or
  6806. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6807. ) and
  6808. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6809. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6810. begin
  6811. { Make sure the flags aren't in use by the second operation }
  6812. TransferUsedRegs(TmpUsedRegs);
  6813. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  6814. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6815. begin
  6816. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6817. begin
  6818. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6819. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6820. Result := True;
  6821. { Handle any overflows }
  6822. case taicpu(p).opsize of
  6823. S_B:
  6824. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6825. S_W:
  6826. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6827. S_L:
  6828. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6829. {$ifdef x86_64}
  6830. S_Q:
  6831. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6832. { Overflow; abort }
  6833. Result := False
  6834. else
  6835. taicpu(p).oper[0]^.val := ThisConst;
  6836. {$endif x86_64}
  6837. else
  6838. InternalError(2021102611);
  6839. end;
  6840. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6841. if Result then
  6842. begin
  6843. if (taicpu(p).oper[0]^.val < 0) and
  6844. (
  6845. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6846. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6847. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6848. ) then
  6849. begin
  6850. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6851. taicpu(p).opcode := A_SUB;
  6852. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6853. end
  6854. else
  6855. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6856. RemoveInstruction(hp1);
  6857. end;
  6858. end
  6859. else
  6860. begin
  6861. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6862. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6863. Asml.Remove(p);
  6864. Asml.InsertAfter(p, hp1);
  6865. p := hp1;
  6866. Result := True;
  6867. Exit;
  6868. end;
  6869. end;
  6870. end;
  6871. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6872. { * change "sub/add const1, reg" or "dec reg" followed by
  6873. "sub const2, reg" to one "sub ..., reg" }
  6874. {$ifdef i386}
  6875. if (taicpu(p).oper[0]^.val = 2) and
  6876. (ActiveReg = NR_ESP) and
  6877. { Don't do the sub/push optimization if the sub }
  6878. { comes from setting up the stack frame (JM) }
  6879. (not(GetLastInstruction(p,hp1)) or
  6880. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6881. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6882. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6883. begin
  6884. hp1 := tai(p.next);
  6885. while Assigned(hp1) and
  6886. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6887. not RegReadByInstruction(NR_ESP,hp1) and
  6888. not RegModifiedByInstruction(NR_ESP,hp1) do
  6889. hp1 := tai(hp1.next);
  6890. if Assigned(hp1) and
  6891. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6892. begin
  6893. taicpu(hp1).changeopsize(S_L);
  6894. if taicpu(hp1).oper[0]^.typ=top_reg then
  6895. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6896. hp1 := tai(p.next);
  6897. RemoveCurrentp(p, hp1);
  6898. Result:=true;
  6899. exit;
  6900. end;
  6901. end;
  6902. {$endif i386}
  6903. if DoArithCombineOpt(p) then
  6904. Result:=true;
  6905. end;
  6906. end;
  6907. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6908. var
  6909. TmpBool1,TmpBool2 : Boolean;
  6910. tmpref : treference;
  6911. hp1,hp2: tai;
  6912. mask, shiftval: tcgint;
  6913. begin
  6914. Result:=false;
  6915. { All these optimisations work on "shl/sal const,%reg" }
  6916. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6917. Exit;
  6918. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6919. (taicpu(p).oper[0]^.val <= 3) then
  6920. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6921. begin
  6922. { should we check the next instruction? }
  6923. TmpBool1 := True;
  6924. { have we found an add/sub which could be
  6925. integrated in the lea? }
  6926. TmpBool2 := False;
  6927. reference_reset(tmpref,2,[]);
  6928. TmpRef.index := taicpu(p).oper[1]^.reg;
  6929. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6930. while TmpBool1 and
  6931. GetNextInstruction(p, hp1) and
  6932. (tai(hp1).typ = ait_instruction) and
  6933. ((((taicpu(hp1).opcode = A_ADD) or
  6934. (taicpu(hp1).opcode = A_SUB)) and
  6935. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6936. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6937. (((taicpu(hp1).opcode = A_INC) or
  6938. (taicpu(hp1).opcode = A_DEC)) and
  6939. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6940. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6941. ((taicpu(hp1).opcode = A_LEA) and
  6942. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6943. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6944. (not GetNextInstruction(hp1,hp2) or
  6945. not instrReadsFlags(hp2)) Do
  6946. begin
  6947. TmpBool1 := False;
  6948. if taicpu(hp1).opcode=A_LEA then
  6949. begin
  6950. if (TmpRef.base = NR_NO) and
  6951. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6952. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6953. { Segment register isn't a concern here }
  6954. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6955. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6956. begin
  6957. TmpBool1 := True;
  6958. TmpBool2 := True;
  6959. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6960. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6961. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6962. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6963. RemoveInstruction(hp1);
  6964. end
  6965. end
  6966. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6967. begin
  6968. TmpBool1 := True;
  6969. TmpBool2 := True;
  6970. case taicpu(hp1).opcode of
  6971. A_ADD:
  6972. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6973. A_SUB:
  6974. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6975. else
  6976. internalerror(2019050536);
  6977. end;
  6978. RemoveInstruction(hp1);
  6979. end
  6980. else
  6981. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6982. (((taicpu(hp1).opcode = A_ADD) and
  6983. (TmpRef.base = NR_NO)) or
  6984. (taicpu(hp1).opcode = A_INC) or
  6985. (taicpu(hp1).opcode = A_DEC)) then
  6986. begin
  6987. TmpBool1 := True;
  6988. TmpBool2 := True;
  6989. case taicpu(hp1).opcode of
  6990. A_ADD:
  6991. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6992. A_INC:
  6993. inc(TmpRef.offset);
  6994. A_DEC:
  6995. dec(TmpRef.offset);
  6996. else
  6997. internalerror(2019050535);
  6998. end;
  6999. RemoveInstruction(hp1);
  7000. end;
  7001. end;
  7002. if TmpBool2
  7003. {$ifndef x86_64}
  7004. or
  7005. ((current_settings.optimizecputype < cpu_Pentium2) and
  7006. (taicpu(p).oper[0]^.val <= 3) and
  7007. not(cs_opt_size in current_settings.optimizerswitches))
  7008. {$endif x86_64}
  7009. then
  7010. begin
  7011. if not(TmpBool2) and
  7012. (taicpu(p).oper[0]^.val=1) then
  7013. begin
  7014. taicpu(p).opcode := A_ADD;
  7015. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  7016. end
  7017. else
  7018. begin
  7019. taicpu(p).opcode := A_LEA;
  7020. taicpu(p).loadref(0, TmpRef);
  7021. end;
  7022. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  7023. Result := True;
  7024. end;
  7025. end
  7026. {$ifndef x86_64}
  7027. else if (current_settings.optimizecputype < cpu_Pentium2) then
  7028. begin
  7029. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  7030. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  7031. (unlike shl, which is only Tairable in the U pipe) }
  7032. if taicpu(p).oper[0]^.val=1 then
  7033. begin
  7034. taicpu(p).opcode := A_ADD;
  7035. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  7036. Result := True;
  7037. end
  7038. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  7039. "shl $3, %reg" to "lea (,%reg,8), %reg }
  7040. else if (taicpu(p).opsize = S_L) and
  7041. (taicpu(p).oper[0]^.val<= 3) then
  7042. begin
  7043. reference_reset(tmpref,2,[]);
  7044. TmpRef.index := taicpu(p).oper[1]^.reg;
  7045. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  7046. taicpu(p).opcode := A_LEA;
  7047. taicpu(p).loadref(0, TmpRef);
  7048. Result := True;
  7049. end;
  7050. end
  7051. {$endif x86_64}
  7052. else if
  7053. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  7054. (
  7055. (
  7056. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  7057. SetAndTest(hp1, hp2)
  7058. {$ifdef x86_64}
  7059. ) or
  7060. (
  7061. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  7062. GetNextInstruction(hp1, hp2) and
  7063. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  7064. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7065. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  7066. {$endif x86_64}
  7067. )
  7068. ) and
  7069. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  7070. begin
  7071. { Change:
  7072. shl x, %reg1
  7073. mov -(1<<x), %reg2
  7074. and %reg2, %reg1
  7075. Or:
  7076. shl x, %reg1
  7077. and -(1<<x), %reg1
  7078. To just:
  7079. shl x, %reg1
  7080. Since the and operation only zeroes bits that are already zero from the shl operation
  7081. }
  7082. case taicpu(p).oper[0]^.val of
  7083. 8:
  7084. mask:=$FFFFFFFFFFFFFF00;
  7085. 16:
  7086. mask:=$FFFFFFFFFFFF0000;
  7087. 32:
  7088. mask:=$FFFFFFFF00000000;
  7089. 63:
  7090. { Constant pre-calculated to prevent overflow errors with Int64 }
  7091. mask:=$8000000000000000;
  7092. else
  7093. begin
  7094. if taicpu(p).oper[0]^.val >= 64 then
  7095. { Shouldn't happen realistically, since the register
  7096. is guaranteed to be set to zero at this point }
  7097. mask := 0
  7098. else
  7099. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  7100. end;
  7101. end;
  7102. if taicpu(hp1).oper[0]^.val = mask then
  7103. begin
  7104. { Everything checks out, perform the optimisation, as long as
  7105. the FLAGS register isn't being used}
  7106. TransferUsedRegs(TmpUsedRegs);
  7107. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7108. {$ifdef x86_64}
  7109. if (hp1 <> hp2) then
  7110. begin
  7111. { "shl/mov/and" version }
  7112. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  7113. { Don't do the optimisation if the FLAGS register is in use }
  7114. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  7115. begin
  7116. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  7117. { Don't remove the 'mov' instruction if its register is used elsewhere }
  7118. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  7119. begin
  7120. RemoveInstruction(hp1);
  7121. Result := True;
  7122. end;
  7123. { Only set Result to True if the 'mov' instruction was removed }
  7124. RemoveInstruction(hp2);
  7125. end;
  7126. end
  7127. else
  7128. {$endif x86_64}
  7129. begin
  7130. { "shl/and" version }
  7131. { Don't do the optimisation if the FLAGS register is in use }
  7132. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  7133. begin
  7134. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  7135. RemoveInstruction(hp1);
  7136. Result := True;
  7137. end;
  7138. end;
  7139. Exit;
  7140. end
  7141. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  7142. begin
  7143. { Even if the mask doesn't allow for its removal, we might be
  7144. able to optimise the mask for the "shl/and" version, which
  7145. may permit other peephole optimisations }
  7146. {$ifdef DEBUG_AOPTCPU}
  7147. mask := taicpu(hp1).oper[0]^.val and mask;
  7148. if taicpu(hp1).oper[0]^.val <> mask then
  7149. begin
  7150. DebugMsg(
  7151. SPeepholeOptimization +
  7152. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  7153. ' to $' + debug_tostr(mask) +
  7154. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  7155. taicpu(hp1).oper[0]^.val := mask;
  7156. end;
  7157. {$else DEBUG_AOPTCPU}
  7158. { If debugging is off, just set the operand even if it's the same }
  7159. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  7160. {$endif DEBUG_AOPTCPU}
  7161. end;
  7162. end;
  7163. {
  7164. change
  7165. shl/sal const,reg
  7166. <op> ...(...,reg,1),...
  7167. into
  7168. <op> ...(...,reg,1 shl const),...
  7169. if const in 1..3
  7170. }
  7171. if MatchOpType(taicpu(p), top_const, top_reg) and
  7172. (taicpu(p).oper[0]^.val in [1..3]) and
  7173. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  7174. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  7175. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  7176. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  7177. MatchOpType(taicpu(hp1),top_ref))
  7178. ) and
  7179. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  7180. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  7181. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  7182. begin
  7183. TransferUsedRegs(TmpUsedRegs);
  7184. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7185. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  7186. begin
  7187. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  7188. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  7189. RemoveCurrentP(p);
  7190. Result:=true;
  7191. exit;
  7192. end;
  7193. end;
  7194. if MatchOpType(taicpu(p), top_const, top_reg) and
  7195. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  7196. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  7197. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7198. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  7199. begin
  7200. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  7201. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  7202. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  7203. {$ifdef x86_64}
  7204. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  7205. {$endif x86_64}
  7206. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  7207. begin
  7208. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  7209. taicpu(hp1).opcode:=A_MOV;
  7210. taicpu(hp1).oper[0]^.val:=0;
  7211. end
  7212. else
  7213. begin
  7214. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  7215. taicpu(hp1).oper[0]^.val:=shiftval;
  7216. end;
  7217. RemoveCurrentP(p);
  7218. Result:=true;
  7219. exit;
  7220. end;
  7221. end;
  7222. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  7223. begin
  7224. case shr_size of
  7225. S_B:
  7226. { No valid combinations }
  7227. Result := False;
  7228. S_W:
  7229. Result := (Shift >= 8) and (movz_size = S_BW);
  7230. S_L:
  7231. Result :=
  7232. (Shift >= 24) { Any opsize is valid for this shift } or
  7233. ((Shift >= 16) and (movz_size = S_WL));
  7234. {$ifdef x86_64}
  7235. S_Q:
  7236. Result :=
  7237. (Shift >= 56) { Any opsize is valid for this shift } or
  7238. ((Shift >= 48) and (movz_size = S_WL));
  7239. {$endif x86_64}
  7240. else
  7241. InternalError(2022081510);
  7242. end;
  7243. end;
  7244. function TX86AsmOptimizer.HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  7245. var
  7246. hp1, hp2: tai;
  7247. IdentityMask, Shift: TCGInt;
  7248. LimitSize: Topsize;
  7249. DoNotMerge: Boolean;
  7250. begin
  7251. if not MatchInstruction(p, A_SHR, []) then
  7252. InternalError(2025040301);
  7253. Result := False;
  7254. DoNotMerge := False;
  7255. Shift := taicpu(p).oper[0]^.val;
  7256. LimitSize := taicpu(p).opsize;
  7257. hp1 := p;
  7258. repeat
  7259. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  7260. Exit;
  7261. case taicpu(hp1).opcode of
  7262. A_AND:
  7263. { Detect:
  7264. shr x, %reg
  7265. and y, %reg
  7266. If and y, %reg doesn't actually change the value of %reg (e.g. with
  7267. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  7268. (Post-peephole only)
  7269. }
  7270. if PostPeephole and
  7271. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7272. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7273. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7274. begin
  7275. { Make sure the FLAGS register isn't in use }
  7276. TransferUsedRegs(TmpUsedRegs);
  7277. hp2 := p;
  7278. repeat
  7279. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7280. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7281. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7282. begin
  7283. { Generate the identity mask }
  7284. case taicpu(p).opsize of
  7285. S_B:
  7286. IdentityMask := $FF shr Shift;
  7287. S_W:
  7288. IdentityMask := $FFFF shr Shift;
  7289. S_L:
  7290. IdentityMask := $FFFFFFFF shr Shift;
  7291. {$ifdef x86_64}
  7292. S_Q:
  7293. { We need to force the operands to be unsigned 64-bit
  7294. integers otherwise the wrong value is generated }
  7295. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  7296. {$endif x86_64}
  7297. else
  7298. InternalError(2022081501);
  7299. end;
  7300. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  7301. begin
  7302. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  7303. { All the possible 1 bits are covered, so we can remove the AND }
  7304. hp2 := tai(hp1.Previous);
  7305. RemoveInstruction(hp1);
  7306. { p wasn't actually changed, so don't set Result to True,
  7307. but a change was nonetheless made elsewhere }
  7308. Include(OptsToCheck, aoc_ForceNewIteration);
  7309. { Do another pass in case other AND or MOVZX instructions
  7310. follow }
  7311. hp1 := hp2;
  7312. Continue;
  7313. end;
  7314. end;
  7315. end;
  7316. A_TEST, A_CMP:
  7317. { Skip over relevant comparisons, but shift instructions must
  7318. now not be merged since the original value is being read }
  7319. begin
  7320. DoNotMerge := True;
  7321. Continue;
  7322. end;
  7323. A_Jcc:
  7324. { Skip over conditional jumps and relevant comparisons }
  7325. Continue;
  7326. A_MOVZX:
  7327. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  7328. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  7329. begin
  7330. { Since the original register is being read as is, subsequent
  7331. SHRs must not be merged at this point }
  7332. DoNotMerge := True;
  7333. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  7334. begin
  7335. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  7336. begin
  7337. { If the MOVZX instruction reads and writes the same register,
  7338. defer this to the post-peephole optimisation stage }
  7339. if PostPeephole then
  7340. begin
  7341. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  7342. { All the possible 1 bits are covered, so we can remove the MOVZX }
  7343. hp2 := tai(hp1.Previous);
  7344. RemoveInstruction(hp1);
  7345. hp1 := hp2;
  7346. end;
  7347. end
  7348. else { Different register target }
  7349. begin
  7350. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  7351. taicpu(hp1).opcode := A_MOV;
  7352. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  7353. case taicpu(hp1).opsize of
  7354. S_BW:
  7355. taicpu(hp1).opsize := S_W;
  7356. S_BL, S_WL:
  7357. taicpu(hp1).opsize := S_L;
  7358. else
  7359. InternalError(2022081503);
  7360. end;
  7361. { p itself hasn't changed, so no need to set Result to True }
  7362. Include(OptsToCheck, aoc_ForceNewIteration);
  7363. { See if there's anything afterwards that can be
  7364. optimised, since the input register hasn't changed }
  7365. Continue;
  7366. end;
  7367. Exit;
  7368. end
  7369. else if PostPeephole and
  7370. (Shift > 0) and
  7371. (taicpu(p).opsize = S_W) and
  7372. (taicpu(hp1).opsize = S_WL) and
  7373. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  7374. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  7375. begin
  7376. { Detect:
  7377. shr x, %ax (x > 0)
  7378. ...
  7379. movzwl %ax,%eax
  7380. -
  7381. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  7382. But first, check to see if movzwl %ax,%eax can be removed...
  7383. }
  7384. hp2 := tai(hp1.Previous);
  7385. TransferUsedRegs(TmpUsedRegs);
  7386. UpdateUsedRegsBetween(UsedRegs, p, hp1);
  7387. if PostPeepholeOptMovZX(hp1) then
  7388. hp1 := hp2
  7389. else
  7390. begin
  7391. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  7392. taicpu(hp1).opcode := A_CWDE;
  7393. taicpu(hp1).clearop(0);
  7394. taicpu(hp1).clearop(1);
  7395. taicpu(hp1).ops := 0;
  7396. end;
  7397. RestoreUsedRegs(TmpUsedRegs);
  7398. { Don't need to set aoc_ForceNewIteration if
  7399. PostPeepholeOptMovZX returned True because it's the
  7400. post-peephole stage }
  7401. end;
  7402. { Move onto the next instruction }
  7403. Continue;
  7404. end;
  7405. A_SHL, A_SAL, A_SHR:
  7406. if (taicpu(hp1).opsize <= LimitSize) and
  7407. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7408. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7409. begin
  7410. { Make sure the sizes don't exceed the register size limit
  7411. (measured by the shift value falling below the limit) }
  7412. if taicpu(hp1).opsize < LimitSize then
  7413. LimitSize := taicpu(hp1).opsize;
  7414. if taicpu(hp1).opcode = A_SHR then
  7415. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7416. else
  7417. begin
  7418. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7419. DoNotMerge := True;
  7420. end;
  7421. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7422. Exit;
  7423. { Since we've established that the combined shift is within
  7424. limits, we can actually combine the adjacent SHR
  7425. instructions even if they're different sizes }
  7426. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7427. begin
  7428. hp2 := tai(hp1.Previous);
  7429. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7430. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7431. RemoveInstruction(hp1);
  7432. hp1 := hp2;
  7433. { Though p has changed, only the constant has, and its
  7434. effects can still be detected on the next iteration of
  7435. the repeat..until loop }
  7436. Include(OptsToCheck, aoc_ForceNewIteration);
  7437. end;
  7438. { Move onto the next instruction }
  7439. Continue;
  7440. end;
  7441. else
  7442. ;
  7443. end;
  7444. { If the register isn't actually modified, move onto the next instruction,
  7445. but set DoNotMerge to True since the register is being read }
  7446. if (
  7447. { Under -O2 and below, GetNextInstructionUsingReg only returns
  7448. the next instruction, whether or not it contains the register }
  7449. (cs_opt_level3 in current_settings.optimizerswitches) or
  7450. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1)
  7451. ) and not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  7452. begin
  7453. DoNotMerge := True;
  7454. Continue;
  7455. end;
  7456. Break;
  7457. until False;
  7458. end;
  7459. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  7460. begin
  7461. Result := False;
  7462. { All these optimisations work on "shr const,%reg" }
  7463. if not MatchOpType(taicpu(p), top_const, top_reg) then
  7464. Exit;
  7465. Result := HandleSHRMerge(p, False);
  7466. end;
  7467. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7468. var
  7469. CurrentRef: TReference;
  7470. FullReg: TRegister;
  7471. hp1, hp2: tai;
  7472. begin
  7473. Result := False;
  7474. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7475. Exit;
  7476. { We assume you've checked if the operand is actually a reference by
  7477. this point. If it isn't, you'll most likely get an access violation }
  7478. CurrentRef := first_mov.oper[1]^.ref^;
  7479. { Memory must be aligned }
  7480. if (CurrentRef.offset mod 4) <> 0 then
  7481. Exit;
  7482. Inc(CurrentRef.offset);
  7483. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7484. if MatchOperand(second_mov.oper[0]^, 0) and
  7485. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7486. GetNextInstruction(second_mov, hp1) and
  7487. (hp1.typ = ait_instruction) and
  7488. (taicpu(hp1).opcode = A_MOV) and
  7489. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7490. (taicpu(hp1).oper[0]^.val = 0) then
  7491. begin
  7492. Inc(CurrentRef.offset);
  7493. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7494. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7495. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7496. begin
  7497. case taicpu(hp1).opsize of
  7498. S_B:
  7499. if GetNextInstruction(hp1, hp2) and
  7500. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7501. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7502. (taicpu(hp2).oper[0]^.val = 0) then
  7503. begin
  7504. Inc(CurrentRef.offset);
  7505. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7506. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7507. (taicpu(hp2).opsize = S_B) then
  7508. begin
  7509. RemoveInstruction(hp1);
  7510. RemoveInstruction(hp2);
  7511. first_mov.opsize := S_L;
  7512. if first_mov.oper[0]^.typ = top_reg then
  7513. begin
  7514. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7515. { Reuse second_mov as a MOVZX instruction }
  7516. second_mov.opcode := A_MOVZX;
  7517. second_mov.opsize := S_BL;
  7518. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7519. second_mov.loadreg(1, FullReg);
  7520. first_mov.oper[0]^.reg := FullReg;
  7521. asml.Remove(second_mov);
  7522. asml.InsertBefore(second_mov, first_mov);
  7523. end
  7524. else
  7525. { It's a value }
  7526. begin
  7527. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7528. RemoveInstruction(second_mov);
  7529. end;
  7530. Result := True;
  7531. Exit;
  7532. end;
  7533. end;
  7534. S_W:
  7535. begin
  7536. RemoveInstruction(hp1);
  7537. first_mov.opsize := S_L;
  7538. if first_mov.oper[0]^.typ = top_reg then
  7539. begin
  7540. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7541. { Reuse second_mov as a MOVZX instruction }
  7542. second_mov.opcode := A_MOVZX;
  7543. second_mov.opsize := S_BL;
  7544. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7545. second_mov.loadreg(1, FullReg);
  7546. first_mov.oper[0]^.reg := FullReg;
  7547. asml.Remove(second_mov);
  7548. asml.InsertBefore(second_mov, first_mov);
  7549. end
  7550. else
  7551. { It's a value }
  7552. begin
  7553. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7554. RemoveInstruction(second_mov);
  7555. end;
  7556. Result := True;
  7557. Exit;
  7558. end;
  7559. else
  7560. ;
  7561. end;
  7562. end;
  7563. end;
  7564. end;
  7565. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7566. { returns true if a "continue" should be done after this optimization }
  7567. var
  7568. hp1, hp2, hp3: tai;
  7569. begin
  7570. Result := false;
  7571. hp3 := nil;
  7572. if MatchOpType(taicpu(p),top_ref) and
  7573. GetNextInstruction(p, hp1) and
  7574. (hp1.typ = ait_instruction) and
  7575. (((taicpu(hp1).opcode = A_FLD) and
  7576. (taicpu(p).opcode = A_FSTP)) or
  7577. ((taicpu(p).opcode = A_FISTP) and
  7578. (taicpu(hp1).opcode = A_FILD))) and
  7579. MatchOpType(taicpu(hp1),top_ref) and
  7580. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7581. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7582. begin
  7583. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7584. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7585. GetNextInstruction(hp1, hp2) and
  7586. (((hp2.typ = ait_instruction) and
  7587. IsExitCode(hp2) and
  7588. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7589. not(assigned(current_procinfo.procdef.funcretsym) and
  7590. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7591. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7592. { fstp <temp>
  7593. fld <temp>
  7594. <dealloc> <temp>
  7595. }
  7596. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7597. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7598. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7599. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7600. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7601. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7602. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7603. )
  7604. )
  7605. ) then
  7606. begin
  7607. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7608. RemoveInstruction(hp1);
  7609. RemoveCurrentP(p, hp2);
  7610. { first case: exit code }
  7611. if hp2.typ = ait_instruction then
  7612. RemoveLastDeallocForFuncRes(p);
  7613. Result := true;
  7614. end
  7615. else
  7616. { we can do this only in fast math mode as fstp is rounding ...
  7617. ... still disabled as it breaks the compiler and/or rtl }
  7618. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7619. { ... or if another fstp equal to the first one follows }
  7620. GetNextInstruction(hp1,hp2) and
  7621. (hp2.typ = ait_instruction) and
  7622. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7623. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7624. begin
  7625. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7626. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7627. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7628. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7629. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7630. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7631. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7632. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7633. ) then
  7634. begin
  7635. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7636. RemoveCurrentP(p,hp2);
  7637. RemoveInstruction(hp1);
  7638. Result := true;
  7639. end
  7640. else if { fst can't store an extended/comp value }
  7641. (taicpu(p).opsize <> S_FX) and
  7642. (taicpu(p).opsize <> S_IQ) then
  7643. begin
  7644. if (taicpu(p).opcode = A_FSTP) then
  7645. taicpu(p).opcode := A_FST
  7646. else
  7647. taicpu(p).opcode := A_FIST;
  7648. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7649. RemoveInstruction(hp1);
  7650. Result := true;
  7651. end;
  7652. end;
  7653. end;
  7654. end;
  7655. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7656. var
  7657. hp1, hp2, hp3: tai;
  7658. begin
  7659. result:=false;
  7660. if MatchOpType(taicpu(p),top_reg) and
  7661. GetNextInstruction(p, hp1) and
  7662. (hp1.typ = Ait_Instruction) and
  7663. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7664. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7665. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7666. { change to
  7667. fld reg fxxx reg,st
  7668. fxxxp st, st1 (hp1)
  7669. Remark: non commutative operations must be reversed!
  7670. }
  7671. begin
  7672. case taicpu(hp1).opcode Of
  7673. A_FMULP,A_FADDP,
  7674. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7675. begin
  7676. case taicpu(hp1).opcode Of
  7677. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7678. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7679. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7680. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7681. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7682. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7683. else
  7684. internalerror(2019050534);
  7685. end;
  7686. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7687. taicpu(hp1).oper[1]^.reg := NR_ST;
  7688. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7689. RemoveCurrentP(p, hp1);
  7690. Result:=true;
  7691. exit;
  7692. end;
  7693. else
  7694. ;
  7695. end;
  7696. end
  7697. else
  7698. if MatchOpType(taicpu(p),top_ref) and
  7699. GetNextInstruction(p, hp2) and
  7700. (hp2.typ = Ait_Instruction) and
  7701. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7702. (taicpu(p).opsize in [S_FS, S_FL]) and
  7703. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7704. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7705. if GetLastInstruction(p, hp1) and
  7706. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7707. MatchOpType(taicpu(hp1),top_ref) and
  7708. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7709. if ((taicpu(hp2).opcode = A_FMULP) or
  7710. (taicpu(hp2).opcode = A_FADDP)) then
  7711. { change to
  7712. fld/fst mem1 (hp1) fld/fst mem1
  7713. fld mem1 (p) fadd/
  7714. faddp/ fmul st, st
  7715. fmulp st, st1 (hp2) }
  7716. begin
  7717. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7718. RemoveCurrentP(p, hp1);
  7719. if (taicpu(hp2).opcode = A_FADDP) then
  7720. taicpu(hp2).opcode := A_FADD
  7721. else
  7722. taicpu(hp2).opcode := A_FMUL;
  7723. taicpu(hp2).oper[1]^.reg := NR_ST;
  7724. end
  7725. else
  7726. { change to
  7727. fld/fst mem1 (hp1) fld/fst mem1
  7728. fld mem1 (p) fld st
  7729. }
  7730. begin
  7731. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7732. taicpu(p).changeopsize(S_FL);
  7733. taicpu(p).loadreg(0,NR_ST);
  7734. end
  7735. else
  7736. begin
  7737. case taicpu(hp2).opcode Of
  7738. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7739. { change to
  7740. fld/fst mem1 (hp1) fld/fst mem1
  7741. fld mem2 (p) fxxx mem2
  7742. fxxxp st, st1 (hp2) }
  7743. begin
  7744. case taicpu(hp2).opcode Of
  7745. A_FADDP: taicpu(p).opcode := A_FADD;
  7746. A_FMULP: taicpu(p).opcode := A_FMUL;
  7747. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7748. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7749. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7750. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7751. else
  7752. internalerror(2019050533);
  7753. end;
  7754. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7755. RemoveInstruction(hp2);
  7756. end
  7757. else
  7758. ;
  7759. end
  7760. end
  7761. end;
  7762. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7763. begin
  7764. Result := condition_in(cond1, cond2) or
  7765. { Not strictly subsets due to the actual flags checked, but because we're
  7766. comparing integers, E is a subset of AE and GE and their aliases }
  7767. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7768. end;
  7769. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7770. var
  7771. v: TCGInt;
  7772. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7773. FirstMatch, TempBool: Boolean;
  7774. NewReg: TRegister;
  7775. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7776. begin
  7777. Result:=false;
  7778. { All these optimisations need a next instruction }
  7779. if not GetNextInstruction(p, hp1) then
  7780. Exit;
  7781. true_hp1 := hp1;
  7782. { Search for:
  7783. cmp ###,###
  7784. j(c1) @lbl1
  7785. ...
  7786. @lbl:
  7787. cmp ###,### (same comparison as above)
  7788. j(c2) @lbl2
  7789. If c1 is a subset of c2, change to:
  7790. cmp ###,###
  7791. j(c1) @lbl2
  7792. (@lbl1 may become a dead label as a result)
  7793. }
  7794. { Also handle cases where there are multiple jumps in a row }
  7795. p_jump := hp1;
  7796. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7797. begin
  7798. Prefetch(p_jump.Next);
  7799. if IsJumpToLabel(taicpu(p_jump)) then
  7800. begin
  7801. { Do jump optimisations first in case the condition becomes
  7802. unnecessary }
  7803. TempBool := True;
  7804. if DoJumpOptimizations(p_jump, TempBool) or
  7805. not TempBool then
  7806. begin
  7807. if Assigned(p_jump) then
  7808. begin
  7809. { CollapseZeroDistJump will be set to the label or an align
  7810. before it after the jump if it optimises, whether or not
  7811. the label is live or dead }
  7812. if (p_jump.typ = ait_align) or
  7813. (
  7814. (p_jump.typ = ait_label) and
  7815. not (tai_label(p_jump).labsym.is_used)
  7816. ) then
  7817. GetNextInstruction(p_jump, p_jump);
  7818. end;
  7819. TransferUsedRegs(TmpUsedRegs);
  7820. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7821. if not Assigned(p_jump) or
  7822. (
  7823. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7824. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7825. ) then
  7826. begin
  7827. { No more conditional jumps; conditional statement is no longer required }
  7828. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7829. RemoveCurrentP(p);
  7830. Result := True;
  7831. Exit;
  7832. end;
  7833. hp1 := p_jump;
  7834. Include(OptsToCheck, aoc_ForceNewIteration);
  7835. Continue;
  7836. end;
  7837. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7838. if GetNextInstruction(p_jump, hp2) and
  7839. (
  7840. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7841. not TempBool
  7842. ) then
  7843. begin
  7844. hp1 := p_jump;
  7845. Include(OptsToCheck, aoc_ForceNewIteration);
  7846. Continue;
  7847. end;
  7848. p_label := nil;
  7849. if Assigned(JumpLabel) then
  7850. p_label := getlabelwithsym(JumpLabel);
  7851. if Assigned(p_label) and
  7852. GetNextInstruction(p_label, p_dist) and
  7853. MatchInstruction(p_dist, A_CMP, []) and
  7854. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7855. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7856. GetNextInstruction(p_dist, hp1_dist) and
  7857. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7858. begin
  7859. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7860. if JumpLabel = JumpLabel_dist then
  7861. { This is an infinite loop }
  7862. Exit;
  7863. { Best optimisation when the first condition is a subset (or equal) of the second }
  7864. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7865. begin
  7866. { Any registers used here will already be allocated }
  7867. if Assigned(JumpLabel) then
  7868. JumpLabel.DecRefs;
  7869. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7870. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7871. Include(OptsToCheck, aoc_ForceNewIteration);
  7872. { Don't exit yet. Since p and p_jump haven't actually been
  7873. removed, we can check for more on this iteration }
  7874. end
  7875. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7876. GetNextInstruction(hp1_dist, hp1_label) and
  7877. (hp1_label.typ = ait_label) then
  7878. begin
  7879. JumpLabel_far := tai_label(hp1_label).labsym;
  7880. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7881. { This is an infinite loop }
  7882. Exit;
  7883. if Assigned(JumpLabel_far) then
  7884. begin
  7885. { In this situation, if the first jump branches, the second one will never,
  7886. branch so change the destination label to after the second jump }
  7887. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7888. if Assigned(JumpLabel) then
  7889. JumpLabel.DecRefs;
  7890. JumpLabel_far.IncRefs;
  7891. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7892. Result := True;
  7893. { Don't exit yet. Since p and p_jump haven't actually been
  7894. removed, we can check for more on this iteration }
  7895. Continue;
  7896. end;
  7897. end;
  7898. end;
  7899. end;
  7900. { Search for:
  7901. cmp ###,###
  7902. j(c1) @lbl1
  7903. cmp ###,### (same as first)
  7904. Remove second cmp
  7905. }
  7906. if GetNextInstruction(p_jump, hp2) and
  7907. (
  7908. (
  7909. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7910. (
  7911. (
  7912. MatchOpType(taicpu(p), top_const, top_reg) and
  7913. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7914. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7915. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7916. ) or (
  7917. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7918. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7919. )
  7920. )
  7921. ) or (
  7922. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7923. MatchOperand(taicpu(p).oper[0]^, 0) and
  7924. (taicpu(p).oper[1]^.typ = top_reg) and
  7925. MatchInstruction(hp2, A_TEST, []) and
  7926. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7927. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7928. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7929. )
  7930. ) then
  7931. begin
  7932. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7933. TransferUsedRegs(TmpUsedRegs);
  7934. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7935. RemoveInstruction(hp2);
  7936. Result := True;
  7937. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7938. end
  7939. else
  7940. begin
  7941. { hp2 is the next instruction, so save time and just set p_jump
  7942. to it instead of calling GetNextInstruction below }
  7943. p_jump := hp2;
  7944. Continue;
  7945. end;
  7946. GetNextInstruction(p_jump, p_jump);
  7947. end;
  7948. if (
  7949. { Don't call GetNextInstruction again if we already have it }
  7950. (true_hp1 = p_jump) or
  7951. GetNextInstruction(p, hp1)
  7952. ) and
  7953. MatchInstruction(hp1, A_Jcc, []) and
  7954. IsJumpToLabel(taicpu(hp1)) and
  7955. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7956. GetNextInstruction(hp1, hp2) then
  7957. begin
  7958. {
  7959. cmp x, y (or "cmp y, x")
  7960. je @lbl
  7961. mov x, y
  7962. @lbl:
  7963. (x and y can be constants, registers or references)
  7964. Change to:
  7965. mov x, y (x and y will always be equal in the end)
  7966. @lbl: (may beceome a dead label)
  7967. Also:
  7968. cmp x, y (or "cmp y, x")
  7969. jne @lbl
  7970. mov x, y
  7971. @lbl:
  7972. (x and y can be constants, registers or references)
  7973. Change to:
  7974. Absolutely nothing! (Except @lbl if it's still live)
  7975. }
  7976. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7977. (
  7978. (
  7979. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7980. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7981. ) or (
  7982. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7983. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7984. )
  7985. ) and
  7986. GetNextInstruction(hp2, hp1_label) and
  7987. (hp1_label.typ = ait_label) and
  7988. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7989. begin
  7990. tai_label(hp1_label).labsym.DecRefs;
  7991. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7992. begin
  7993. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7994. RemoveInstruction(hp2);
  7995. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7996. end
  7997. else
  7998. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7999. RemoveInstruction(hp1);
  8000. RemoveCurrentp(p, hp2);
  8001. Result := True;
  8002. Exit;
  8003. end;
  8004. {
  8005. Try to optimise the following:
  8006. cmp $x,### ($x and $y can be registers or constants)
  8007. je @lbl1 (only reference)
  8008. cmp $y,### (### are identical)
  8009. @Lbl:
  8010. sete %reg1
  8011. Change to:
  8012. cmp $x,###
  8013. sete %reg2 (allocate new %reg2)
  8014. cmp $y,###
  8015. sete %reg1
  8016. orb %reg2,%reg1
  8017. (dealloc %reg2)
  8018. This adds an instruction (so don't perform under -Os), but it removes
  8019. a conditional branch.
  8020. }
  8021. if not (cs_opt_size in current_settings.optimizerswitches) and
  8022. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  8023. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  8024. { The first operand of CMP instructions can only be a register or
  8025. immediate anyway, so no need to check }
  8026. GetNextInstruction(hp2, p_label) and
  8027. (p_label.typ = ait_label) and
  8028. (tai_label(p_label).labsym.getrefs = 1) and
  8029. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  8030. GetNextInstruction(p_label, p_dist) and
  8031. MatchInstruction(p_dist, A_SETcc, []) and
  8032. (taicpu(p_dist).condition in [C_E, C_Z]) and
  8033. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8034. begin
  8035. TransferUsedRegs(TmpUsedRegs);
  8036. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8037. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8038. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  8039. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  8040. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  8041. { Get the instruction after the SETcc instruction so we can
  8042. allocate a new register over the entire range }
  8043. GetNextInstruction(p_dist, hp1_dist) then
  8044. begin
  8045. { Register can appear in p if it's not used afterwards, so only
  8046. allocate between hp1 and hp1_dist }
  8047. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  8048. if NewReg <> NR_NO then
  8049. begin
  8050. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  8051. { Change the jump instruction into a SETcc instruction }
  8052. taicpu(hp1).opcode := A_SETcc;
  8053. taicpu(hp1).opsize := S_B;
  8054. taicpu(hp1).loadreg(0, NewReg);
  8055. { This is now a dead label }
  8056. tai_label(p_label).labsym.decrefs;
  8057. { Prefer adding before the next instruction so the FLAGS
  8058. register is deallicated first }
  8059. AsmL.InsertBefore(
  8060. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  8061. hp1_dist
  8062. );
  8063. Result := True;
  8064. { Don't exit yet, as p wasn't changed and hp1, while
  8065. modified, is still intact and might be optimised by the
  8066. SETcc optimisation below }
  8067. end;
  8068. end;
  8069. end;
  8070. end;
  8071. if (taicpu(p).oper[0]^.typ = top_const) and
  8072. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  8073. begin
  8074. if (taicpu(p).oper[0]^.val = 0) and
  8075. (taicpu(p).oper[1]^.typ = top_reg) then
  8076. begin
  8077. hp2 := p;
  8078. FirstMatch := True;
  8079. { When dealing with "cmp $0,%reg", only ZF and SF contain
  8080. anything meaningful once it's converted to "test %reg,%reg";
  8081. additionally, some jumps will always (or never) branch, so
  8082. evaluate every jump immediately following the
  8083. comparison, optimising the conditions if possible.
  8084. Similarly with SETcc... those that are always set to 0 or 1
  8085. are changed to MOV instructions }
  8086. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  8087. (
  8088. GetNextInstruction(hp2, hp1) and
  8089. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  8090. ) do
  8091. begin
  8092. Prefetch(hp1.Next);
  8093. FirstMatch := False;
  8094. case taicpu(hp1).condition of
  8095. C_B, C_C, C_NAE, C_O:
  8096. { For B/NAE:
  8097. Will never branch since an unsigned integer can never be below zero
  8098. For C/O:
  8099. Result cannot overflow because 0 is being subtracted
  8100. }
  8101. begin
  8102. if taicpu(hp1).opcode = A_Jcc then
  8103. begin
  8104. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  8105. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  8106. RemoveInstruction(hp1);
  8107. { Since hp1 was deleted, hp2 must not be updated }
  8108. Continue;
  8109. end
  8110. else
  8111. begin
  8112. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  8113. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  8114. taicpu(hp1).opcode := A_MOV;
  8115. taicpu(hp1).ops := 2;
  8116. taicpu(hp1).condition := C_None;
  8117. taicpu(hp1).opsize := S_B;
  8118. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8119. taicpu(hp1).loadconst(0, 0);
  8120. end;
  8121. end;
  8122. C_BE, C_NA:
  8123. begin
  8124. { Will only branch if equal to zero }
  8125. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  8126. taicpu(hp1).condition := C_E;
  8127. end;
  8128. C_A, C_NBE:
  8129. begin
  8130. { Will only branch if not equal to zero }
  8131. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  8132. taicpu(hp1).condition := C_NE;
  8133. end;
  8134. C_AE, C_NB, C_NC, C_NO:
  8135. begin
  8136. { Will always branch }
  8137. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  8138. if taicpu(hp1).opcode = A_Jcc then
  8139. begin
  8140. MakeUnconditional(taicpu(hp1));
  8141. { Any jumps/set that follow will now be dead code }
  8142. RemoveDeadCodeAfterJump(taicpu(hp1));
  8143. Break;
  8144. end
  8145. else
  8146. begin
  8147. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  8148. taicpu(hp1).opcode := A_MOV;
  8149. taicpu(hp1).ops := 2;
  8150. taicpu(hp1).condition := C_None;
  8151. taicpu(hp1).opsize := S_B;
  8152. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8153. taicpu(hp1).loadconst(0, 1);
  8154. end;
  8155. end;
  8156. C_None:
  8157. InternalError(2020012201);
  8158. C_P, C_PE, C_NP, C_PO:
  8159. { We can't handle parity checks and they should never be generated
  8160. after a general-purpose CMP (it's used in some floating-point
  8161. comparisons that don't use CMP) }
  8162. InternalError(2020012202);
  8163. else
  8164. { Zero/Equality, Sign, their complements and all of the
  8165. signed comparisons do not need to be converted };
  8166. end;
  8167. hp2 := hp1;
  8168. end;
  8169. { Convert the instruction to a TEST }
  8170. taicpu(p).opcode := A_TEST;
  8171. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8172. Result := True;
  8173. Exit;
  8174. end
  8175. else
  8176. begin
  8177. TransferUsedRegs(TmpUsedRegs);
  8178. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8179. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8180. begin
  8181. if (taicpu(p).oper[0]^.val = 1) and
  8182. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  8183. begin
  8184. { Convert; To:
  8185. cmp $1,r/m cmp $0,r/m
  8186. jl @lbl jle @lbl
  8187. (Also do inverted conditions)
  8188. }
  8189. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  8190. taicpu(p).oper[0]^.val := 0;
  8191. if taicpu(hp1).condition in [C_L, C_NGE] then
  8192. taicpu(hp1).condition := C_LE
  8193. else
  8194. taicpu(hp1).condition := C_NLE;
  8195. { If the instruction is now "cmp $0,%reg", convert it to a
  8196. TEST (and effectively do the work of the "cmp $0,%reg" in
  8197. the block above)
  8198. }
  8199. if (taicpu(p).oper[1]^.typ = top_reg) then
  8200. begin
  8201. taicpu(p).opcode := A_TEST;
  8202. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8203. end;
  8204. Result := True;
  8205. Exit;
  8206. end
  8207. else if (taicpu(p).oper[1]^.typ = top_reg)
  8208. {$ifdef x86_64}
  8209. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  8210. {$endif x86_64}
  8211. then
  8212. begin
  8213. { cmp register,$8000 neg register
  8214. je target --> jo target
  8215. .... only if register is deallocated before jump.}
  8216. case Taicpu(p).opsize of
  8217. S_B: v:=$80;
  8218. S_W: v:=$8000;
  8219. S_L: v:=qword($80000000);
  8220. else
  8221. internalerror(2013112905);
  8222. end;
  8223. if (taicpu(p).oper[0]^.val=v) and
  8224. (Taicpu(hp1).condition in [C_E,C_NE]) then
  8225. begin
  8226. TransferUsedRegs(TmpUsedRegs);
  8227. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  8228. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  8229. begin
  8230. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  8231. Taicpu(p).opcode:=A_NEG;
  8232. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  8233. Taicpu(p).clearop(1);
  8234. Taicpu(p).ops:=1;
  8235. if Taicpu(hp1).condition=C_E then
  8236. Taicpu(hp1).condition:=C_O
  8237. else
  8238. Taicpu(hp1).condition:=C_NO;
  8239. Result:=true;
  8240. exit;
  8241. end;
  8242. end;
  8243. end;
  8244. end;
  8245. end;
  8246. end;
  8247. if TrySwapMovCmp(p, hp1) then
  8248. begin
  8249. Result := True;
  8250. Exit;
  8251. end;
  8252. end;
  8253. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  8254. var
  8255. hp1: tai;
  8256. begin
  8257. {
  8258. remove the second (v)pxor from
  8259. pxor reg,reg
  8260. ...
  8261. pxor reg,reg
  8262. }
  8263. Result:=false;
  8264. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8265. MatchOpType(taicpu(p),top_reg,top_reg) and
  8266. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8267. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8268. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8269. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  8270. begin
  8271. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  8272. RemoveInstruction(hp1);
  8273. Result:=true;
  8274. Exit;
  8275. end
  8276. {
  8277. replace
  8278. pxor reg1,reg1
  8279. movapd/s reg1,reg2
  8280. dealloc reg1
  8281. by
  8282. pxor reg2,reg2
  8283. }
  8284. else if GetNextInstruction(p,hp1) and
  8285. { we mix single and double opperations here because we assume that the compiler
  8286. generates vmovapd only after double operations and vmovaps only after single operations }
  8287. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  8288. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8289. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  8290. (taicpu(p).oper[0]^.typ=top_reg) then
  8291. begin
  8292. TransferUsedRegs(TmpUsedRegs);
  8293. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8294. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8295. begin
  8296. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  8297. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  8298. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  8299. RemoveInstruction(hp1);
  8300. result:=true;
  8301. end;
  8302. end;
  8303. end;
  8304. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  8305. var
  8306. hp1: tai;
  8307. begin
  8308. {
  8309. remove the second (v)pxor from
  8310. (v)pxor reg,reg
  8311. ...
  8312. (v)pxor reg,reg
  8313. }
  8314. Result:=false;
  8315. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  8316. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8317. begin
  8318. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8319. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8320. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8321. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  8322. begin
  8323. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  8324. RemoveInstruction(hp1);
  8325. Result:=true;
  8326. Exit;
  8327. end;
  8328. {$ifdef x86_64}
  8329. {
  8330. replace
  8331. vpxor reg1,reg1,reg1
  8332. vmov reg,mem
  8333. by
  8334. movq $0,mem
  8335. }
  8336. if GetNextInstruction(p,hp1) and
  8337. MatchInstruction(hp1,A_VMOVSD,[]) and
  8338. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8339. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  8340. begin
  8341. TransferUsedRegs(TmpUsedRegs);
  8342. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8343. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8344. begin
  8345. taicpu(hp1).loadconst(0,0);
  8346. taicpu(hp1).opcode:=A_MOV;
  8347. taicpu(hp1).opsize:=S_Q;
  8348. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  8349. RemoveCurrentP(p);
  8350. result:=true;
  8351. Exit;
  8352. end;
  8353. end;
  8354. {$endif x86_64}
  8355. end
  8356. {
  8357. replace
  8358. vpxor reg1,reg1,reg2
  8359. by
  8360. vpxor reg2,reg2,reg2
  8361. to avoid unncessary data dependencies
  8362. }
  8363. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8364. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8365. begin
  8366. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  8367. { avoid unncessary data dependency }
  8368. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  8369. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  8370. result:=true;
  8371. exit;
  8372. end;
  8373. Result:=OptPass1VOP(p);
  8374. end;
  8375. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  8376. var
  8377. hp1 : tai;
  8378. begin
  8379. result:=false;
  8380. { replace
  8381. IMul const,%mreg1,%mreg2
  8382. Mov %reg2,%mreg3
  8383. dealloc %mreg3
  8384. by
  8385. Imul const,%mreg1,%mreg23
  8386. }
  8387. if (taicpu(p).ops=3) and
  8388. GetNextInstruction(p,hp1) and
  8389. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8390. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8391. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8392. begin
  8393. TransferUsedRegs(TmpUsedRegs);
  8394. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8395. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8396. begin
  8397. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8398. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  8399. RemoveInstruction(hp1);
  8400. result:=true;
  8401. end;
  8402. end;
  8403. end;
  8404. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  8405. var
  8406. hp1 : tai;
  8407. begin
  8408. result:=false;
  8409. { replace
  8410. IMul %reg0,%reg1,%reg2
  8411. Mov %reg2,%reg3
  8412. dealloc %reg2
  8413. by
  8414. Imul %reg0,%reg1,%reg3
  8415. }
  8416. if GetNextInstruction(p,hp1) and
  8417. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8418. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8419. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8420. begin
  8421. TransferUsedRegs(TmpUsedRegs);
  8422. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8423. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8424. begin
  8425. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8426. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8427. RemoveInstruction(hp1);
  8428. result:=true;
  8429. end;
  8430. end;
  8431. end;
  8432. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8433. var
  8434. hp1: tai;
  8435. begin
  8436. Result:=false;
  8437. { get rid of
  8438. (v)cvtss2sd reg0,<reg1,>reg2
  8439. (v)cvtss2sd reg2,<reg2,>reg0
  8440. }
  8441. if GetNextInstruction(p,hp1) and
  8442. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8443. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8444. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8445. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8446. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8447. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8448. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8449. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8450. )
  8451. ) then
  8452. begin
  8453. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8454. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8455. begin
  8456. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8457. RemoveCurrentP(p);
  8458. RemoveInstruction(hp1);
  8459. end
  8460. else
  8461. begin
  8462. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8463. if taicpu(hp1).opcode=A_CVTSD2SS then
  8464. begin
  8465. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8466. taicpu(p).opcode:=A_MOVAPS;
  8467. end
  8468. else
  8469. begin
  8470. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8471. taicpu(p).opcode:=A_VMOVAPS;
  8472. end;
  8473. taicpu(p).ops:=2;
  8474. RemoveInstruction(hp1);
  8475. end;
  8476. Result:=true;
  8477. Exit;
  8478. end;
  8479. end;
  8480. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8481. var
  8482. hp1, hp2, hp3, hp4, hp5: tai;
  8483. ThisReg: TRegister;
  8484. begin
  8485. Result := False;
  8486. if not GetNextInstruction(p,hp1) then
  8487. Exit;
  8488. {
  8489. convert
  8490. j<c> .L1
  8491. mov 1,reg
  8492. jmp .L2
  8493. .L1
  8494. mov 0,reg
  8495. .L2
  8496. into
  8497. mov 0,reg
  8498. set<not(c)> reg
  8499. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8500. would destroy the flag contents
  8501. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8502. executed at the same time as a previous comparison.
  8503. set<not(c)> reg
  8504. movzx reg, reg
  8505. }
  8506. if MatchInstruction(hp1,A_MOV,[]) and
  8507. (taicpu(hp1).oper[0]^.typ = top_const) and
  8508. (
  8509. (
  8510. (taicpu(hp1).oper[1]^.typ = top_reg)
  8511. {$ifdef i386}
  8512. { Under i386, ESI, EDI, EBP and ESP
  8513. don't have an 8-bit representation }
  8514. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8515. {$endif i386}
  8516. ) or (
  8517. {$ifdef i386}
  8518. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8519. {$endif i386}
  8520. (taicpu(hp1).opsize = S_B)
  8521. )
  8522. ) and
  8523. GetNextInstruction(hp1,hp2) and
  8524. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8525. GetNextInstruction(hp2,hp3) and
  8526. FindLabel(tasmlabel(taicpu(p).oper[0]^.ref^.symbol), hp3) and
  8527. GetNextInstruction(hp3,hp4) and
  8528. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8529. (taicpu(hp4).oper[0]^.typ = top_const) and
  8530. (
  8531. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8532. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8533. ) and
  8534. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8535. GetNextInstruction(hp4,hp5) and
  8536. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol), hp5) then
  8537. begin
  8538. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8539. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8540. tai_label(hp3).labsym.DecRefs;
  8541. { If this isn't the only reference to the middle label, we can
  8542. still make a saving - only that the first jump and everything
  8543. that follows will remain. }
  8544. if (tai_label(hp3).labsym.getrefs = 0) then
  8545. begin
  8546. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8547. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8548. else
  8549. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8550. { remove jump, first label and second MOV (also catching any aligns) }
  8551. repeat
  8552. if not GetNextInstruction(hp2, hp3) then
  8553. InternalError(2021040810);
  8554. RemoveInstruction(hp2);
  8555. hp2 := hp3;
  8556. until hp2 = hp5;
  8557. { Don't decrement reference count before the removal loop
  8558. above, otherwise GetNextInstruction won't stop on the
  8559. the label }
  8560. tai_label(hp5).labsym.DecRefs;
  8561. end
  8562. else
  8563. begin
  8564. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8565. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8566. else
  8567. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8568. end;
  8569. taicpu(p).opcode:=A_SETcc;
  8570. taicpu(p).opsize:=S_B;
  8571. taicpu(p).is_jmp:=False;
  8572. if taicpu(hp1).opsize=S_B then
  8573. begin
  8574. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8575. if taicpu(hp1).oper[1]^.typ = top_reg then
  8576. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8577. RemoveInstruction(hp1);
  8578. end
  8579. else
  8580. begin
  8581. { Will be a register because the size can't be S_B otherwise }
  8582. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8583. taicpu(p).loadreg(0, ThisReg);
  8584. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8585. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8586. begin
  8587. case taicpu(hp1).opsize of
  8588. S_W:
  8589. taicpu(hp1).opsize := S_BW;
  8590. S_L:
  8591. taicpu(hp1).opsize := S_BL;
  8592. {$ifdef x86_64}
  8593. S_Q:
  8594. begin
  8595. taicpu(hp1).opsize := S_BL;
  8596. { Change the destination register to 32-bit }
  8597. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8598. end;
  8599. {$endif x86_64}
  8600. else
  8601. InternalError(2021040820);
  8602. end;
  8603. taicpu(hp1).opcode := A_MOVZX;
  8604. taicpu(hp1).loadreg(0, ThisReg);
  8605. end
  8606. else
  8607. begin
  8608. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8609. { hp1 is already a MOV instruction with the correct register }
  8610. taicpu(hp1).loadconst(0, 0);
  8611. { Inserting it right before p will guarantee that the flags are also tracked }
  8612. asml.Remove(hp1);
  8613. asml.InsertBefore(hp1, p);
  8614. end;
  8615. end;
  8616. Result:=true;
  8617. exit;
  8618. end
  8619. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8620. Result := TryJccStcClcOpt(p, hp1)
  8621. else if (hp1.typ = ait_label) then
  8622. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8623. end;
  8624. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8625. var
  8626. hp1, hp2, hp3: tai;
  8627. SourceRef, TargetRef: TReference;
  8628. CurrentReg: TRegister;
  8629. begin
  8630. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8631. if not UseAVX then
  8632. InternalError(2021100501);
  8633. Result := False;
  8634. { Look for the following to simplify:
  8635. vmovdqa/u x(mem1), %xmmreg
  8636. vmovdqa/u %xmmreg, y(mem2)
  8637. vmovdqa/u x+16(mem1), %xmmreg
  8638. vmovdqa/u %xmmreg, y+16(mem2)
  8639. Change to:
  8640. vmovdqa/u x(mem1), %ymmreg
  8641. vmovdqa/u %ymmreg, y(mem2)
  8642. vpxor %ymmreg, %ymmreg, %ymmreg
  8643. ( The VPXOR instruction is to zero the upper half, thus removing the
  8644. need to call the potentially expensive VZEROUPPER instruction. Other
  8645. peephole optimisations can remove VPXOR if it's unnecessary )
  8646. }
  8647. TransferUsedRegs(TmpUsedRegs);
  8648. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8649. { NOTE: In the optimisations below, if the references dictate that an
  8650. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8651. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8652. if (taicpu(p).opsize = S_XMM) and
  8653. MatchOpType(taicpu(p), top_ref, top_reg) and
  8654. GetNextInstruction(p, hp1) and
  8655. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8656. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8657. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8658. begin
  8659. SourceRef := taicpu(p).oper[0]^.ref^;
  8660. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8661. if GetNextInstruction(hp1, hp2) and
  8662. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8663. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8664. begin
  8665. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8666. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8667. Inc(SourceRef.offset, 16);
  8668. { Reuse the register in the first block move }
  8669. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8670. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8671. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8672. begin
  8673. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8674. Inc(TargetRef.offset, 16);
  8675. if GetNextInstruction(hp2, hp3) and
  8676. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8677. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8678. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8679. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8680. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8681. begin
  8682. { Update the register tracking to the new size }
  8683. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8684. { Remember that the offsets are 16 ahead }
  8685. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8686. if not (
  8687. ((SourceRef.offset mod 32) = 16) and
  8688. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8689. ) then
  8690. taicpu(p).opcode := A_VMOVDQU;
  8691. taicpu(p).opsize := S_YMM;
  8692. taicpu(p).oper[1]^.reg := CurrentReg;
  8693. if not (
  8694. ((TargetRef.offset mod 32) = 16) and
  8695. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8696. ) then
  8697. taicpu(hp1).opcode := A_VMOVDQU;
  8698. taicpu(hp1).opsize := S_YMM;
  8699. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8700. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8701. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8702. if (pi_uses_ymm in current_procinfo.flags) then
  8703. RemoveInstruction(hp2)
  8704. else
  8705. begin
  8706. taicpu(hp2).opcode := A_VPXOR;
  8707. taicpu(hp2).opsize := S_YMM;
  8708. taicpu(hp2).loadreg(0, CurrentReg);
  8709. taicpu(hp2).loadreg(1, CurrentReg);
  8710. taicpu(hp2).loadreg(2, CurrentReg);
  8711. taicpu(hp2).ops := 3;
  8712. end;
  8713. RemoveInstruction(hp3);
  8714. Result := True;
  8715. Exit;
  8716. end;
  8717. end
  8718. else
  8719. begin
  8720. { See if the next references are 16 less rather than 16 greater }
  8721. Dec(SourceRef.offset, 32); { -16 the other way }
  8722. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8723. begin
  8724. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8725. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8726. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8727. GetNextInstruction(hp2, hp3) and
  8728. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8729. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8730. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8731. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8732. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8733. begin
  8734. { Update the register tracking to the new size }
  8735. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8736. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8737. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8738. if not(
  8739. ((SourceRef.offset mod 32) = 0) and
  8740. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8741. ) then
  8742. taicpu(hp2).opcode := A_VMOVDQU;
  8743. taicpu(hp2).opsize := S_YMM;
  8744. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8745. if not (
  8746. ((TargetRef.offset mod 32) = 0) and
  8747. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8748. ) then
  8749. taicpu(hp3).opcode := A_VMOVDQU;
  8750. taicpu(hp3).opsize := S_YMM;
  8751. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8752. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8753. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8754. if (pi_uses_ymm in current_procinfo.flags) then
  8755. RemoveInstruction(hp1)
  8756. else
  8757. begin
  8758. taicpu(hp1).opcode := A_VPXOR;
  8759. taicpu(hp1).opsize := S_YMM;
  8760. taicpu(hp1).loadreg(0, CurrentReg);
  8761. taicpu(hp1).loadreg(1, CurrentReg);
  8762. taicpu(hp1).loadreg(2, CurrentReg);
  8763. taicpu(hp1).ops := 3;
  8764. Asml.Remove(hp1);
  8765. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8766. end;
  8767. RemoveCurrentP(p, hp2);
  8768. Result := True;
  8769. Exit;
  8770. end;
  8771. end;
  8772. end;
  8773. end;
  8774. end;
  8775. end;
  8776. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8777. var
  8778. hp2, hp3, first_assignment: tai;
  8779. IncCount, OperIdx: Integer;
  8780. OrigLabel: TAsmLabel;
  8781. begin
  8782. Count := 0;
  8783. Result := False;
  8784. first_assignment := nil;
  8785. if (LoopCount >= 20) then
  8786. begin
  8787. { Guard against infinite loops }
  8788. Exit;
  8789. end;
  8790. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8791. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8792. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8793. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8794. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8795. Exit;
  8796. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8797. {
  8798. change
  8799. jmp .L1
  8800. ...
  8801. .L1:
  8802. mov ##, ## ( multiple movs possible )
  8803. jmp/ret
  8804. into
  8805. mov ##, ##
  8806. jmp/ret
  8807. }
  8808. if not Assigned(hp1) then
  8809. begin
  8810. hp1 := GetLabelWithSym(OrigLabel);
  8811. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8812. Exit;
  8813. end;
  8814. hp2 := hp1;
  8815. while Assigned(hp2) do
  8816. begin
  8817. if Assigned(hp2) and (hp2.typ = ait_label) then
  8818. SkipLabels(hp2,hp2);
  8819. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8820. Break;
  8821. case taicpu(hp2).opcode of
  8822. A_MOVSD:
  8823. begin
  8824. if taicpu(hp2).ops = 0 then
  8825. { Wrong MOVSD }
  8826. Break;
  8827. Inc(Count);
  8828. if Count >= 5 then
  8829. { Too many to be worthwhile }
  8830. Break;
  8831. GetNextInstruction(hp2, hp2);
  8832. Continue;
  8833. end;
  8834. A_MOV,
  8835. A_MOVD,
  8836. A_MOVQ,
  8837. A_MOVSX,
  8838. {$ifdef x86_64}
  8839. A_MOVSXD,
  8840. {$endif x86_64}
  8841. A_MOVZX,
  8842. A_MOVAPS,
  8843. A_MOVUPS,
  8844. A_MOVSS,
  8845. A_MOVAPD,
  8846. A_MOVUPD,
  8847. A_MOVDQA,
  8848. A_MOVDQU,
  8849. A_VMOVSS,
  8850. A_VMOVAPS,
  8851. A_VMOVUPS,
  8852. A_VMOVSD,
  8853. A_VMOVAPD,
  8854. A_VMOVUPD,
  8855. A_VMOVDQA,
  8856. A_VMOVDQU:
  8857. begin
  8858. Inc(Count);
  8859. if Count >= 5 then
  8860. { Too many to be worthwhile }
  8861. Break;
  8862. GetNextInstruction(hp2, hp2);
  8863. Continue;
  8864. end;
  8865. A_JMP:
  8866. begin
  8867. { Guard against infinite loops }
  8868. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8869. Exit;
  8870. { Analyse this jump first in case it also duplicates assignments }
  8871. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8872. begin
  8873. { Something did change! }
  8874. Result := True;
  8875. Inc(Count, IncCount);
  8876. if Count >= 5 then
  8877. begin
  8878. { Too many to be worthwhile }
  8879. Exit;
  8880. end;
  8881. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8882. Break;
  8883. end;
  8884. Result := True;
  8885. Break;
  8886. end;
  8887. A_RET:
  8888. begin
  8889. Result := True;
  8890. Break;
  8891. end;
  8892. else
  8893. Break;
  8894. end;
  8895. end;
  8896. if Result then
  8897. begin
  8898. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8899. if Count = 0 then
  8900. begin
  8901. Result := False;
  8902. Exit;
  8903. end;
  8904. TransferUsedRegs(TmpUsedRegs);
  8905. hp3 := p;
  8906. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8907. while True do
  8908. begin
  8909. if Assigned(hp1) and (hp1.typ = ait_label) then
  8910. SkipLabels(hp1,hp1);
  8911. case hp1.typ of
  8912. ait_regalloc:
  8913. if tai_regalloc(hp1).ratype = ra_dealloc then
  8914. begin
  8915. { Duplicate the register deallocation... }
  8916. hp3:=tai(hp1.getcopy);
  8917. if first_assignment = nil then
  8918. first_assignment := hp3;
  8919. asml.InsertBefore(hp3, p);
  8920. { ... but also reallocate it after the jump }
  8921. hp3:=tai(hp1.getcopy);
  8922. tai_regalloc(hp3).ratype := ra_alloc;
  8923. asml.InsertAfter(hp3, p);
  8924. end;
  8925. ait_instruction:
  8926. case taicpu(hp1).opcode of
  8927. A_JMP:
  8928. begin
  8929. { Change the original jump to the new destination }
  8930. OrigLabel.decrefs;
  8931. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8932. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8933. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8934. if not Assigned(first_assignment) then
  8935. InternalError(2021040810)
  8936. else
  8937. p := first_assignment;
  8938. Exit;
  8939. end;
  8940. A_RET:
  8941. begin
  8942. { Now change the jump into a RET instruction }
  8943. ConvertJumpToRET(p, hp1);
  8944. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8945. if not Assigned(first_assignment) then
  8946. InternalError(2021040811)
  8947. else
  8948. p := first_assignment;
  8949. Exit;
  8950. end;
  8951. else
  8952. begin
  8953. { Duplicate the MOV instruction }
  8954. hp3:=tai(hp1.getcopy);
  8955. if first_assignment = nil then
  8956. first_assignment := hp3;
  8957. asml.InsertBefore(hp3, p);
  8958. { Make sure the compiler knows about any final registers written here }
  8959. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8960. with taicpu(hp3).oper[OperIdx]^ do
  8961. begin
  8962. case typ of
  8963. top_ref:
  8964. begin
  8965. if (ref^.base <> NR_NO) and
  8966. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8967. (
  8968. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8969. (
  8970. { Allow the frame pointer if it's not being used by the procedure as such }
  8971. Assigned(current_procinfo) and
  8972. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8973. )
  8974. )
  8975. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8976. then
  8977. begin
  8978. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8979. if not Assigned(first_assignment) then
  8980. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8981. end;
  8982. if (ref^.index <> NR_NO) and
  8983. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8984. (
  8985. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8986. (
  8987. { Allow the frame pointer if it's not being used by the procedure as such }
  8988. Assigned(current_procinfo) and
  8989. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8990. )
  8991. )
  8992. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8993. (ref^.index <> ref^.base) then
  8994. begin
  8995. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8996. if not Assigned(first_assignment) then
  8997. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8998. end;
  8999. end;
  9000. top_reg:
  9001. begin
  9002. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  9003. if not Assigned(first_assignment) then
  9004. IncludeRegInUsedRegs(reg, UsedRegs);
  9005. end;
  9006. else
  9007. ;
  9008. end;
  9009. end;
  9010. end;
  9011. end;
  9012. else
  9013. InternalError(2021040720);
  9014. end;
  9015. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  9016. { Should have dropped out earlier }
  9017. InternalError(2021040710);
  9018. end;
  9019. end;
  9020. end;
  9021. const
  9022. WriteOp: array[0..3] of set of TInsChange = (
  9023. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  9024. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  9025. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  9026. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  9027. RegWriteFlags: array[0..7] of set of TInsChange = (
  9028. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  9029. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  9030. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  9031. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  9032. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  9033. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  9034. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  9035. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  9036. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  9037. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  9038. var
  9039. hp2: tai;
  9040. X: Integer;
  9041. begin
  9042. { If we have something like:
  9043. op ###,###
  9044. mov ###,###
  9045. Try to move the MOV instruction to before OP as long as OP and MOV don't
  9046. interfere in regards to what they write to.
  9047. NOTE: p must be a 2-operand instruction
  9048. }
  9049. Result := False;
  9050. if (hp1.typ <> ait_instruction) or
  9051. taicpu(hp1).is_jmp or
  9052. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  9053. Exit;
  9054. { NOP is a pipeline fence, likely marking the beginning of the function
  9055. epilogue, so drop out. Similarly, drop out if POP or RET are
  9056. encountered }
  9057. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  9058. Exit;
  9059. if (taicpu(hp1).opcode = A_MOVSD) and
  9060. (taicpu(hp1).ops = 0) then
  9061. { Wrong MOVSD }
  9062. Exit;
  9063. { Check for writes to specific registers first }
  9064. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  9065. for X := 0 to 7 do
  9066. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  9067. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  9068. Exit;
  9069. for X := 0 to taicpu(hp1).ops - 1 do
  9070. begin
  9071. { Check to see if this operand writes to something }
  9072. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  9073. { And matches something in the CMP/TEST instruction }
  9074. (
  9075. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  9076. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  9077. (
  9078. { If it's a register, make sure the register written to doesn't
  9079. appear in the cmp instruction as part of a reference }
  9080. (taicpu(hp1).oper[X]^.typ = top_reg) and
  9081. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  9082. )
  9083. ) then
  9084. Exit;
  9085. end;
  9086. { Check p to make sure it doesn't write to something that affects hp1 }
  9087. { Check for writes to specific registers first }
  9088. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  9089. for X := 0 to 7 do
  9090. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  9091. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  9092. Exit;
  9093. for X := 0 to taicpu(p).ops - 1 do
  9094. begin
  9095. { Check to see if this operand writes to something }
  9096. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  9097. { And matches something in hp1 }
  9098. (taicpu(p).oper[X]^.typ = top_reg) and
  9099. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  9100. Exit;
  9101. end;
  9102. { The instruction can be safely moved }
  9103. asml.Remove(hp1);
  9104. { Try to insert after the last instructions where the FLAGS register is not
  9105. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  9106. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  9107. asml.InsertBefore(hp1, hp2)
  9108. { Failing that, try to insert after the last instructions where the
  9109. FLAGS register is not yet in use }
  9110. else if GetLastInstruction(p, hp2) and
  9111. (
  9112. (hp2.typ <> ait_instruction) or
  9113. { Don't insert after an instruction that uses the flags when p doesn't use them }
  9114. RegInInstruction(NR_DEFAULTFLAGS, p) or
  9115. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  9116. ) then
  9117. asml.InsertAfter(hp1, hp2)
  9118. else
  9119. { Note, if p.Previous is nil (even if it should logically never be the
  9120. case), FindRegAllocBackward immediately exits with False and so we
  9121. safely land here (we can't just pass p because FindRegAllocBackward
  9122. immediately exits on an instruction). [Kit] }
  9123. asml.InsertBefore(hp1, p);
  9124. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  9125. { We can't trust UsedRegs because we're looking backwards, although we
  9126. know the registers are allocated after p at the very least, so manually
  9127. create tai_regalloc objects if needed }
  9128. for X := 0 to taicpu(hp1).ops - 1 do
  9129. case taicpu(hp1).oper[X]^.typ of
  9130. top_reg:
  9131. begin
  9132. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  9133. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  9134. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  9135. end;
  9136. top_ref:
  9137. begin
  9138. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  9139. begin
  9140. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  9141. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  9142. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  9143. end;
  9144. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  9145. begin
  9146. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  9147. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  9148. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  9149. end;
  9150. end;
  9151. else
  9152. ;
  9153. end;
  9154. Result := True;
  9155. end;
  9156. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  9157. var
  9158. hp2: tai;
  9159. X: Integer;
  9160. begin
  9161. { If we have something like:
  9162. cmp ###,%reg1
  9163. mov 0,%reg2
  9164. And no modified registers are shared, move the instruction to before
  9165. the comparison as this means it can be optimised without worrying
  9166. about the FLAGS register. (CMP/MOV is generated by
  9167. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  9168. As long as the second instruction doesn't use the flags or one of the
  9169. registers used by CMP or TEST (also check any references that use the
  9170. registers), then it can be moved prior to the comparison.
  9171. }
  9172. Result := False;
  9173. if not TrySwapMovOp(p, hp1) then
  9174. Exit;
  9175. if taicpu(hp1).opcode = A_LEA then
  9176. { The flags will be overwritten by the CMP/TEST instruction }
  9177. ConvertLEA(taicpu(hp1));
  9178. Result := True;
  9179. { Can we move it one further back? }
  9180. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  9181. { Check to see if CMP/TEST is a comparison against zero }
  9182. (
  9183. (
  9184. (taicpu(p).opcode = A_CMP) and
  9185. MatchOperand(taicpu(p).oper[0]^, 0)
  9186. ) or
  9187. (
  9188. (taicpu(p).opcode = A_TEST) and
  9189. (
  9190. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  9191. MatchOperand(taicpu(p).oper[0]^, -1)
  9192. )
  9193. )
  9194. ) and
  9195. { These instructions set the zero flag if the result is zero }
  9196. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  9197. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  9198. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  9199. TrySwapMovOp(hp2, hp1);
  9200. end;
  9201. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  9202. var
  9203. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  9204. JumpLabel: TAsmLabel;
  9205. TmpBool: Boolean;
  9206. begin
  9207. Result := False;
  9208. { Look for:
  9209. stc/clc
  9210. j(c) .L1
  9211. ...
  9212. .L1:
  9213. set(n)cb %reg
  9214. (flags deallocated)
  9215. j(c) .L2
  9216. Change to:
  9217. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  9218. j(c) .L2
  9219. }
  9220. p_last := p;
  9221. while GetNextInstruction(p_last, hp1) and
  9222. (hp1.typ = ait_instruction) and
  9223. IsJumpToLabel(taicpu(hp1)) do
  9224. begin
  9225. if DoJumpOptimizations(hp1, TmpBool) then
  9226. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9227. Continue;
  9228. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  9229. if not Assigned(JumpLabel) then
  9230. InternalError(2024012801);
  9231. { Optimise the J(c); stc/clc optimisation first since this will
  9232. get missed if the main optimisation takes place }
  9233. if (taicpu(hp1).opcode = A_JCC) then
  9234. begin
  9235. if GetNextInstruction(hp1, hp2) and
  9236. MatchInstruction(hp2, A_CLC, A_STC, []) and
  9237. TryJccStcClcOpt(hp1, hp2) then
  9238. begin
  9239. Result := True;
  9240. Exit;
  9241. end;
  9242. hp2 := nil; { Suppress compiler warning }
  9243. if (taicpu(hp1).condition in [C_C, C_NC]) and
  9244. { Make sure the flags aren't used again }
  9245. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  9246. begin
  9247. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9248. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  9249. begin
  9250. if (taicpu(p).opcode = A_STC) then
  9251. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  9252. else
  9253. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  9254. MakeUnconditional(taicpu(hp1));
  9255. { Move the jump to after the flag deallocations }
  9256. Asml.Remove(hp1);
  9257. Asml.InsertAfter(hp1, hp2);
  9258. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9259. Result := True;
  9260. Exit;
  9261. end
  9262. else
  9263. begin
  9264. if (taicpu(p).opcode = A_STC) then
  9265. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  9266. else
  9267. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  9268. { In this case, the jump is deterministic in that it will never be taken }
  9269. JumpLabel.DecRefs;
  9270. RemoveInstruction(hp1);
  9271. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  9272. Result := True;
  9273. Exit;
  9274. end;
  9275. end;
  9276. end;
  9277. hp2 := nil; { Suppress compiler warning }
  9278. if
  9279. { Make sure the carry flag doesn't appear in the jump conditions }
  9280. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9281. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  9282. GetNextInstruction(hp2, p_dist) and
  9283. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  9284. (taicpu(p_dist).condition in [C_C, C_NC]) then
  9285. begin
  9286. case taicpu(p_dist).opcode of
  9287. A_Jcc:
  9288. begin
  9289. if DoJumpOptimizations(p_dist, TmpBool) then
  9290. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9291. Continue;
  9292. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9293. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  9294. begin
  9295. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  9296. JumpLabel.decrefs;
  9297. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  9298. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9299. Result := True;
  9300. Exit;
  9301. end
  9302. else if GetNextInstruction(p_dist, hp1_dist) and
  9303. (hp1_dist.typ = ait_label) then
  9304. begin
  9305. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  9306. JumpLabel.decrefs;
  9307. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  9308. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9309. Result := True;
  9310. Exit;
  9311. end;
  9312. end;
  9313. A_SETcc:
  9314. if { Make sure the flags aren't used again }
  9315. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  9316. GetNextInstruction(hp2, hp1_dist) and
  9317. (hp1_dist.typ = ait_instruction) and
  9318. IsJumpToLabel(taicpu(hp1_dist)) and
  9319. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9320. { This works if hp1_dist or both are regular JMP instructions }
  9321. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  9322. (
  9323. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  9324. { Make sure the register isn't still in use, otherwise it
  9325. may get corrupted (fixes #40659) }
  9326. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  9327. ) then
  9328. begin
  9329. taicpu(p).allocate_oper(2);
  9330. taicpu(p).ops := 2;
  9331. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  9332. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  9333. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  9334. taicpu(p).opcode := A_MOV;
  9335. taicpu(p).opsize := S_B;
  9336. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  9337. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  9338. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  9339. JumpLabel.decrefs;
  9340. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  9341. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  9342. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  9343. (tai_regalloc(hp2).ratype = ra_alloc) then
  9344. begin
  9345. Asml.Remove(hp2);
  9346. Asml.InsertAfter(hp2, p);
  9347. end;
  9348. Result := True;
  9349. Exit;
  9350. end;
  9351. else
  9352. ;
  9353. end;
  9354. end;
  9355. p_last := hp1;
  9356. end;
  9357. end;
  9358. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  9359. var
  9360. hp2, hp3: tai;
  9361. TempBool: Boolean;
  9362. begin
  9363. Result := False;
  9364. {
  9365. j(c) .L1
  9366. stc/clc
  9367. .L1:
  9368. jc/jnc .L2
  9369. (Flags deallocated)
  9370. Change to:
  9371. j)c) .L1
  9372. jmp .L2
  9373. .L1:
  9374. jc/jnc .L2
  9375. Then call DoJumpOptimizations to convert to:
  9376. j(nc) .L2
  9377. .L1: (may become a dead label)
  9378. jc/jnc .L2
  9379. }
  9380. if GetNextInstruction(hp1, hp2) and
  9381. (hp2.typ = ait_label) and
  9382. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  9383. GetNextInstruction(hp2, hp3) and
  9384. MatchInstruction(hp3, A_Jcc, []) and
  9385. (
  9386. (
  9387. (taicpu(hp3).condition = C_C) and
  9388. (taicpu(hp1).opcode = A_STC)
  9389. ) or (
  9390. (taicpu(hp3).condition = C_NC) and
  9391. (taicpu(hp1).opcode = A_CLC)
  9392. )
  9393. ) and
  9394. { Make sure the flags aren't used again }
  9395. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  9396. begin
  9397. taicpu(hp1).allocate_oper(1);
  9398. taicpu(hp1).ops := 1;
  9399. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  9400. taicpu(hp1).opcode := A_JMP;
  9401. taicpu(hp1).is_jmp := True;
  9402. TempBool := True; { Prevent compiler warnings }
  9403. if DoJumpOptimizations(p, TempBool) then
  9404. Result := True
  9405. else
  9406. Include(OptsToCheck, aoc_ForceNewIteration);
  9407. end;
  9408. end;
  9409. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  9410. begin
  9411. { This generally only executes under -O3 and above }
  9412. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  9413. end;
  9414. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  9415. var
  9416. hp1, hp2: tai;
  9417. FoundComparison: Boolean;
  9418. begin
  9419. { Run the pass 1 optimisations as well, since they may have some effect
  9420. after the CMOV blocks are created in OptPass2Jcc }
  9421. Result := False;
  9422. { Result := OptPass1CMOVcc(p);
  9423. if Result then
  9424. Exit;}
  9425. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9426. and make a slightly inefficent result on branching-type blocks, notably
  9427. when setting a function result then jumping to the function epilogue.
  9428. In this case, change:
  9429. cmov(c) %reg1,%reg2
  9430. j(c) @lbl
  9431. (%reg2 deallocated)
  9432. To:
  9433. mov %reg11,%reg2
  9434. j(c) @lbl
  9435. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9436. jump because if it's not present, we may end up with a jump that's
  9437. completely unrelated.
  9438. }
  9439. hp1 := p;
  9440. while GetNextInstruction(hp1, hp1) and
  9441. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9442. if (hp1.typ = ait_instruction) and
  9443. (taicpu(hp1).opcode = A_Jcc) and
  9444. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9445. begin
  9446. TransferUsedRegs(TmpUsedRegs);
  9447. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9448. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9449. (
  9450. { See if we can find a more distant instruction that overwrites
  9451. the destination register }
  9452. (cs_opt_level3 in current_settings.optimizerswitches) and
  9453. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9454. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9455. ) then
  9456. begin
  9457. if (taicpu(p).oper[0]^.typ = top_reg) then
  9458. begin
  9459. { Search backwards to see if the source register is set to a
  9460. constant }
  9461. FoundComparison := False;
  9462. hp1 := p;
  9463. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9464. begin
  9465. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9466. begin
  9467. FoundComparison := True;
  9468. Continue;
  9469. end;
  9470. { Once we find the CMP, TEST or similar instruction, we
  9471. have to stop if we find anything other than a MOV }
  9472. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9473. Break;
  9474. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9475. { Destination register was modified }
  9476. Break;
  9477. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9478. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9479. begin
  9480. { Found a constant! }
  9481. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9482. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9483. { The source register is no longer in use }
  9484. RemoveInstruction(hp1);
  9485. Break;
  9486. end;
  9487. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9488. { Some other instruction has modified the source register }
  9489. Break;
  9490. end;
  9491. end;
  9492. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9493. taicpu(p).opcode := A_MOV;
  9494. taicpu(p).condition := C_None;
  9495. { Rely on the post peephole stage to put the MOV before the
  9496. CMP/TEST instruction that appears prior }
  9497. Result := True;
  9498. Exit;
  9499. end;
  9500. end;
  9501. end;
  9502. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9503. function IsXCHGAcceptable: Boolean; inline;
  9504. begin
  9505. { Always accept if optimising for size }
  9506. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9507. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9508. than 3, so it becomes a saving compared to three MOVs with two of
  9509. them able to execute simultaneously. [Kit] }
  9510. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9511. end;
  9512. var
  9513. NewRef: TReference;
  9514. hp1, hp2, hp3, hp4: Tai;
  9515. {$ifndef x86_64}
  9516. OperIdx: Integer;
  9517. {$endif x86_64}
  9518. NewInstr : Taicpu;
  9519. NewAligh : Tai_align;
  9520. DestLabel: TAsmLabel;
  9521. TempTracking: TAllUsedRegs;
  9522. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9523. var
  9524. NextInstr: tai;
  9525. begin
  9526. Result := False;
  9527. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9528. if not GetNextInstruction(InputInstr, NextInstr) or
  9529. (
  9530. { The FLAGS register isn't always tracked properly, so do not
  9531. perform this optimisation if a conditional statement follows }
  9532. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9533. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9534. ) then
  9535. begin
  9536. reference_reset(NewRef, 1, []);
  9537. NewRef.base := taicpu(p).oper[0]^.reg;
  9538. NewRef.scalefactor := 1;
  9539. if taicpu(InputInstr).opcode = A_ADD then
  9540. begin
  9541. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9542. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9543. end
  9544. else
  9545. begin
  9546. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9547. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9548. end;
  9549. taicpu(p).opcode := A_LEA;
  9550. taicpu(p).loadref(0, NewRef);
  9551. { For the sake of debugging, have the line info match the
  9552. arithmetic instruction rather than the MOV instruction }
  9553. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9554. RemoveInstruction(InputInstr);
  9555. Result := True;
  9556. end;
  9557. end;
  9558. begin
  9559. Result:=false;
  9560. { This optimisation adds an instruction, so only do it for speed }
  9561. if not (cs_opt_size in current_settings.optimizerswitches) and
  9562. MatchOpType(taicpu(p), top_const, top_reg) and
  9563. (taicpu(p).oper[0]^.val = 0) then
  9564. begin
  9565. { To avoid compiler warning }
  9566. DestLabel := nil;
  9567. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9568. InternalError(2021040750);
  9569. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9570. Exit;
  9571. case hp1.typ of
  9572. ait_label:
  9573. begin
  9574. { Change:
  9575. mov $0,%reg mov $0,%reg
  9576. @Lbl1: @Lbl1:
  9577. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9578. je @Lbl2 jne @Lbl2
  9579. To: To:
  9580. mov $0,%reg mov $0,%reg
  9581. jmp @Lbl2 jmp @Lbl3
  9582. (align) (align)
  9583. @Lbl1: @Lbl1:
  9584. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9585. je @Lbl2 je @Lbl2
  9586. @Lbl3: <-- Only if label exists
  9587. (Not if it's optimised for size)
  9588. }
  9589. if not GetNextInstruction(hp1, hp2) then
  9590. Exit;
  9591. if (hp2.typ = ait_instruction) and
  9592. (
  9593. { Register sizes must exactly match }
  9594. (
  9595. (taicpu(hp2).opcode = A_CMP) and
  9596. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9597. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9598. ) or (
  9599. (taicpu(hp2).opcode = A_TEST) and
  9600. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9601. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9602. )
  9603. ) and GetNextInstruction(hp2, hp3) and
  9604. (hp3.typ = ait_instruction) and
  9605. (taicpu(hp3).opcode = A_JCC) and
  9606. (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
  9607. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9608. begin
  9609. { Check condition of jump }
  9610. { Always true? }
  9611. if condition_in(C_E, taicpu(hp3).condition) then
  9612. begin
  9613. { Copy label symbol and obtain matching label entry for the
  9614. conditional jump, as this will be our destination}
  9615. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9616. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9617. Result := True;
  9618. end
  9619. { Always false? }
  9620. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9621. begin
  9622. { This is only worth it if there's a jump to take }
  9623. case hp2.typ of
  9624. ait_instruction:
  9625. begin
  9626. if taicpu(hp2).opcode = A_JMP then
  9627. begin
  9628. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9629. { An unconditional jump follows the conditional jump which will always be false,
  9630. so use this jump's destination for the new jump }
  9631. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9632. Result := True;
  9633. end
  9634. else if taicpu(hp2).opcode = A_JCC then
  9635. begin
  9636. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9637. if condition_in(C_E, taicpu(hp2).condition) then
  9638. begin
  9639. { A second conditional jump follows the conditional jump which will always be false,
  9640. while the second jump is always True, so use this jump's destination for the new jump }
  9641. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9642. Result := True;
  9643. end;
  9644. { Don't risk it if the jump isn't always true (Result remains False) }
  9645. end;
  9646. end;
  9647. else
  9648. { If anything else don't optimise };
  9649. end;
  9650. end;
  9651. if Result then
  9652. begin
  9653. { Just so we have something to insert as a paremeter}
  9654. reference_reset(NewRef, 1, []);
  9655. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9656. { Now actually load the correct parameter (this also
  9657. increases the reference count) }
  9658. NewInstr.loadsymbol(0, DestLabel, 0);
  9659. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9660. begin
  9661. { Get instruction before original label (may not be p under -O3) }
  9662. if not GetLastInstruction(hp1, hp2) then
  9663. { Shouldn't fail here }
  9664. InternalError(2021040701);
  9665. end
  9666. else
  9667. hp2 := p;
  9668. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9669. AsmL.InsertAfter(NewInstr, hp2);
  9670. { Add new alignment field }
  9671. (* AsmL.InsertAfter(
  9672. cai_align.create_max(
  9673. current_settings.alignment.jumpalign,
  9674. current_settings.alignment.jumpalignskipmax
  9675. ),
  9676. NewInstr
  9677. ); *)
  9678. end;
  9679. Exit;
  9680. end;
  9681. end;
  9682. else
  9683. ;
  9684. end;
  9685. end;
  9686. if not GetNextInstruction(p, hp1) then
  9687. Exit;
  9688. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9689. begin
  9690. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9691. begin
  9692. Result := True;
  9693. Exit;
  9694. end;
  9695. { This optimisation is only effective on a second run of Pass 2,
  9696. hence -O3 or above.
  9697. Change:
  9698. mov %reg1,%reg2
  9699. cmp/test (contains %reg1)
  9700. mov x, %reg1
  9701. (another mov or a j(c))
  9702. To:
  9703. mov %reg1,%reg2
  9704. mov x, %reg1
  9705. cmp (%reg1 replaced with %reg2)
  9706. (another mov or a j(c))
  9707. The requirement of an additional MOV or a jump ensures there
  9708. isn't performance loss, since a j(c) will permit macro-fusion
  9709. with the cmp instruction, while another MOV likely means it's
  9710. not all being executed in a single cycle due to parallelisation.
  9711. }
  9712. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9713. MatchOpType(taicpu(p), top_reg, top_reg) and
  9714. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9715. GetNextInstruction(hp1, hp2) and
  9716. MatchInstruction(hp2, A_MOV, []) and
  9717. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9718. { Registers don't have to be the same size in this case }
  9719. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9720. GetNextInstruction(hp2, hp3) and
  9721. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9722. { Make sure the operands in the camparison can be safely replaced }
  9723. (
  9724. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9725. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9726. ) and
  9727. (
  9728. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9729. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9730. ) then
  9731. begin
  9732. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9733. AsmL.Remove(hp2);
  9734. AsmL.InsertAfter(hp2, p);
  9735. Result := True;
  9736. Exit;
  9737. end;
  9738. end;
  9739. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9740. begin
  9741. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9742. further, but we can't just put this jump optimisation in pass 1
  9743. because it tends to perform worse when conditional jumps are
  9744. nearby (e.g. when converting CMOV instructions). [Kit] }
  9745. CopyUsedRegs(TempTracking);
  9746. UpdateUsedRegs(tai(p.Next));
  9747. if OptPass2JMP(hp1) then
  9748. begin
  9749. { Restore register state }
  9750. RestoreUsedRegs(TempTracking);
  9751. ReleaseUsedRegs(TempTracking);
  9752. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9753. OptPass1MOV(p);
  9754. Result := True;
  9755. Exit;
  9756. end;
  9757. { If OptPass2JMP returned False, no optimisations were done to
  9758. the jump and there are no further optimisations that can be done
  9759. to the MOV instruction on this pass other than FuncMov2Func }
  9760. { Restore register state }
  9761. RestoreUsedRegs(TempTracking);
  9762. ReleaseUsedRegs(TempTracking);
  9763. Result := FuncMov2Func(p, hp1);
  9764. Exit;
  9765. end;
  9766. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9767. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9768. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9769. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9770. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9771. begin
  9772. { Change:
  9773. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9774. addl/q $x,%reg2 subl/q $x,%reg2
  9775. To:
  9776. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9777. }
  9778. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9779. { be lazy, checking separately for sub would be slightly better }
  9780. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9781. begin
  9782. TransferUsedRegs(TmpUsedRegs);
  9783. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9784. if TryMovArith2Lea(hp1) then
  9785. begin
  9786. Result := True;
  9787. Exit;
  9788. end
  9789. end
  9790. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9791. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9792. { Same as above, but also adds or subtracts to %reg2 in between.
  9793. It's still valid as long as the flags aren't in use }
  9794. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9795. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9796. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9797. { be lazy, checking separately for sub would be slightly better }
  9798. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9799. begin
  9800. TransferUsedRegs(TmpUsedRegs);
  9801. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9802. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9803. if TryMovArith2Lea(hp2) then
  9804. begin
  9805. Result := True;
  9806. Exit;
  9807. end;
  9808. end;
  9809. end;
  9810. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9811. {$ifdef x86_64}
  9812. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9813. {$else x86_64}
  9814. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9815. {$endif x86_64}
  9816. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9817. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9818. { mov reg1, reg2 mov reg1, reg2
  9819. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9820. begin
  9821. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9822. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9823. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9824. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9825. TransferUsedRegs(TmpUsedRegs);
  9826. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9827. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9828. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9829. then
  9830. begin
  9831. RemoveCurrentP(p, hp1);
  9832. Result:=true;
  9833. end;
  9834. Exit;
  9835. end;
  9836. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9837. IsXCHGAcceptable and
  9838. { XCHG doesn't support 8-bit registers }
  9839. (taicpu(p).opsize <> S_B) and
  9840. MatchInstruction(hp1, A_MOV, []) and
  9841. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9842. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9843. GetNextInstruction(hp1, hp2) and
  9844. MatchInstruction(hp2, A_MOV, []) and
  9845. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9846. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9847. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9848. begin
  9849. { mov %reg1,%reg2
  9850. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9851. mov %reg2,%reg3
  9852. (%reg2 not used afterwards)
  9853. Note that xchg takes 3 cycles to execute, and generally mov's take
  9854. only one cycle apiece, but the first two mov's can be executed in
  9855. parallel, only taking 2 cycles overall. Older processors should
  9856. therefore only optimise for size. [Kit]
  9857. }
  9858. TransferUsedRegs(TmpUsedRegs);
  9859. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9860. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9861. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9862. begin
  9863. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9864. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9865. taicpu(hp1).opcode := A_XCHG;
  9866. RemoveCurrentP(p, hp1);
  9867. RemoveInstruction(hp2);
  9868. Result := True;
  9869. Exit;
  9870. end;
  9871. end;
  9872. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9873. MatchInstruction(hp1, A_SAR, []) then
  9874. begin
  9875. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9876. begin
  9877. { the use of %edx also covers the opsize being S_L }
  9878. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9879. begin
  9880. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9881. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9882. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9883. begin
  9884. { Change:
  9885. movl %eax,%edx
  9886. sarl $31,%edx
  9887. To:
  9888. cltd
  9889. }
  9890. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9891. RemoveInstruction(hp1);
  9892. taicpu(p).opcode := A_CDQ;
  9893. taicpu(p).opsize := S_NO;
  9894. taicpu(p).clearop(1);
  9895. taicpu(p).clearop(0);
  9896. taicpu(p).ops:=0;
  9897. Result := True;
  9898. Exit;
  9899. end
  9900. else if (cs_opt_size in current_settings.optimizerswitches) and
  9901. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9902. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9903. begin
  9904. { Change:
  9905. movl %edx,%eax
  9906. sarl $31,%edx
  9907. To:
  9908. movl %edx,%eax
  9909. cltd
  9910. Note that this creates a dependency between the two instructions,
  9911. so only perform if optimising for size.
  9912. }
  9913. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9914. taicpu(hp1).opcode := A_CDQ;
  9915. taicpu(hp1).opsize := S_NO;
  9916. taicpu(hp1).clearop(1);
  9917. taicpu(hp1).clearop(0);
  9918. taicpu(hp1).ops:=0;
  9919. Include(OptsToCheck, aoc_ForceNewIteration);
  9920. Exit;
  9921. end;
  9922. {$ifndef x86_64}
  9923. end
  9924. { Don't bother if CMOV is supported, because a more optimal
  9925. sequence would have been generated for the Abs() intrinsic }
  9926. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9927. { the use of %eax also covers the opsize being S_L }
  9928. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9929. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9930. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9931. GetNextInstruction(hp1, hp2) and
  9932. MatchInstruction(hp2, A_XOR, [S_L]) and
  9933. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9934. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9935. GetNextInstruction(hp2, hp3) and
  9936. MatchInstruction(hp3, A_SUB, [S_L]) and
  9937. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9938. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9939. begin
  9940. { Change:
  9941. movl %eax,%edx
  9942. sarl $31,%eax
  9943. xorl %eax,%edx
  9944. subl %eax,%edx
  9945. (Instruction that uses %edx)
  9946. (%eax deallocated)
  9947. (%edx deallocated)
  9948. To:
  9949. cltd
  9950. xorl %edx,%eax <-- Note the registers have swapped
  9951. subl %edx,%eax
  9952. (Instruction that uses %eax) <-- %eax rather than %edx
  9953. }
  9954. TransferUsedRegs(TmpUsedRegs);
  9955. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9956. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9957. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9958. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9959. begin
  9960. if GetNextInstruction(hp3, hp4) and
  9961. not RegModifiedByInstruction(NR_EDX, hp4) and
  9962. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9963. begin
  9964. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9965. taicpu(p).opcode := A_CDQ;
  9966. taicpu(p).clearop(1);
  9967. taicpu(p).clearop(0);
  9968. taicpu(p).ops:=0;
  9969. RemoveInstruction(hp1);
  9970. taicpu(hp2).loadreg(0, NR_EDX);
  9971. taicpu(hp2).loadreg(1, NR_EAX);
  9972. taicpu(hp3).loadreg(0, NR_EDX);
  9973. taicpu(hp3).loadreg(1, NR_EAX);
  9974. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9975. { Convert references in the following instruction (hp4) from %edx to %eax }
  9976. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9977. with taicpu(hp4).oper[OperIdx]^ do
  9978. case typ of
  9979. top_reg:
  9980. if getsupreg(reg) = RS_EDX then
  9981. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9982. top_ref:
  9983. begin
  9984. if getsupreg(reg) = RS_EDX then
  9985. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9986. if getsupreg(reg) = RS_EDX then
  9987. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9988. end;
  9989. else
  9990. ;
  9991. end;
  9992. Result := True;
  9993. Exit;
  9994. end;
  9995. end;
  9996. {$else x86_64}
  9997. end;
  9998. end
  9999. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  10000. { the use of %rdx also covers the opsize being S_Q }
  10001. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  10002. begin
  10003. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  10004. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  10005. (taicpu(p).oper[1]^.reg = NR_RDX) then
  10006. begin
  10007. { Change:
  10008. movq %rax,%rdx
  10009. sarq $63,%rdx
  10010. To:
  10011. cqto
  10012. }
  10013. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  10014. RemoveInstruction(hp1);
  10015. taicpu(p).opcode := A_CQO;
  10016. taicpu(p).opsize := S_NO;
  10017. taicpu(p).clearop(1);
  10018. taicpu(p).clearop(0);
  10019. taicpu(p).ops:=0;
  10020. Result := True;
  10021. Exit;
  10022. end
  10023. else if (cs_opt_size in current_settings.optimizerswitches) and
  10024. (taicpu(p).oper[0]^.reg = NR_RDX) and
  10025. (taicpu(p).oper[1]^.reg = NR_RAX) then
  10026. begin
  10027. { Change:
  10028. movq %rdx,%rax
  10029. sarq $63,%rdx
  10030. To:
  10031. movq %rdx,%rax
  10032. cqto
  10033. Note that this creates a dependency between the two instructions,
  10034. so only perform if optimising for size.
  10035. }
  10036. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  10037. taicpu(hp1).opcode := A_CQO;
  10038. taicpu(hp1).opsize := S_NO;
  10039. taicpu(hp1).clearop(1);
  10040. taicpu(hp1).clearop(0);
  10041. taicpu(hp1).ops:=0;
  10042. Include(OptsToCheck, aoc_ForceNewIteration);
  10043. Exit;
  10044. {$endif x86_64}
  10045. end;
  10046. end;
  10047. end;
  10048. if MatchInstruction(hp1, A_MOV, []) and
  10049. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10050. { Though "GetNextInstruction" could be factored out, along with
  10051. the instructions that depend on hp2, it is an expensive call that
  10052. should be delayed for as long as possible, hence we do cheaper
  10053. checks first that are likely to be False. [Kit] }
  10054. begin
  10055. if (
  10056. (
  10057. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  10058. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  10059. (
  10060. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10061. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  10062. )
  10063. ) or
  10064. (
  10065. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  10066. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  10067. (
  10068. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10069. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  10070. )
  10071. )
  10072. ) and
  10073. GetNextInstruction(hp1, hp2) and
  10074. MatchInstruction(hp2, A_SAR, []) and
  10075. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  10076. begin
  10077. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  10078. begin
  10079. { Change:
  10080. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  10081. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  10082. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  10083. To:
  10084. movl r/m,%eax <- Note the change in register
  10085. cltd
  10086. }
  10087. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  10088. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  10089. taicpu(p).loadreg(1, NR_EAX);
  10090. taicpu(hp1).opcode := A_CDQ;
  10091. taicpu(hp1).clearop(1);
  10092. taicpu(hp1).clearop(0);
  10093. taicpu(hp1).ops:=0;
  10094. RemoveInstruction(hp2);
  10095. Include(OptsToCheck, aoc_ForceNewIteration);
  10096. (*
  10097. {$ifdef x86_64}
  10098. end
  10099. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  10100. { This code sequence does not get generated - however it might become useful
  10101. if and when 128-bit signed integer types make an appearance, so the code
  10102. is kept here for when it is eventually needed. [Kit] }
  10103. (
  10104. (
  10105. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  10106. (
  10107. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10108. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  10109. )
  10110. ) or
  10111. (
  10112. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  10113. (
  10114. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10115. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  10116. )
  10117. )
  10118. ) and
  10119. GetNextInstruction(hp1, hp2) and
  10120. MatchInstruction(hp2, A_SAR, [S_Q]) and
  10121. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  10122. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  10123. begin
  10124. { Change:
  10125. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  10126. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  10127. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  10128. To:
  10129. movq r/m,%rax <- Note the change in register
  10130. cqto
  10131. }
  10132. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  10133. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  10134. taicpu(p).loadreg(1, NR_RAX);
  10135. taicpu(hp1).opcode := A_CQO;
  10136. taicpu(hp1).clearop(1);
  10137. taicpu(hp1).clearop(0);
  10138. taicpu(hp1).ops:=0;
  10139. RemoveInstruction(hp2);
  10140. Include(OptsToCheck, aoc_ForceNewIteration);
  10141. {$endif x86_64}
  10142. *)
  10143. end;
  10144. end;
  10145. {$ifdef x86_64}
  10146. end;
  10147. if (taicpu(p).opsize = S_L) and
  10148. (taicpu(p).oper[1]^.typ = top_reg) and
  10149. (
  10150. MatchInstruction(hp1, A_MOV,[]) and
  10151. (taicpu(hp1).opsize = S_L) and
  10152. (taicpu(hp1).oper[1]^.typ = top_reg)
  10153. ) and (
  10154. GetNextInstruction(hp1, hp2) and
  10155. (tai(hp2).typ=ait_instruction) and
  10156. (taicpu(hp2).opsize = S_Q) and
  10157. (
  10158. (
  10159. MatchInstruction(hp2, A_ADD,[]) and
  10160. (taicpu(hp2).opsize = S_Q) and
  10161. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  10162. (
  10163. (
  10164. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  10165. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10166. ) or (
  10167. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10168. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  10169. )
  10170. )
  10171. ) or (
  10172. MatchInstruction(hp2, A_LEA,[]) and
  10173. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  10174. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  10175. (
  10176. (
  10177. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  10178. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10179. ) or (
  10180. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10181. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  10182. )
  10183. ) and (
  10184. (
  10185. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10186. ) or (
  10187. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  10188. )
  10189. )
  10190. )
  10191. )
  10192. ) and (
  10193. GetNextInstruction(hp2, hp3) and
  10194. MatchInstruction(hp3, A_SHR,[]) and
  10195. (taicpu(hp3).opsize = S_Q) and
  10196. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  10197. (taicpu(hp3).oper[0]^.val = 1) and
  10198. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  10199. ) then
  10200. begin
  10201. { Change movl x, reg1d movl x, reg1d
  10202. movl y, reg2d movl y, reg2d
  10203. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  10204. shrq $1, reg1q shrq $1, reg1q
  10205. ( reg1d and reg2d can be switched around in the first two instructions )
  10206. To movl x, reg1d
  10207. addl y, reg1d
  10208. rcrl $1, reg1d
  10209. This corresponds to the common expression (x + y) shr 1, where
  10210. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  10211. smaller code, but won't account for x + y causing an overflow). [Kit]
  10212. }
  10213. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  10214. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10215. begin
  10216. { Change first MOV command to have the same register as the final output }
  10217. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10218. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  10219. Result := True;
  10220. end
  10221. else
  10222. begin
  10223. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  10224. Include(OptsToCheck, aoc_ForceNewIteration);
  10225. end;
  10226. { Change second MOV command to an ADD command. This is easier than
  10227. converting the existing command because it means we don't have to
  10228. touch 'y', which might be a complicated reference, and also the
  10229. fact that the third command might either be ADD or LEA. [Kit] }
  10230. taicpu(hp1).opcode := A_ADD;
  10231. { Delete old ADD/LEA instruction }
  10232. RemoveInstruction(hp2);
  10233. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  10234. taicpu(hp3).opcode := A_RCR;
  10235. taicpu(hp3).changeopsize(S_L);
  10236. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  10237. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  10238. called, so FuncMov2Func below is safe to call }
  10239. {$endif x86_64}
  10240. end;
  10241. if FuncMov2Func(p, hp1) then
  10242. begin
  10243. Result := True;
  10244. Exit;
  10245. end;
  10246. end;
  10247. {$push}
  10248. {$q-}{$r-}
  10249. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  10250. var
  10251. ThisReg: TRegister;
  10252. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  10253. TargetSubReg: TSubRegister;
  10254. hp1, hp2: tai;
  10255. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  10256. { Store list of found instructions so we don't have to call
  10257. GetNextInstructionUsingReg multiple times }
  10258. InstrList: array of taicpu;
  10259. InstrMax, Index: Integer;
  10260. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  10261. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  10262. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  10263. WorkingValue: TCgInt;
  10264. PreMessage: string;
  10265. { Data flow analysis }
  10266. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  10267. BitwiseOnly, OrXorUsed,
  10268. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  10269. function CheckOverflowConditions: Boolean;
  10270. begin
  10271. Result := True;
  10272. if (TestValSignedMax > SignedUpperLimit) then
  10273. UpperSignedOverflow := True;
  10274. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  10275. LowerSignedOverflow := True;
  10276. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  10277. LowerUnsignedOverflow := True;
  10278. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  10279. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  10280. begin
  10281. { Absolute overflow }
  10282. Result := False;
  10283. Exit;
  10284. end;
  10285. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  10286. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  10287. ShiftDownOverflow := True;
  10288. if (TestValMin < 0) or (TestValMax < 0) then
  10289. begin
  10290. LowerUnsignedOverflow := True;
  10291. UpperUnsignedOverflow := True;
  10292. end;
  10293. end;
  10294. function AdjustInitialLoadAndSize: Boolean;
  10295. begin
  10296. Result := False;
  10297. if not p_removed then
  10298. begin
  10299. if TargetSize = MinSize then
  10300. begin
  10301. { Convert the input MOVZX to a MOV }
  10302. if (taicpu(p).oper[0]^.typ = top_reg) and
  10303. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10304. begin
  10305. { Or remove it completely! }
  10306. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  10307. RemoveCurrentP(p);
  10308. p_removed := True;
  10309. end
  10310. else
  10311. begin
  10312. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  10313. taicpu(p).opcode := A_MOV;
  10314. taicpu(p).oper[1]^.reg := ThisReg;
  10315. taicpu(p).opsize := TargetSize;
  10316. end;
  10317. Result := True;
  10318. end
  10319. else if TargetSize <> MaxSize then
  10320. begin
  10321. case MaxSize of
  10322. S_L:
  10323. if TargetSize = S_W then
  10324. begin
  10325. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  10326. taicpu(p).opsize := S_BW;
  10327. taicpu(p).oper[1]^.reg := ThisReg;
  10328. Result := True;
  10329. end
  10330. else
  10331. InternalError(2020112341);
  10332. S_W:
  10333. if TargetSize = S_L then
  10334. begin
  10335. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  10336. taicpu(p).opsize := S_BL;
  10337. taicpu(p).oper[1]^.reg := ThisReg;
  10338. Result := True;
  10339. end
  10340. else
  10341. InternalError(2020112342);
  10342. else
  10343. ;
  10344. end;
  10345. end
  10346. else if not hp1_removed and not RegInUse then
  10347. begin
  10348. { If we have something like:
  10349. movzbl (oper),%regd
  10350. add x, %regd
  10351. movzbl %regb, %regd
  10352. We can reduce the register size to the input of the final
  10353. movzbl instruction. Overflows won't have any effect.
  10354. }
  10355. if (taicpu(p).opsize in [S_BW, S_BL]) and
  10356. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10357. begin
  10358. TargetSize := S_B;
  10359. setsubreg(ThisReg, R_SUBL);
  10360. Result := True;
  10361. end
  10362. else if (taicpu(p).opsize = S_WL) and
  10363. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10364. begin
  10365. TargetSize := S_W;
  10366. setsubreg(ThisReg, R_SUBW);
  10367. Result := True;
  10368. end;
  10369. if Result then
  10370. begin
  10371. { Convert the input MOVZX to a MOV }
  10372. if (taicpu(p).oper[0]^.typ = top_reg) and
  10373. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10374. begin
  10375. { Or remove it completely! }
  10376. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  10377. RemoveCurrentP(p);
  10378. p_removed := True;
  10379. end
  10380. else
  10381. begin
  10382. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  10383. taicpu(p).opcode := A_MOV;
  10384. taicpu(p).oper[1]^.reg := ThisReg;
  10385. taicpu(p).opsize := TargetSize;
  10386. end;
  10387. end;
  10388. end;
  10389. end;
  10390. end;
  10391. procedure AdjustFinalLoad;
  10392. begin
  10393. if not LowerUnsignedOverflow then
  10394. begin
  10395. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  10396. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  10397. begin
  10398. { Convert the output MOVZX to a MOV }
  10399. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10400. begin
  10401. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  10402. if (MinSize = S_B) or
  10403. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  10404. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  10405. begin
  10406. { Remove it completely! }
  10407. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  10408. { Be careful; if p = hp1 and p was also removed, p
  10409. will become a dangling pointer }
  10410. if p = hp1 then
  10411. begin
  10412. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10413. p_removed := True;
  10414. end
  10415. else
  10416. RemoveInstruction(hp1);
  10417. hp1_removed := True;
  10418. end;
  10419. end
  10420. else
  10421. begin
  10422. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10423. taicpu(hp1).opcode := A_MOV;
  10424. taicpu(hp1).oper[0]^.reg := ThisReg;
  10425. taicpu(hp1).opsize := TargetSize;
  10426. end;
  10427. end
  10428. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10429. begin
  10430. { Need to change the size of the output }
  10431. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10432. taicpu(hp1).oper[0]^.reg := ThisReg;
  10433. taicpu(hp1).opsize := S_BL;
  10434. end;
  10435. end;
  10436. end;
  10437. function CompressInstructions: Boolean;
  10438. var
  10439. LocalIndex: Integer;
  10440. begin
  10441. Result := False;
  10442. { The objective here is to try to find a combination that
  10443. removes one of the MOV/Z instructions. }
  10444. if (
  10445. (taicpu(p).oper[0]^.typ <> top_reg) or
  10446. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10447. ) and
  10448. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10449. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10450. begin
  10451. { Make a preference to remove the second MOVZX instruction }
  10452. case taicpu(hp1).opsize of
  10453. S_BL, S_WL:
  10454. begin
  10455. TargetSize := S_L;
  10456. TargetSubReg := R_SUBD;
  10457. end;
  10458. S_BW:
  10459. begin
  10460. TargetSize := S_W;
  10461. TargetSubReg := R_SUBW;
  10462. end;
  10463. else
  10464. InternalError(2020112302);
  10465. end;
  10466. end
  10467. else
  10468. begin
  10469. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10470. begin
  10471. { Exceeded lower bound but not upper bound }
  10472. TargetSize := MaxSize;
  10473. end
  10474. else if not LowerUnsignedOverflow then
  10475. begin
  10476. { Size didn't exceed lower bound }
  10477. TargetSize := MinSize;
  10478. end
  10479. else
  10480. Exit;
  10481. end;
  10482. case TargetSize of
  10483. S_B:
  10484. TargetSubReg := R_SUBL;
  10485. S_W:
  10486. TargetSubReg := R_SUBW;
  10487. S_L:
  10488. TargetSubReg := R_SUBD;
  10489. else
  10490. InternalError(2020112350);
  10491. end;
  10492. { Update the register to its new size }
  10493. setsubreg(ThisReg, TargetSubReg);
  10494. RegInUse := False;
  10495. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10496. begin
  10497. { Check to see if the active register is used afterwards;
  10498. if not, we can change it and make a saving. }
  10499. TransferUsedRegs(TmpUsedRegs);
  10500. { The target register may be marked as in use to cross
  10501. a jump to a distant label, so exclude it }
  10502. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10503. hp2 := p;
  10504. repeat
  10505. { Explicitly check for the excluded register (don't include the first
  10506. instruction as it may be reading from here }
  10507. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10508. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10509. begin
  10510. RegInUse := True;
  10511. Break;
  10512. end;
  10513. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10514. if not GetNextInstruction(hp2, hp2) then
  10515. InternalError(2020112340);
  10516. until (hp2 = hp1);
  10517. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10518. { We might still be able to get away with this }
  10519. RegInUse := not
  10520. (
  10521. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10522. (hp2.typ = ait_instruction) and
  10523. (
  10524. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10525. instruction that doesn't actually contain ThisReg }
  10526. (cs_opt_level3 in current_settings.optimizerswitches) or
  10527. RegInInstruction(ThisReg, hp2)
  10528. ) and
  10529. RegLoadedWithNewValue(ThisReg, hp2)
  10530. );
  10531. if not RegInUse then
  10532. begin
  10533. { Force the register size to the same as this instruction so it can be removed}
  10534. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10535. begin
  10536. TargetSize := S_L;
  10537. TargetSubReg := R_SUBD;
  10538. end
  10539. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10540. begin
  10541. TargetSize := S_W;
  10542. TargetSubReg := R_SUBW;
  10543. end;
  10544. ThisReg := taicpu(hp1).oper[1]^.reg;
  10545. setsubreg(ThisReg, TargetSubReg);
  10546. RegChanged := True;
  10547. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10548. TransferUsedRegs(TmpUsedRegs);
  10549. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10550. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10551. if p = hp1 then
  10552. begin
  10553. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10554. p_removed := True;
  10555. end
  10556. else
  10557. RemoveInstruction(hp1);
  10558. hp1_removed := True;
  10559. { Instruction will become "mov %reg,%reg" }
  10560. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10561. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10562. begin
  10563. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10564. RemoveCurrentP(p);
  10565. p_removed := True;
  10566. end
  10567. else
  10568. taicpu(p).oper[1]^.reg := ThisReg;
  10569. Result := True;
  10570. end
  10571. else
  10572. begin
  10573. if TargetSize <> MaxSize then
  10574. begin
  10575. { Since the register is in use, we have to force it to
  10576. MaxSize otherwise part of it may become undefined later on }
  10577. TargetSize := MaxSize;
  10578. case TargetSize of
  10579. S_B:
  10580. TargetSubReg := R_SUBL;
  10581. S_W:
  10582. TargetSubReg := R_SUBW;
  10583. S_L:
  10584. TargetSubReg := R_SUBD;
  10585. else
  10586. InternalError(2020112351);
  10587. end;
  10588. setsubreg(ThisReg, TargetSubReg);
  10589. end;
  10590. AdjustFinalLoad;
  10591. end;
  10592. end
  10593. else
  10594. AdjustFinalLoad;
  10595. Result := AdjustInitialLoadAndSize or Result;
  10596. { Now go through every instruction we found and change the
  10597. size. If TargetSize = MaxSize, then almost no changes are
  10598. needed and Result can remain False if it hasn't been set
  10599. yet.
  10600. If RegChanged is True, then the register requires changing
  10601. and so the point about TargetSize = MaxSize doesn't apply. }
  10602. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10603. begin
  10604. for LocalIndex := 0 to InstrMax do
  10605. begin
  10606. { If p_removed is true, then the original MOV/Z was removed
  10607. and removing the AND instruction may not be safe if it
  10608. appears first }
  10609. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10610. InternalError(2020112310);
  10611. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10612. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10613. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10614. InstrList[LocalIndex].opsize := TargetSize;
  10615. end;
  10616. Result := True;
  10617. end;
  10618. end;
  10619. begin
  10620. Result := False;
  10621. p_removed := False;
  10622. hp1_removed := False;
  10623. ThisReg := taicpu(p).oper[1]^.reg;
  10624. { Check for:
  10625. movs/z ###,%ecx (or %cx or %rcx)
  10626. ...
  10627. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10628. (dealloc %ecx)
  10629. Change to:
  10630. mov ###,%cl (if ### = %cl, then remove completely)
  10631. ...
  10632. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10633. }
  10634. if (getsupreg(ThisReg) = RS_ECX) and
  10635. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10636. (hp1.typ = ait_instruction) and
  10637. (
  10638. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10639. instruction that doesn't actually contain ECX }
  10640. (cs_opt_level3 in current_settings.optimizerswitches) or
  10641. RegInInstruction(NR_ECX, hp1) or
  10642. (
  10643. { It's common for the shift/rotate's read/write register to be
  10644. initialised in between, so under -O2 and under, search ahead
  10645. one more instruction
  10646. }
  10647. GetNextInstruction(hp1, hp1) and
  10648. (hp1.typ = ait_instruction) and
  10649. RegInInstruction(NR_ECX, hp1)
  10650. )
  10651. ) and
  10652. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10653. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10654. begin
  10655. TransferUsedRegs(TmpUsedRegs);
  10656. hp2 := p;
  10657. repeat
  10658. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10659. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10660. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10661. begin
  10662. case taicpu(p).opsize of
  10663. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10664. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10665. begin
  10666. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10667. RemoveCurrentP(p);
  10668. end
  10669. else
  10670. begin
  10671. taicpu(p).opcode := A_MOV;
  10672. taicpu(p).opsize := S_B;
  10673. taicpu(p).oper[1]^.reg := NR_CL;
  10674. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10675. end;
  10676. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10677. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10678. begin
  10679. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10680. RemoveCurrentP(p);
  10681. end
  10682. else
  10683. begin
  10684. taicpu(p).opcode := A_MOV;
  10685. taicpu(p).opsize := S_W;
  10686. taicpu(p).oper[1]^.reg := NR_CX;
  10687. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10688. end;
  10689. {$ifdef x86_64}
  10690. S_LQ:
  10691. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10692. begin
  10693. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10694. RemoveCurrentP(p);
  10695. end
  10696. else
  10697. begin
  10698. taicpu(p).opcode := A_MOV;
  10699. taicpu(p).opsize := S_L;
  10700. taicpu(p).oper[1]^.reg := NR_ECX;
  10701. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10702. end;
  10703. {$endif x86_64}
  10704. else
  10705. InternalError(2021120401);
  10706. end;
  10707. Result := True;
  10708. Exit;
  10709. end;
  10710. end;
  10711. { This is anything but quick! }
  10712. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10713. Exit;
  10714. SetLength(InstrList, 0);
  10715. InstrMax := -1;
  10716. case taicpu(p).opsize of
  10717. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10718. begin
  10719. {$if defined(i386) or defined(i8086)}
  10720. { If the target size is 8-bit, make sure we can actually encode it }
  10721. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10722. Exit;
  10723. {$endif i386 or i8086}
  10724. LowerLimit := $FF;
  10725. SignedLowerLimit := $7F;
  10726. SignedLowerLimitBottom := -128;
  10727. MinSize := S_B;
  10728. if taicpu(p).opsize = S_BW then
  10729. begin
  10730. MaxSize := S_W;
  10731. UpperLimit := $FFFF;
  10732. SignedUpperLimit := $7FFF;
  10733. SignedUpperLimitBottom := -32768;
  10734. end
  10735. else
  10736. begin
  10737. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10738. MaxSize := S_L;
  10739. UpperLimit := $FFFFFFFF;
  10740. SignedUpperLimit := $7FFFFFFF;
  10741. SignedUpperLimitBottom := -2147483648;
  10742. end;
  10743. end;
  10744. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10745. begin
  10746. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10747. LowerLimit := $FFFF;
  10748. SignedLowerLimit := $7FFF;
  10749. SignedLowerLimitBottom := -32768;
  10750. UpperLimit := $FFFFFFFF;
  10751. SignedUpperLimit := $7FFFFFFF;
  10752. SignedUpperLimitBottom := -2147483648;
  10753. MinSize := S_W;
  10754. MaxSize := S_L;
  10755. end;
  10756. {$ifdef x86_64}
  10757. S_LQ:
  10758. begin
  10759. { Both the lower and upper limits are set to 32-bit. If a limit
  10760. is breached, then optimisation is impossible }
  10761. LowerLimit := $FFFFFFFF;
  10762. SignedLowerLimit := $7FFFFFFF;
  10763. SignedLowerLimitBottom := -2147483648;
  10764. UpperLimit := $FFFFFFFF;
  10765. SignedUpperLimit := $7FFFFFFF;
  10766. SignedUpperLimitBottom := -2147483648;
  10767. MinSize := S_L;
  10768. MaxSize := S_L;
  10769. end;
  10770. {$endif x86_64}
  10771. else
  10772. InternalError(2020112301);
  10773. end;
  10774. TestValMin := 0;
  10775. TestValMax := LowerLimit;
  10776. TestValSignedMax := SignedLowerLimit;
  10777. TryShiftDownLimit := LowerLimit;
  10778. TryShiftDown := S_NO;
  10779. ShiftDownOverflow := False;
  10780. RegChanged := False;
  10781. BitwiseOnly := True;
  10782. OrXorUsed := False;
  10783. UpperSignedOverflow := False;
  10784. LowerSignedOverflow := False;
  10785. UpperUnsignedOverflow := False;
  10786. LowerUnsignedOverflow := False;
  10787. hp1 := p;
  10788. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10789. (hp1.typ = ait_instruction) and
  10790. (
  10791. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10792. instruction that doesn't actually contain ThisReg }
  10793. (cs_opt_level3 in current_settings.optimizerswitches) or
  10794. { This allows this Movx optimisation to work through the SETcc instructions
  10795. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10796. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10797. skip over these SETcc instructions). }
  10798. (taicpu(hp1).opcode = A_SETcc) or
  10799. RegInInstruction(ThisReg, hp1)
  10800. ) do
  10801. begin
  10802. case taicpu(hp1).opcode of
  10803. A_INC,A_DEC:
  10804. begin
  10805. { Has to be an exact match on the register }
  10806. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10807. Break;
  10808. if taicpu(hp1).opcode = A_INC then
  10809. begin
  10810. Inc(TestValMin);
  10811. Inc(TestValMax);
  10812. Inc(TestValSignedMax);
  10813. end
  10814. else
  10815. begin
  10816. Dec(TestValMin);
  10817. Dec(TestValMax);
  10818. Dec(TestValSignedMax);
  10819. end;
  10820. end;
  10821. A_TEST, A_CMP:
  10822. begin
  10823. if (
  10824. { Too high a risk of non-linear behaviour that breaks DFA
  10825. here, unless it's cmp $0,%reg, which is equivalent to
  10826. test %reg,%reg }
  10827. OrXorUsed and
  10828. (taicpu(hp1).opcode = A_CMP) and
  10829. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10830. ) or
  10831. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10832. { Has to be an exact match on the register }
  10833. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10834. (
  10835. { Permit "test %reg,%reg" }
  10836. (taicpu(hp1).opcode = A_TEST) and
  10837. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10838. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10839. ) or
  10840. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10841. { Make sure the comparison value is not smaller than the
  10842. smallest allowed signed value for the minimum size (e.g.
  10843. -128 for 8-bit) }
  10844. not (
  10845. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10846. { Is it in the negative range? }
  10847. (
  10848. (taicpu(hp1).oper[0]^.val < 0) and
  10849. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10850. )
  10851. ) then
  10852. Break;
  10853. { Check to see if the active register is used afterwards }
  10854. TransferUsedRegs(TmpUsedRegs);
  10855. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10856. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10857. begin
  10858. { Make sure the comparison or any previous instructions
  10859. hasn't pushed the test values outside of the range of
  10860. MinSize }
  10861. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10862. begin
  10863. { Exceeded lower bound but not upper bound }
  10864. Exit;
  10865. end
  10866. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10867. begin
  10868. { Size didn't exceed lower bound }
  10869. TargetSize := MinSize;
  10870. end
  10871. else
  10872. Break;
  10873. case TargetSize of
  10874. S_B:
  10875. TargetSubReg := R_SUBL;
  10876. S_W:
  10877. TargetSubReg := R_SUBW;
  10878. S_L:
  10879. TargetSubReg := R_SUBD;
  10880. else
  10881. InternalError(2021051002);
  10882. end;
  10883. if TargetSize <> MaxSize then
  10884. begin
  10885. { Update the register to its new size }
  10886. setsubreg(ThisReg, TargetSubReg);
  10887. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10888. taicpu(hp1).oper[1]^.reg := ThisReg;
  10889. taicpu(hp1).opsize := TargetSize;
  10890. { Convert the input MOVZX to a MOV if necessary }
  10891. AdjustInitialLoadAndSize;
  10892. if (InstrMax >= 0) then
  10893. begin
  10894. for Index := 0 to InstrMax do
  10895. begin
  10896. { If p_removed is true, then the original MOV/Z was removed
  10897. and removing the AND instruction may not be safe if it
  10898. appears first }
  10899. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10900. InternalError(2020112311);
  10901. if InstrList[Index].oper[0]^.typ = top_reg then
  10902. InstrList[Index].oper[0]^.reg := ThisReg;
  10903. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10904. InstrList[Index].opsize := MinSize;
  10905. end;
  10906. end;
  10907. Result := True;
  10908. end;
  10909. Exit;
  10910. end;
  10911. end;
  10912. A_SETcc:
  10913. begin
  10914. { This allows this Movx optimisation to work through the SETcc instructions
  10915. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10916. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10917. skip over these SETcc instructions). }
  10918. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10919. { Of course, break out if the current register is used }
  10920. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10921. Break
  10922. else
  10923. { We must use Continue so the instruction doesn't get added
  10924. to InstrList }
  10925. Continue;
  10926. end;
  10927. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10928. begin
  10929. if
  10930. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10931. { Has to be an exact match on the register }
  10932. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10933. (
  10934. (
  10935. (taicpu(hp1).oper[0]^.typ = top_const) and
  10936. (
  10937. (
  10938. (taicpu(hp1).opcode = A_SHL) and
  10939. (
  10940. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10941. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10942. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10943. )
  10944. ) or (
  10945. (taicpu(hp1).opcode <> A_SHL) and
  10946. (
  10947. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10948. { Is it in the negative range? }
  10949. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10950. )
  10951. )
  10952. )
  10953. ) or (
  10954. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10955. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10956. )
  10957. ) then
  10958. Break;
  10959. { Only process OR and XOR if there are only bitwise operations,
  10960. since otherwise they can too easily fool the data flow
  10961. analysis (they can cause non-linear behaviour) }
  10962. case taicpu(hp1).opcode of
  10963. A_ADD:
  10964. begin
  10965. if OrXorUsed then
  10966. { Too high a risk of non-linear behaviour that breaks DFA here }
  10967. Break
  10968. else
  10969. BitwiseOnly := False;
  10970. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10971. begin
  10972. TestValMin := TestValMin * 2;
  10973. TestValMax := TestValMax * 2;
  10974. TestValSignedMax := TestValSignedMax * 2;
  10975. end
  10976. else
  10977. begin
  10978. WorkingValue := taicpu(hp1).oper[0]^.val;
  10979. TestValMin := TestValMin + WorkingValue;
  10980. TestValMax := TestValMax + WorkingValue;
  10981. TestValSignedMax := TestValSignedMax + WorkingValue;
  10982. end;
  10983. end;
  10984. A_SUB:
  10985. begin
  10986. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10987. begin
  10988. TestValMin := 0;
  10989. TestValMax := 0;
  10990. TestValSignedMax := 0;
  10991. end
  10992. else
  10993. begin
  10994. if OrXorUsed then
  10995. { Too high a risk of non-linear behaviour that breaks DFA here }
  10996. Break
  10997. else
  10998. BitwiseOnly := False;
  10999. WorkingValue := taicpu(hp1).oper[0]^.val;
  11000. TestValMin := TestValMin - WorkingValue;
  11001. TestValMax := TestValMax - WorkingValue;
  11002. TestValSignedMax := TestValSignedMax - WorkingValue;
  11003. end;
  11004. end;
  11005. A_AND:
  11006. if (taicpu(hp1).oper[0]^.typ = top_const) then
  11007. begin
  11008. { we might be able to go smaller if AND appears first }
  11009. if InstrMax = -1 then
  11010. case MinSize of
  11011. S_B:
  11012. ;
  11013. S_W:
  11014. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  11015. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  11016. begin
  11017. TryShiftDown := S_B;
  11018. TryShiftDownLimit := $FF;
  11019. end;
  11020. S_L:
  11021. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  11022. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  11023. begin
  11024. TryShiftDown := S_B;
  11025. TryShiftDownLimit := $FF;
  11026. end
  11027. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  11028. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  11029. begin
  11030. TryShiftDown := S_W;
  11031. TryShiftDownLimit := $FFFF;
  11032. end;
  11033. else
  11034. InternalError(2020112320);
  11035. end;
  11036. WorkingValue := taicpu(hp1).oper[0]^.val;
  11037. TestValMin := TestValMin and WorkingValue;
  11038. TestValMax := TestValMax and WorkingValue;
  11039. TestValSignedMax := TestValSignedMax and WorkingValue;
  11040. end;
  11041. A_OR:
  11042. begin
  11043. if not BitwiseOnly then
  11044. Break;
  11045. OrXorUsed := True;
  11046. WorkingValue := taicpu(hp1).oper[0]^.val;
  11047. TestValMin := TestValMin or WorkingValue;
  11048. TestValMax := TestValMax or WorkingValue;
  11049. TestValSignedMax := TestValSignedMax or WorkingValue;
  11050. end;
  11051. A_XOR:
  11052. begin
  11053. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11054. begin
  11055. TestValMin := 0;
  11056. TestValMax := 0;
  11057. TestValSignedMax := 0;
  11058. end
  11059. else
  11060. begin
  11061. if not BitwiseOnly then
  11062. Break;
  11063. OrXorUsed := True;
  11064. WorkingValue := taicpu(hp1).oper[0]^.val;
  11065. TestValMin := TestValMin xor WorkingValue;
  11066. TestValMax := TestValMax xor WorkingValue;
  11067. TestValSignedMax := TestValSignedMax xor WorkingValue;
  11068. end;
  11069. end;
  11070. A_SHL:
  11071. begin
  11072. BitwiseOnly := False;
  11073. WorkingValue := taicpu(hp1).oper[0]^.val;
  11074. TestValMin := TestValMin shl WorkingValue;
  11075. TestValMax := TestValMax shl WorkingValue;
  11076. TestValSignedMax := TestValSignedMax shl WorkingValue;
  11077. end;
  11078. A_SHR,
  11079. { The first instruction was MOVZX, so the value won't be negative }
  11080. A_SAR:
  11081. begin
  11082. if InstrMax <> -1 then
  11083. BitwiseOnly := False
  11084. else
  11085. { we might be able to go smaller if SHR appears first }
  11086. case MinSize of
  11087. S_B:
  11088. ;
  11089. S_W:
  11090. if (taicpu(hp1).oper[0]^.val >= 8) then
  11091. begin
  11092. TryShiftDown := S_B;
  11093. TryShiftDownLimit := $FF;
  11094. TryShiftDownSignedLimit := $7F;
  11095. TryShiftDownSignedLimitLower := -128;
  11096. end;
  11097. S_L:
  11098. if (taicpu(hp1).oper[0]^.val >= 24) then
  11099. begin
  11100. TryShiftDown := S_B;
  11101. TryShiftDownLimit := $FF;
  11102. TryShiftDownSignedLimit := $7F;
  11103. TryShiftDownSignedLimitLower := -128;
  11104. end
  11105. else if (taicpu(hp1).oper[0]^.val >= 16) then
  11106. begin
  11107. TryShiftDown := S_W;
  11108. TryShiftDownLimit := $FFFF;
  11109. TryShiftDownSignedLimit := $7FFF;
  11110. TryShiftDownSignedLimitLower := -32768;
  11111. end;
  11112. else
  11113. InternalError(2020112321);
  11114. end;
  11115. WorkingValue := taicpu(hp1).oper[0]^.val;
  11116. if taicpu(hp1).opcode = A_SAR then
  11117. begin
  11118. TestValMin := SarInt64(TestValMin, WorkingValue);
  11119. TestValMax := SarInt64(TestValMax, WorkingValue);
  11120. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  11121. end
  11122. else
  11123. begin
  11124. TestValMin := TestValMin shr WorkingValue;
  11125. TestValMax := TestValMax shr WorkingValue;
  11126. TestValSignedMax := TestValSignedMax shr WorkingValue;
  11127. end;
  11128. end;
  11129. else
  11130. InternalError(2020112303);
  11131. end;
  11132. end;
  11133. (*
  11134. A_IMUL:
  11135. case taicpu(hp1).ops of
  11136. 2:
  11137. begin
  11138. if not MatchOpType(hp1, top_reg, top_reg) or
  11139. { Has to be an exact match on the register }
  11140. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  11141. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  11142. Break;
  11143. TestValMin := TestValMin * TestValMin;
  11144. TestValMax := TestValMax * TestValMax;
  11145. TestValSignedMax := TestValSignedMax * TestValMax;
  11146. end;
  11147. 3:
  11148. begin
  11149. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  11150. { Has to be an exact match on the register }
  11151. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  11152. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  11153. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  11154. { Is it in the negative range? }
  11155. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  11156. Break;
  11157. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  11158. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  11159. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  11160. end;
  11161. else
  11162. Break;
  11163. end;
  11164. A_IDIV:
  11165. case taicpu(hp1).ops of
  11166. 3:
  11167. begin
  11168. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  11169. { Has to be an exact match on the register }
  11170. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  11171. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  11172. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  11173. { Is it in the negative range? }
  11174. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  11175. Break;
  11176. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  11177. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  11178. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  11179. end;
  11180. else
  11181. Break;
  11182. end;
  11183. *)
  11184. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11185. begin
  11186. { If there are no instructions in between, then we might be able to make a saving }
  11187. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  11188. Break;
  11189. { We have something like:
  11190. movzbw %dl,%dx
  11191. ...
  11192. movswl %dx,%edx
  11193. Change the latter to a zero-extension then enter the
  11194. A_MOVZX case branch.
  11195. }
  11196. {$ifdef x86_64}
  11197. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11198. begin
  11199. { this becomes a zero extension from 32-bit to 64-bit, but
  11200. the upper 32 bits are already zero, so just delete the
  11201. instruction }
  11202. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  11203. RemoveInstruction(hp1);
  11204. Result := True;
  11205. Exit;
  11206. end
  11207. else
  11208. {$endif x86_64}
  11209. begin
  11210. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  11211. taicpu(hp1).opcode := A_MOVZX;
  11212. {$ifdef x86_64}
  11213. case taicpu(hp1).opsize of
  11214. S_BQ:
  11215. begin
  11216. taicpu(hp1).opsize := S_BL;
  11217. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11218. end;
  11219. S_WQ:
  11220. begin
  11221. taicpu(hp1).opsize := S_WL;
  11222. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11223. end;
  11224. S_LQ:
  11225. begin
  11226. taicpu(hp1).opcode := A_MOV;
  11227. taicpu(hp1).opsize := S_L;
  11228. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11229. { In this instance, we need to break out because the
  11230. instruction is no longer MOVZX or MOVSXD }
  11231. Result := True;
  11232. Exit;
  11233. end;
  11234. else
  11235. ;
  11236. end;
  11237. {$endif x86_64}
  11238. Result := CompressInstructions;
  11239. Exit;
  11240. end;
  11241. end;
  11242. A_MOVZX:
  11243. begin
  11244. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  11245. Break;
  11246. if (InstrMax = -1) then
  11247. begin
  11248. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  11249. begin
  11250. { Optimise around i40003 }
  11251. { Check to see if the active register is used afterwards }
  11252. TransferUsedRegs(TmpUsedRegs);
  11253. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  11254. if (
  11255. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) or
  11256. not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs)
  11257. ) and
  11258. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  11259. {$ifndef x86_64}
  11260. and (
  11261. (taicpu(p).oper[0]^.typ <> top_reg) or
  11262. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  11263. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  11264. )
  11265. {$endif not x86_64}
  11266. then
  11267. begin
  11268. if (taicpu(p).oper[0]^.typ = top_reg) then
  11269. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  11270. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  11271. taicpu(p).opsize := S_BL;
  11272. { Only remove if the active register is overwritten }
  11273. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11274. begin
  11275. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  11276. RemoveInstruction(hp1);
  11277. end;
  11278. Result := True;
  11279. Exit;
  11280. end;
  11281. end
  11282. else
  11283. begin
  11284. { Will return false if the second parameter isn't ThisReg
  11285. (can happen on -O2 and under) }
  11286. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11287. begin
  11288. { The two MOVZX instructions are adjacent, so remove the first one }
  11289. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  11290. RemoveCurrentP(p);
  11291. Result := True;
  11292. Exit;
  11293. end;
  11294. Break;
  11295. end;
  11296. end;
  11297. Result := CompressInstructions;
  11298. Exit;
  11299. end;
  11300. else
  11301. { This includes ADC, SBB and IDIV }
  11302. Break;
  11303. end;
  11304. if not CheckOverflowConditions then
  11305. Break;
  11306. { Contains highest index (so instruction count - 1) }
  11307. Inc(InstrMax);
  11308. if InstrMax > High(InstrList) then
  11309. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11310. InstrList[InstrMax] := taicpu(hp1);
  11311. end;
  11312. end;
  11313. {$pop}
  11314. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  11315. var
  11316. hp1 : tai;
  11317. begin
  11318. Result:=false;
  11319. if (taicpu(p).ops >= 2) and
  11320. ((taicpu(p).oper[0]^.typ = top_const) or
  11321. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  11322. (taicpu(p).oper[1]^.typ = top_reg) and
  11323. ((taicpu(p).ops = 2) or
  11324. ((taicpu(p).oper[2]^.typ = top_reg) and
  11325. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  11326. GetLastInstruction(p,hp1) and
  11327. MatchInstruction(hp1,A_MOV,[]) and
  11328. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11329. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11330. begin
  11331. TransferUsedRegs(TmpUsedRegs);
  11332. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  11333. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  11334. { change
  11335. mov reg1,reg2
  11336. imul y,reg2 to imul y,reg1,reg2 }
  11337. begin
  11338. taicpu(p).ops := 3;
  11339. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  11340. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  11341. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  11342. RemoveInstruction(hp1);
  11343. result:=true;
  11344. end;
  11345. end;
  11346. end;
  11347. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  11348. var
  11349. ThisLabel: TAsmLabel;
  11350. begin
  11351. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  11352. ThisLabel.decrefs;
  11353. taicpu(p).condition := C_None;
  11354. taicpu(p).opcode := A_RET;
  11355. taicpu(p).is_jmp := false;
  11356. taicpu(p).ops := taicpu(ret_p).ops;
  11357. case taicpu(ret_p).ops of
  11358. 0:
  11359. taicpu(p).clearop(0);
  11360. 1:
  11361. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  11362. else
  11363. internalerror(2016041301);
  11364. end;
  11365. { If the original label is now dead, it might turn out that the label
  11366. immediately follows p. As a result, everything beyond it, which will
  11367. be just some final register configuration and a RET instruction, is
  11368. now dead code. [Kit] }
  11369. { NOTE: This is much faster than introducing a OptPass2RET routine and
  11370. running RemoveDeadCodeAfterJump for each RET instruction, because
  11371. this optimisation rarely happens and most RETs appear at the end of
  11372. routines where there is nothing that can be stripped. [Kit] }
  11373. if not ThisLabel.is_used then
  11374. RemoveDeadCodeAfterJump(p);
  11375. end;
  11376. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  11377. var
  11378. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  11379. Unconditional, PotentialModified: Boolean;
  11380. OperPtr: POper;
  11381. NewRef: TReference;
  11382. InstrList: array of taicpu;
  11383. InstrMax, Index: Integer;
  11384. const
  11385. {$ifdef DEBUG_AOPTCPU}
  11386. SNoFlags: shortstring = ' so the flags aren''t modified';
  11387. {$else DEBUG_AOPTCPU}
  11388. SNoFlags = '';
  11389. {$endif DEBUG_AOPTCPU}
  11390. begin
  11391. Result:=false;
  11392. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  11393. begin
  11394. if MatchInstruction(hp1, A_TEST, [S_B]) and
  11395. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11396. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11397. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11398. GetNextInstruction(hp1, hp2) and
  11399. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  11400. { Change from: To:
  11401. set(C) %reg j(~C) label
  11402. test %reg,%reg/cmp $0,%reg
  11403. je label
  11404. set(C) %reg j(C) label
  11405. test %reg,%reg/cmp $0,%reg
  11406. jne label
  11407. (Also do something similar with sete/setne instead of je/jne)
  11408. }
  11409. begin
  11410. { Before we do anything else, we need to check the instructions
  11411. in between SETcc and TEST to make sure they don't modify the
  11412. FLAGS register - if -O2 or under, there won't be any
  11413. instructions between SET and TEST }
  11414. TransferUsedRegs(TmpUsedRegs);
  11415. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11416. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11417. begin
  11418. next := p;
  11419. SetLength(InstrList, 0);
  11420. InstrMax := -1;
  11421. PotentialModified := False;
  11422. { Make a note of every instruction that modifies the FLAGS
  11423. register }
  11424. while GetNextInstruction(next, next) and (next <> hp1) do
  11425. begin
  11426. if next.typ <> ait_instruction then
  11427. { GetNextInstructionUsingReg should have returned False }
  11428. InternalError(2021051701);
  11429. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11430. begin
  11431. case taicpu(next).opcode of
  11432. A_SETcc,
  11433. A_CMOVcc,
  11434. A_Jcc:
  11435. begin
  11436. if PotentialModified then
  11437. { Not safe because the flags were modified earlier }
  11438. Exit
  11439. else
  11440. { Condition is the same as the initial SETcc, so this is safe
  11441. (don't add to instruction list though) }
  11442. Continue;
  11443. end;
  11444. A_ADD:
  11445. begin
  11446. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11447. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11448. (taicpu(next).oper[1]^.typ <> top_reg) or
  11449. { Must write to a register }
  11450. (taicpu(next).oper[0]^.typ = top_ref) then
  11451. { Require a constant or a register }
  11452. Exit;
  11453. PotentialModified := True;
  11454. end;
  11455. A_SUB:
  11456. begin
  11457. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11458. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11459. (taicpu(next).oper[1]^.typ <> top_reg) or
  11460. { Must write to a register }
  11461. (taicpu(next).oper[0]^.typ <> top_const) or
  11462. (taicpu(next).oper[0]^.val = $80000000) then
  11463. { Can't subtract a register with LEA - also
  11464. check that the value isn't -2^31, as this
  11465. can't be negated }
  11466. Exit;
  11467. PotentialModified := True;
  11468. end;
  11469. A_SAL,
  11470. A_SHL:
  11471. begin
  11472. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11473. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11474. (taicpu(next).oper[1]^.typ <> top_reg) or
  11475. { Must write to a register }
  11476. (taicpu(next).oper[0]^.typ <> top_const) or
  11477. (taicpu(next).oper[0]^.val < 0) or
  11478. (taicpu(next).oper[0]^.val > 3) then
  11479. Exit;
  11480. PotentialModified := True;
  11481. end;
  11482. A_IMUL:
  11483. begin
  11484. if (taicpu(next).ops <> 3) or
  11485. (taicpu(next).oper[1]^.typ <> top_reg) or
  11486. { Must write to a register }
  11487. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11488. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11489. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11490. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11491. Exit
  11492. else
  11493. PotentialModified := True;
  11494. end;
  11495. else
  11496. { Don't know how to change this, so abort }
  11497. Exit;
  11498. end;
  11499. { Contains highest index (so instruction count - 1) }
  11500. Inc(InstrMax);
  11501. if InstrMax > High(InstrList) then
  11502. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11503. InstrList[InstrMax] := taicpu(next);
  11504. end;
  11505. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11506. end;
  11507. if not Assigned(next) or (next <> hp1) then
  11508. { It should be equal to hp1 }
  11509. InternalError(2021051702);
  11510. { Cycle through each instruction and check to see if we can
  11511. change them to versions that don't modify the flags }
  11512. if (InstrMax >= 0) then
  11513. begin
  11514. for Index := 0 to InstrMax do
  11515. case InstrList[Index].opcode of
  11516. A_ADD:
  11517. begin
  11518. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11519. InstrList[Index].opcode := A_LEA;
  11520. reference_reset(NewRef, 1, []);
  11521. NewRef.base := InstrList[Index].oper[1]^.reg;
  11522. if InstrList[Index].oper[0]^.typ = top_reg then
  11523. begin
  11524. NewRef.index := InstrList[Index].oper[0]^.reg;
  11525. NewRef.scalefactor := 1;
  11526. end
  11527. else
  11528. NewRef.offset := InstrList[Index].oper[0]^.val;
  11529. InstrList[Index].loadref(0, NewRef);
  11530. end;
  11531. A_SUB:
  11532. begin
  11533. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11534. InstrList[Index].opcode := A_LEA;
  11535. reference_reset(NewRef, 1, []);
  11536. NewRef.base := InstrList[Index].oper[1]^.reg;
  11537. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11538. InstrList[Index].loadref(0, NewRef);
  11539. end;
  11540. A_SHL,
  11541. A_SAL:
  11542. begin
  11543. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11544. InstrList[Index].opcode := A_LEA;
  11545. reference_reset(NewRef, 1, []);
  11546. NewRef.index := InstrList[Index].oper[1]^.reg;
  11547. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11548. InstrList[Index].loadref(0, NewRef);
  11549. end;
  11550. A_IMUL:
  11551. begin
  11552. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11553. InstrList[Index].opcode := A_LEA;
  11554. reference_reset(NewRef, 1, []);
  11555. NewRef.index := InstrList[Index].oper[1]^.reg;
  11556. case InstrList[Index].oper[0]^.val of
  11557. 2, 4, 8:
  11558. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11559. else {3, 5 and 9}
  11560. begin
  11561. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11562. NewRef.base := InstrList[Index].oper[1]^.reg;
  11563. end;
  11564. end;
  11565. InstrList[Index].loadref(0, NewRef);
  11566. end;
  11567. else
  11568. InternalError(2021051710);
  11569. end;
  11570. end;
  11571. { Mark the FLAGS register as used across this whole block }
  11572. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11573. end;
  11574. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11575. JumpC := taicpu(hp2).condition;
  11576. Unconditional := False;
  11577. if conditions_equal(JumpC, C_E) then
  11578. SetC := inverse_cond(taicpu(p).condition)
  11579. else if conditions_equal(JumpC, C_NE) then
  11580. SetC := taicpu(p).condition
  11581. else
  11582. { We've got something weird here (and inefficent) }
  11583. begin
  11584. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11585. SetC := C_NONE;
  11586. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11587. if condition_in(C_AE, JumpC) then
  11588. Unconditional := True
  11589. else
  11590. { Not sure what to do with this jump - drop out }
  11591. Exit;
  11592. end;
  11593. RemoveInstruction(hp1);
  11594. if Unconditional then
  11595. MakeUnconditional(taicpu(hp2))
  11596. else
  11597. begin
  11598. if SetC = C_NONE then
  11599. InternalError(2018061402);
  11600. taicpu(hp2).SetCondition(SetC);
  11601. end;
  11602. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11603. TmpUsedRegs }
  11604. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11605. begin
  11606. RemoveCurrentp(p, hp2);
  11607. if taicpu(hp2).opcode = A_SETcc then
  11608. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11609. else
  11610. begin
  11611. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11612. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11613. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11614. end;
  11615. end
  11616. else
  11617. if taicpu(hp2).opcode = A_SETcc then
  11618. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11619. else
  11620. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11621. Result := True;
  11622. end
  11623. else if
  11624. { Make sure the instructions are adjacent }
  11625. (
  11626. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11627. GetNextInstruction(p, hp1)
  11628. ) and
  11629. MatchInstruction(hp1, A_MOV, [S_B]) and
  11630. { Writing to memory is allowed }
  11631. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11632. begin
  11633. {
  11634. Watch out for sequences such as:
  11635. set(c)b %regb
  11636. movb %regb,(ref)
  11637. movb $0,1(ref)
  11638. movb $0,2(ref)
  11639. movb $0,3(ref)
  11640. Much more efficient to turn it into:
  11641. movl $0,%regl
  11642. set(c)b %regb
  11643. movl %regl,(ref)
  11644. Or:
  11645. set(c)b %regb
  11646. movzbl %regb,%regl
  11647. movl %regl,(ref)
  11648. }
  11649. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11650. GetNextInstruction(hp1, hp2) and
  11651. MatchInstruction(hp2, A_MOV, [S_B]) and
  11652. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11653. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11654. begin
  11655. { Don't do anything else except set Result to True }
  11656. end
  11657. else
  11658. begin
  11659. if taicpu(p).oper[0]^.typ = top_reg then
  11660. begin
  11661. TransferUsedRegs(TmpUsedRegs);
  11662. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11663. end;
  11664. { If it's not a register, it's a memory address }
  11665. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11666. begin
  11667. { Even if the register is still in use, we can minimise the
  11668. pipeline stall by changing the MOV into another SETcc. }
  11669. taicpu(hp1).opcode := A_SETcc;
  11670. taicpu(hp1).condition := taicpu(p).condition;
  11671. if taicpu(hp1).oper[1]^.typ = top_ref then
  11672. begin
  11673. { Swapping the operand pointers like this is probably a
  11674. bit naughty, but it is far faster than using loadoper
  11675. to transfer the reference from oper[1] to oper[0] if
  11676. you take into account the extra procedure calls and
  11677. the memory allocation and deallocation required }
  11678. OperPtr := taicpu(hp1).oper[1];
  11679. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11680. taicpu(hp1).oper[0] := OperPtr;
  11681. end
  11682. else
  11683. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11684. taicpu(hp1).clearop(1);
  11685. taicpu(hp1).ops := 1;
  11686. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11687. end
  11688. else
  11689. begin
  11690. if taicpu(hp1).oper[1]^.typ = top_reg then
  11691. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11692. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11693. RemoveInstruction(hp1);
  11694. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11695. end
  11696. end;
  11697. Result := True;
  11698. end;
  11699. end;
  11700. end;
  11701. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11702. var
  11703. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11704. TargetReg: TRegister;
  11705. condition, inverted_condition: TAsmCond;
  11706. FoundMOV: Boolean;
  11707. begin
  11708. Result := False;
  11709. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11710. create the most optimial instructions possible due to limited
  11711. register availability, and there are situations where two
  11712. complementary "simple" CMOV blocks are created which, after the fact
  11713. can be merged into a "double" block. For example:
  11714. movw $257,%ax
  11715. movw $2,%r8w
  11716. xorl r9d,%r9d
  11717. testw $16,18(%rcx)
  11718. cmovew %ax,%dx
  11719. cmovew %r8w,%bx
  11720. cmovel %r9d,%r14d
  11721. movw $1283,%ax
  11722. movw $4,%r8w
  11723. movl $9,%r9d
  11724. cmovnew %ax,%dx
  11725. cmovnew %r8w,%bx
  11726. cmovnel %r9d,%r14d
  11727. The CMOVNE instructions at the end can be removed, and the
  11728. destination registers copied into the MOV instructions directly
  11729. above them, before finally being moved to before the first CMOVE
  11730. instructions, to produce:
  11731. movw $257,%ax
  11732. movw $2,%r8w
  11733. xorl r9d,%r9d
  11734. testw $16,18(%rcx)
  11735. movw $1283,%dx
  11736. movw $4,%bx
  11737. movl $9,%r14d
  11738. cmovew %ax,%dx
  11739. cmovew %r8w,%bx
  11740. cmovel %r9d,%r14d
  11741. Which can then be later optimised to:
  11742. movw $257,%ax
  11743. movw $2,%r8w
  11744. xorl r9d,%r9d
  11745. movw $1283,%dx
  11746. movw $4,%bx
  11747. movl $9,%r14d
  11748. testw $16,18(%rcx)
  11749. cmovew %ax,%dx
  11750. cmovew %r8w,%bx
  11751. cmovel %r9d,%r14d
  11752. }
  11753. TargetReg := taicpu(hp1).oper[1]^.reg;
  11754. condition := taicpu(hp1).condition;
  11755. inverted_condition := inverse_cond(condition);
  11756. pFirstMov := nil;
  11757. pLastMov := nil;
  11758. pCMOV := nil;
  11759. if (p.typ = ait_instruction) then
  11760. pCond := p
  11761. else if not GetNextInstruction(p, pCond) then
  11762. InternalError(2024012501);
  11763. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11764. { We should get the CMP or TEST instructeion }
  11765. InternalError(2024012502);
  11766. if (
  11767. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11768. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11769. ) then
  11770. begin
  11771. { We have to tread carefully here, hence why we're not using
  11772. GetNextInstructionUsingReg... we can only accept MOV and other
  11773. CMOV instructions. Anything else and we must drop out}
  11774. hp2 := hp1;
  11775. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11776. begin
  11777. if (hp2.typ <> ait_instruction) then
  11778. Exit;
  11779. case taicpu(hp2).opcode of
  11780. A_MOV:
  11781. begin
  11782. if not Assigned(pFirstMov) then
  11783. pFirstMov := hp2;
  11784. pLastMOV := hp2;
  11785. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11786. { Something different - drop out }
  11787. Exit;
  11788. { Otherwise, leave it for now }
  11789. end;
  11790. A_CMOVcc:
  11791. begin
  11792. if taicpu(hp2).condition = inverted_condition then
  11793. begin
  11794. { We found what we're looking for }
  11795. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11796. begin
  11797. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11798. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11799. begin
  11800. pCMOV := hp2;
  11801. Break;
  11802. end
  11803. else
  11804. { Unsafe reference - drop out }
  11805. Exit;
  11806. end;
  11807. end
  11808. else if taicpu(hp2).condition <> condition then
  11809. { Something weird - drop out }
  11810. Exit;
  11811. end;
  11812. else
  11813. { Invalid }
  11814. Exit;
  11815. end;
  11816. end;
  11817. if not Assigned(pCMOV) then
  11818. { No complementary CMOV found }
  11819. Exit;
  11820. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11821. begin
  11822. { Don't need to do anything special or search for a matching MOV }
  11823. Asml.Remove(pCMOV);
  11824. if RegInInstruction(TargetReg, pCond) then
  11825. { Make sure we don't overwrite the register if it's being used in the condition }
  11826. Asml.InsertAfter(pCMOV, pCond)
  11827. else
  11828. Asml.InsertBefore(pCMOV, pCond);
  11829. taicpu(pCMOV).opcode := A_MOV;
  11830. taicpu(pCMOV).condition := C_None;
  11831. { Don't need to worry about allocating new registers in these cases }
  11832. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11833. Result := True;
  11834. Exit;
  11835. end
  11836. else
  11837. begin
  11838. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11839. FoundMOV := False;
  11840. { Search for the MOV that sets the target register }
  11841. hp2 := pFirstMov;
  11842. repeat
  11843. if (taicpu(hp2).opcode = A_MOV) and
  11844. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11845. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11846. begin
  11847. { Change the destination }
  11848. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11849. if not FoundMOV then
  11850. begin
  11851. FoundMOV := True;
  11852. { Make sure the register is allocated }
  11853. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11854. end;
  11855. hp1 := tai(hp2.Previous);
  11856. Asml.Remove(hp2);
  11857. if RegInInstruction(TargetReg, pCond) then
  11858. { Make sure we don't overwrite the register if it's being used in the condition }
  11859. Asml.InsertAfter(hp2, pCond)
  11860. else
  11861. Asml.InsertBefore(hp2, pCond);
  11862. if (hp2 = pLastMov) then
  11863. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11864. Break;
  11865. hp2 := hp1;
  11866. end;
  11867. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11868. if FoundMOV then
  11869. { Delete the CMOV }
  11870. RemoveInstruction(pCMOV)
  11871. else
  11872. begin
  11873. { If no MOV was found, we have to actually move and transmute the CMOV }
  11874. Asml.Remove(pCMOV);
  11875. if RegInInstruction(TargetReg, pCond) then
  11876. { Make sure we don't overwrite the register if it's being used in the condition }
  11877. Asml.InsertAfter(pCMOV, pCond)
  11878. else
  11879. Asml.InsertBefore(pCMOV, pCond);
  11880. taicpu(pCMOV).opcode := A_MOV;
  11881. taicpu(pCMOV).condition := C_None;
  11882. end;
  11883. Result := True;
  11884. Exit;
  11885. end;
  11886. end;
  11887. end;
  11888. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11889. var
  11890. hp1, hp2, pCond: tai;
  11891. begin
  11892. Result := False;
  11893. { Search ahead for CMOV instructions }
  11894. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11895. begin
  11896. hp1 := p;
  11897. hp2 := p;
  11898. pCond := nil; { To prevent compiler warnings }
  11899. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11900. DEFAULTFLAGS }
  11901. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11902. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11903. pCond := p;
  11904. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11905. begin
  11906. if (hp1.typ <> ait_instruction) then
  11907. { Break out on markers and labels etc. }
  11908. Break;
  11909. case taicpu(hp1).opcode of
  11910. A_MOV:
  11911. { Ignore regular MOVs unless they are obviously not related
  11912. to a CMOV block }
  11913. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11914. Break;
  11915. A_CMOVcc:
  11916. if TryCmpCMovOpts(pCond, hp1) then
  11917. begin
  11918. hp1 := hp2;
  11919. { p itself isn't changed, and we're still inside a
  11920. while loop to catch subsequent CMOVs, so just flag
  11921. a new iteration }
  11922. Include(OptsToCheck, aoc_ForceNewIteration);
  11923. Continue;
  11924. end;
  11925. else
  11926. { Drop out if we find anything else }
  11927. Break;
  11928. end;
  11929. hp2 := hp1;
  11930. end;
  11931. end;
  11932. end;
  11933. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11934. var
  11935. hp1, hp2, pCond: tai;
  11936. SourceReg, TargetReg: TRegister;
  11937. begin
  11938. Result := False;
  11939. { In some situations, we end up with an inefficient arrangement of
  11940. instructions in the form of:
  11941. or %reg1,%reg2
  11942. (%reg1 deallocated)
  11943. test %reg2,%reg2
  11944. mov x,%reg2
  11945. we may be able to swap and rearrange the registers to produce:
  11946. or %reg2,%reg1
  11947. mov x,%reg2
  11948. test %reg1,%reg1
  11949. (%reg1 deallocated)
  11950. }
  11951. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11952. (taicpu(p).oper[1]^.typ = top_reg) and
  11953. (
  11954. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11955. MatchOperand(taicpu(p).oper[0]^, -1)
  11956. ) and
  11957. GetNextInstruction(p, hp1) and
  11958. MatchInstruction(hp1, A_MOV, []) and
  11959. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11960. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11961. begin
  11962. TargetReg := taicpu(p).oper[1]^.reg;
  11963. { Now look backwards to find a simple commutative operation: ADD,
  11964. IMUL (2-register version), OR, AND or XOR - whose destination
  11965. register is the same as TEST }
  11966. hp2 := p;
  11967. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11968. if RegInInstruction(TargetReg, hp2) then
  11969. begin
  11970. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11971. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11972. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11973. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11974. begin
  11975. SourceReg := taicpu(hp2).oper[0]^.reg;
  11976. if
  11977. { Make sure the MOV doesn't use the other register }
  11978. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11979. { And make sure the source register is not used afterwards }
  11980. not RegInUsedRegs(SourceReg, UsedRegs) then
  11981. begin
  11982. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11983. taicpu(hp2).oper[0]^.reg := TargetReg;
  11984. taicpu(hp2).oper[1]^.reg := SourceReg;
  11985. if taicpu(p).oper[0]^.typ = top_reg then
  11986. taicpu(p).oper[0]^.reg := SourceReg;
  11987. taicpu(p).oper[1]^.reg := SourceReg;
  11988. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11989. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11990. Include(OptsToCheck, aoc_ForceNewIteration);
  11991. { We can still check the following optimisations since
  11992. the instruction is still a TEST }
  11993. end;
  11994. end;
  11995. Break;
  11996. end;
  11997. end;
  11998. { Search ahead3 for CMOV instructions }
  11999. if (cs_opt_level2 in current_settings.optimizerswitches) then
  12000. begin
  12001. hp1 := p;
  12002. hp2 := p;
  12003. pCond := nil; { To prevent compiler warnings }
  12004. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  12005. DEFAULTFLAGS }
  12006. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  12007. (tai_regalloc(pCond).ratype = ra_dealloc) then
  12008. pCond := p;
  12009. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  12010. begin
  12011. if (hp1.typ <> ait_instruction) then
  12012. { Break out on markers and labels etc. }
  12013. Break;
  12014. case taicpu(hp1).opcode of
  12015. A_MOV:
  12016. { Ignore regular MOVs unless they are obviously not related
  12017. to a CMOV block }
  12018. if taicpu(hp1).oper[1]^.typ <> top_reg then
  12019. Break;
  12020. A_CMOVcc:
  12021. if TryCmpCMovOpts(pCond, hp1) then
  12022. begin
  12023. hp1 := hp2;
  12024. { p itself isn't changed, and we're still inside a
  12025. while loop to catch subsequent CMOVs, so just flag
  12026. a new iteration }
  12027. Include(OptsToCheck, aoc_ForceNewIteration);
  12028. Continue;
  12029. end;
  12030. else
  12031. { Drop out if we find anything else }
  12032. Break;
  12033. end;
  12034. hp2 := hp1;
  12035. end;
  12036. end;
  12037. end;
  12038. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  12039. var
  12040. hp1: tai;
  12041. Count: Integer;
  12042. OrigLabel: TAsmLabel;
  12043. begin
  12044. result := False;
  12045. { Sometimes, the optimisations below can permit this }
  12046. RemoveDeadCodeAfterJump(p);
  12047. 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
  12048. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  12049. begin
  12050. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12051. { Also a side-effect of optimisations }
  12052. if CollapseZeroDistJump(p, OrigLabel) then
  12053. begin
  12054. Result := True;
  12055. Exit;
  12056. end;
  12057. hp1 := GetLabelWithSym(OrigLabel);
  12058. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  12059. begin
  12060. if taicpu(hp1).opcode = A_RET then
  12061. begin
  12062. {
  12063. change
  12064. jmp .L1
  12065. ...
  12066. .L1:
  12067. ret
  12068. into
  12069. ret
  12070. }
  12071. begin
  12072. ConvertJumpToRET(p, hp1);
  12073. result:=true;
  12074. end;
  12075. end
  12076. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  12077. not (cs_opt_size in current_settings.optimizerswitches) and
  12078. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  12079. begin
  12080. Result := True;
  12081. Exit;
  12082. end;
  12083. end;
  12084. end;
  12085. end;
  12086. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  12087. begin
  12088. Result := assigned(p) and
  12089. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  12090. (taicpu(p).oper[1]^.typ = top_reg) and
  12091. (
  12092. (taicpu(p).oper[0]^.typ = top_reg) or
  12093. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  12094. it is not expected that this can cause a seg. violation }
  12095. (
  12096. (taicpu(p).oper[0]^.typ = top_ref) and
  12097. { TODO: Can we detect which references become constants at this
  12098. stage so we don't have to do a blanket ban? }
  12099. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  12100. (
  12101. IsRefSafe(taicpu(p).oper[0]^.ref) or
  12102. (
  12103. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  12104. not RefModified and
  12105. { If the reference also appears in the condition, then we know it's safe, otherwise
  12106. any kind of access violation would have occurred already }
  12107. Assigned(cond_p) and
  12108. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  12109. (cond_p.typ = ait_instruction) and
  12110. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  12111. { Just consider 2-operand comparison instructions for now to be safe }
  12112. (taicpu(cond_p).ops = 2) and
  12113. (
  12114. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  12115. (
  12116. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  12117. { Don't risk identical registers but different offsets, as we may have constructs
  12118. such as buffer streams with things like length fields that indicate whether
  12119. any more data follows. And there are probably some contrived examples where
  12120. writing to offsets behind the one being read also lead to access violations }
  12121. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  12122. (
  12123. { Check that we're not modifying a register that appears in the reference }
  12124. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  12125. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  12126. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  12127. )
  12128. )
  12129. )
  12130. )
  12131. )
  12132. )
  12133. );
  12134. end;
  12135. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  12136. begin
  12137. { Update integer registers, ignoring deallocations }
  12138. repeat
  12139. while assigned(p) and
  12140. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  12141. (p.typ = ait_label) or
  12142. ((p.typ = ait_marker) and
  12143. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  12144. p := tai(p.next);
  12145. while assigned(p) and
  12146. (p.typ=ait_RegAlloc) Do
  12147. begin
  12148. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  12149. begin
  12150. case tai_regalloc(p).ratype of
  12151. ra_alloc :
  12152. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  12153. else
  12154. ;
  12155. end;
  12156. end;
  12157. p := tai(p.next);
  12158. end;
  12159. until not(assigned(p)) or
  12160. (not(p.typ in SkipInstr) and
  12161. not((p.typ = ait_label) and
  12162. labelCanBeSkipped(tai_label(p))));
  12163. end;
  12164. {$ifndef 8086}
  12165. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  12166. begin
  12167. Result := False;
  12168. EndJump := nil;
  12169. BlockStop := nil;
  12170. while (BlockStart <> fOptimizer.BlockEnd) and
  12171. { stop on labels }
  12172. (BlockStart.typ <> ait_label) do
  12173. begin
  12174. { Keep track of all integer registers that are used }
  12175. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  12176. if BlockStart.typ = ait_instruction then
  12177. begin
  12178. if (taicpu(BlockStart).opcode = A_JMP) then
  12179. begin
  12180. if not IsJumpToLabel(taicpu(BlockStart)) or
  12181. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  12182. Exit;
  12183. EndJump := BlockStart;
  12184. Break;
  12185. end
  12186. { Check to see if we have a valid MOV instruction instead }
  12187. else if (taicpu(BlockStart).opcode <> A_MOV) or
  12188. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  12189. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12190. begin
  12191. Exit;
  12192. end
  12193. else
  12194. { This will be a valid MOV }
  12195. fAllocationRange := BlockStart;
  12196. end;
  12197. OneBeforeBlock := BlockStart;
  12198. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  12199. end;
  12200. if (BlockStart = fOptimizer.BlockEnd) then
  12201. Exit;
  12202. BlockStop := BlockStart;
  12203. Result := True;
  12204. end;
  12205. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  12206. var
  12207. hp1: tai;
  12208. RefModified: Boolean;
  12209. begin
  12210. Result := 0;
  12211. hp1 := BlockStart;
  12212. RefModified := False; { As long as the condition is inverted, this can be reset }
  12213. while assigned(hp1) and
  12214. (hp1 <> BlockStop) do
  12215. begin
  12216. case hp1.typ of
  12217. ait_instruction:
  12218. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12219. begin
  12220. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  12221. begin
  12222. Inc(Result);
  12223. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  12224. Assigned(fCondition) and
  12225. { Will have 2 operands }
  12226. (
  12227. (
  12228. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  12229. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  12230. ) or
  12231. (
  12232. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  12233. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  12234. )
  12235. ) then
  12236. { It is no longer safe to use the reference in the condition.
  12237. this prevents problems such as:
  12238. mov (%reg),%reg
  12239. mov (%reg),...
  12240. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  12241. (fixes #40165)
  12242. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  12243. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  12244. }
  12245. RefModified := True;
  12246. end
  12247. else if not (cs_opt_size in current_settings.optimizerswitches) and
  12248. { CMOV with constants grows the code size }
  12249. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  12250. begin
  12251. { Register was reserved by TryCMOVConst and
  12252. stored on ConstRegs }
  12253. end
  12254. else
  12255. begin
  12256. Result := -1;
  12257. Exit;
  12258. end;
  12259. end
  12260. else
  12261. begin
  12262. Result := -1;
  12263. Exit;
  12264. end;
  12265. else
  12266. { Most likely an align };
  12267. end;
  12268. fOptimizer.GetNextInstruction(hp1, hp1);
  12269. end;
  12270. end;
  12271. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  12272. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  12273. (this is done as a separate stage because the double types are extensions of the branching type,
  12274. but we can't discount the conditional jump until the last step) }
  12275. procedure EvaluateBranchingType;
  12276. begin
  12277. Inc(CMOVScore);
  12278. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  12279. { Too many instructions to be worthwhile }
  12280. fState := tsInvalid;
  12281. end;
  12282. var
  12283. hp1: tai;
  12284. Count: Integer;
  12285. begin
  12286. { Table of valid CMOV block types
  12287. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  12288. ---------- --------- --------- --------- --------- ---------
  12289. tsSimple X Yes X X X
  12290. tsDetour = 1st X X X X
  12291. tsBranching <> Mid Yes X X X
  12292. tsDouble End-label Yes * Yes X Yes
  12293. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  12294. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  12295. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  12296. * Only one reference allowed
  12297. }
  12298. hp1 := nil; { To prevent compiler warnings }
  12299. Optimizer.CopyUsedRegs(RegisterTracking);
  12300. fOptimizer := Optimizer;
  12301. fLabel := AFirstLabel;
  12302. CMOVScore := 0;
  12303. ConstCount := 0;
  12304. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  12305. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  12306. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  12307. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  12308. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  12309. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  12310. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  12311. fInsertionPoint := p_initialjump;
  12312. fCondition := nil;
  12313. fInitialJump := p_initialjump;
  12314. fFirstMovBlock := p_initialmov;
  12315. fFirstMovBlockStop := nil;
  12316. fSecondJump := nil;
  12317. fSecondMovBlock := nil;
  12318. fSecondMovBlockStop := nil;
  12319. fMidLabel := nil;
  12320. fSecondJump := nil;
  12321. fSecondMovBlock := nil;
  12322. fEndLabel := nil;
  12323. fAllocationRange := nil;
  12324. { Assume it all goes horribly wrong! }
  12325. fState := tsInvalid;
  12326. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  12327. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  12328. MatchInstruction(fCondition, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  12329. begin
  12330. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  12331. for Count := 0 to 1 do
  12332. with taicpu(fCondition).oper[Count]^ do
  12333. case typ of
  12334. top_reg:
  12335. if getregtype(reg) = R_INTREGISTER then
  12336. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12337. top_ref:
  12338. begin
  12339. if
  12340. {$ifdef x86_64}
  12341. (ref^.base <> NR_RIP) and
  12342. {$endif x86_64}
  12343. (ref^.base <> NR_NO) then
  12344. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12345. if (ref^.index <> NR_NO) then
  12346. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12347. end
  12348. else
  12349. ;
  12350. end;
  12351. { When inserting instructions before hp_prev, try to insert them
  12352. before the allocation of the FLAGS register }
  12353. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  12354. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  12355. { If not found, set it equal to the condition so it's something sensible }
  12356. fInsertionPoint := fCondition;
  12357. { When dealing with a comparison against zero, take note of the
  12358. instruction before it to see if we can move instructions further
  12359. back in order to benefit PostPeepholeOptTestOr.
  12360. }
  12361. if (
  12362. (
  12363. (taicpu(fCondition).opcode = A_CMP) and
  12364. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  12365. ) or
  12366. (
  12367. (taicpu(fCondition).opcode = A_TEST) and
  12368. (
  12369. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  12370. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  12371. )
  12372. )
  12373. ) and
  12374. Optimizer.GetLastInstruction(fCondition, hp1) then
  12375. begin
  12376. { These instructions set the zero flag if the result is zero }
  12377. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  12378. begin
  12379. fInsertionPoint := hp1;
  12380. { Also mark all the registers in this previous instruction
  12381. as 'in use', even if they've just been deallocated }
  12382. for Count := 0 to 1 do
  12383. with taicpu(hp1).oper[Count]^ do
  12384. case typ of
  12385. top_reg:
  12386. if getregtype(reg) = R_INTREGISTER then
  12387. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12388. top_ref:
  12389. begin
  12390. if
  12391. {$ifdef x86_64}
  12392. (ref^.base <> NR_RIP) and
  12393. {$endif x86_64}
  12394. (ref^.base <> NR_NO) then
  12395. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12396. if (ref^.index <> NR_NO) then
  12397. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12398. end
  12399. else
  12400. ;
  12401. end;
  12402. end;
  12403. end;
  12404. end
  12405. else
  12406. fCondition := nil;
  12407. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  12408. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  12409. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  12410. { If not found, set it equal to p so it's something sensible }
  12411. fInsertionPoint := hp1;
  12412. hp1 := p_initialmov;
  12413. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  12414. Exit;
  12415. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  12416. if (hp1.typ <> ait_label) then { should be on a jump }
  12417. begin
  12418. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  12419. { Need a label afterwards }
  12420. Exit;
  12421. end
  12422. else
  12423. fMidLabel := hp1;
  12424. if tai_label(fMidLabel).labsym <> AFirstLabel then
  12425. { Not the correct label }
  12426. fMidLabel := nil;
  12427. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12428. { If there's neither a 2nd jump nor correct label, then it's invalid
  12429. (see above table) }
  12430. Exit;
  12431. { Analyse the first block of MOVs more closely }
  12432. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12433. if Assigned(fSecondJump) then
  12434. begin
  12435. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12436. begin
  12437. fState := tsDetour
  12438. end
  12439. else
  12440. begin
  12441. { Need the correct mid-label for this one }
  12442. if not Assigned(fMidLabel) then
  12443. Exit;
  12444. fState := tsBranching;
  12445. end;
  12446. end
  12447. else
  12448. { No jump. but mid-label is present }
  12449. fState := tsSimple;
  12450. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12451. begin
  12452. { Invalid or too many instructions to be worthwhile }
  12453. fState := tsInvalid;
  12454. Exit;
  12455. end;
  12456. { check further for
  12457. jCC xxx
  12458. <several movs 1>
  12459. jmp yyy
  12460. xxx:
  12461. <several movs 2>
  12462. yyy:
  12463. etc.
  12464. }
  12465. if (fState = tsBranching) and
  12466. { Estimate for required savings for extra jump }
  12467. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12468. { Only one reference is allowed for double blocks }
  12469. (AFirstLabel.getrefs = 1) then
  12470. begin
  12471. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12472. fSecondMovBlock := hp1;
  12473. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12474. begin
  12475. EvaluateBranchingType;
  12476. Exit;
  12477. end;
  12478. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12479. if (hp1.typ <> ait_label) then { should be on a jump }
  12480. begin
  12481. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12482. begin
  12483. { Need a label afterwards }
  12484. EvaluateBranchingType;
  12485. Exit;
  12486. end;
  12487. end
  12488. else
  12489. fEndLabel := hp1;
  12490. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12491. { Second jump doesn't go to the end }
  12492. fEndLabel := nil;
  12493. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12494. begin
  12495. { If there's neither a 3rd jump nor correct end label, then it's
  12496. not a invalid double block, but is a valid single branching
  12497. block (see above table) }
  12498. EvaluateBranchingType;
  12499. Exit;
  12500. end;
  12501. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12502. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12503. { Invalid or too many instructions to be worthwhile }
  12504. Exit;
  12505. Inc(CMOVScore, Count);
  12506. if Assigned(fThirdJump) then
  12507. begin
  12508. if not Assigned(fSecondJump) then
  12509. fState := tsDoubleSecondBranching
  12510. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12511. fState := tsDoubleBranchSame
  12512. else
  12513. fState := tsDoubleBranchDifferent;
  12514. end
  12515. else
  12516. fState := tsDouble;
  12517. end;
  12518. if fState = tsBranching then
  12519. EvaluateBranchingType;
  12520. end;
  12521. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12522. new register to store the constant }
  12523. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12524. var
  12525. RegSize: TSubRegister;
  12526. CurrentVal: TCGInt;
  12527. ANewReg: TRegister;
  12528. X: ShortInt;
  12529. begin
  12530. Result := False;
  12531. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12532. Exit;
  12533. if ConstCount >= MAX_CMOV_REGISTERS then
  12534. { Arrays are full }
  12535. Exit;
  12536. { Remember that CMOV can't encode 8-bit registers }
  12537. case taicpu(p).opsize of
  12538. S_W:
  12539. RegSize := R_SUBW;
  12540. S_L:
  12541. RegSize := R_SUBD;
  12542. {$ifdef x86_64}
  12543. S_Q:
  12544. RegSize := R_SUBQ;
  12545. {$endif x86_64}
  12546. else
  12547. InternalError(2021100401);
  12548. end;
  12549. { See if the value has already been reserved for another CMOV instruction }
  12550. CurrentVal := taicpu(p).oper[0]^.val;
  12551. for X := 0 to ConstCount - 1 do
  12552. if ConstVals[X] = CurrentVal then
  12553. begin
  12554. ConstRegs[ConstCount] := ConstRegs[X];
  12555. ConstSizes[ConstCount] := RegSize;
  12556. ConstVals[ConstCount] := CurrentVal;
  12557. Inc(ConstCount);
  12558. Inc(Count);
  12559. Result := True;
  12560. Exit;
  12561. end;
  12562. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12563. if ANewReg = NR_NO then
  12564. { No free registers }
  12565. Exit;
  12566. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12567. up vying for the same register }
  12568. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12569. ConstRegs[ConstCount] := ANewReg;
  12570. ConstSizes[ConstCount] := RegSize;
  12571. ConstVals[ConstCount] := CurrentVal;
  12572. Inc(ConstCount);
  12573. Inc(Count);
  12574. Result := True;
  12575. end;
  12576. destructor TCMOVTracking.Done;
  12577. begin
  12578. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12579. end;
  12580. procedure TCMOVTracking.Process(out new_p: tai);
  12581. var
  12582. Count, Writes: LongInt;
  12583. RegMatch: Boolean;
  12584. hp1, hp_new: tai;
  12585. inverted_condition, condition: TAsmCond;
  12586. begin
  12587. if (fState in [tsInvalid, tsProcessed]) then
  12588. InternalError(2023110701);
  12589. { Repurpose RegisterTracking to mark registers that we've defined }
  12590. RegisterTracking[R_INTREGISTER].Clear;
  12591. Count := 0;
  12592. Writes := 0;
  12593. condition := taicpu(fInitialJump).condition;
  12594. inverted_condition := inverse_cond(condition);
  12595. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12596. doesn't get CMOVs in this case }
  12597. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12598. begin
  12599. { Include the jump in the flag tracking }
  12600. if Assigned(fThirdJump) then
  12601. begin
  12602. if (fState = tsDoubleBranchSame) then
  12603. begin
  12604. { Will be an unconditional jump, so track to the instruction before it }
  12605. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12606. InternalError(2023110710);
  12607. end
  12608. else
  12609. hp1 := fThirdJump;
  12610. end
  12611. else
  12612. hp1 := fSecondMovBlockStop;
  12613. end
  12614. else
  12615. begin
  12616. { Include a conditional jump in the flag tracking }
  12617. if Assigned(fSecondJump) then
  12618. begin
  12619. if (fState = tsDetour) then
  12620. begin
  12621. { Will be an unconditional jump, so track to the instruction before it }
  12622. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12623. InternalError(2023110711);
  12624. end
  12625. else
  12626. hp1 := fSecondJump;
  12627. end
  12628. else
  12629. hp1 := fFirstMovBlockStop;
  12630. end;
  12631. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12632. { Process the second set of MOVs first, because if a destination
  12633. register is shared between the first and second MOV sets, it is more
  12634. efficient to turn the first one into a MOV instruction and place it
  12635. before the CMP if possible, but we won't know which registers are
  12636. shared until we've processed at least one list, so we might as well
  12637. make it the second one since that won't be modified again. }
  12638. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12639. begin
  12640. hp1 := fSecondMovBlock;
  12641. repeat
  12642. if not Assigned(hp1) then
  12643. InternalError(2018062902);
  12644. if (hp1.typ = ait_instruction) then
  12645. begin
  12646. { Extra safeguard }
  12647. if (taicpu(hp1).opcode <> A_MOV) then
  12648. InternalError(2018062903);
  12649. { Note: tsDoubleBranchDifferent is essentially identical to
  12650. tsBranching and the 2nd block is best left largely
  12651. untouched, but we need to evaluate which registers the MOVs
  12652. write to in order to track what would be complementary CMOV
  12653. pairs that can be further optimised. [Kit] }
  12654. if fState <> tsDoubleBranchDifferent then
  12655. begin
  12656. if taicpu(hp1).oper[0]^.typ = top_const then
  12657. begin
  12658. RegMatch := False;
  12659. for Count := 0 to ConstCount - 1 do
  12660. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12661. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12662. begin
  12663. RegMatch := True;
  12664. { If it's in RegisterTracking, then this register
  12665. is being used more than once and hence has
  12666. already had its value defined (it gets added to
  12667. UsedRegs through AllocRegBetween below) }
  12668. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12669. begin
  12670. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12671. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12672. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12673. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12674. ConstMovs[Count] := hp_new;
  12675. end
  12676. else
  12677. { We just need an instruction between hp_prev and hp1
  12678. where we know the register is marked as in use }
  12679. hp_new := fSecondMovBlock;
  12680. { Keep track of largest write for this register so it can be optimised later }
  12681. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12682. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12683. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12684. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12685. Break;
  12686. end;
  12687. if not RegMatch then
  12688. InternalError(2021100411);
  12689. end;
  12690. taicpu(hp1).opcode := A_CMOVcc;
  12691. taicpu(hp1).condition := condition;
  12692. end;
  12693. { Store these writes to search for duplicates later on }
  12694. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12695. Inc(Writes);
  12696. end;
  12697. fOptimizer.GetNextInstruction(hp1, hp1);
  12698. until (hp1 = fSecondMovBlockStop);
  12699. end;
  12700. { Now do the first set of MOVs }
  12701. hp1 := fFirstMovBlock;
  12702. repeat
  12703. if not Assigned(hp1) then
  12704. InternalError(2018062904);
  12705. if (hp1.typ = ait_instruction) then
  12706. begin
  12707. RegMatch := False;
  12708. { Extra safeguard }
  12709. if (taicpu(hp1).opcode <> A_MOV) then
  12710. InternalError(2018062905);
  12711. { Search through the RegWrites list to see if there are any
  12712. opposing CMOV pairs that write to the same register }
  12713. for Count := 0 to Writes - 1 do
  12714. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12715. begin
  12716. { We have a match. Keep this as a MOV }
  12717. { Move ahead in preparation }
  12718. fOptimizer.GetNextInstruction(hp1, hp1);
  12719. RegMatch := True;
  12720. Break;
  12721. end;
  12722. if RegMatch then
  12723. Continue;
  12724. if taicpu(hp1).oper[0]^.typ = top_const then
  12725. begin
  12726. for Count := 0 to ConstCount - 1 do
  12727. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12728. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12729. begin
  12730. RegMatch := True;
  12731. { If it's in RegisterTracking, then this register is
  12732. being used more than once and hence has already had
  12733. its value defined (it gets added to UsedRegs through
  12734. AllocRegBetween below) }
  12735. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12736. begin
  12737. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12738. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12739. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12740. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12741. ConstMovs[Count] := hp_new;
  12742. end
  12743. else
  12744. { We just need an instruction between hp_prev and hp1
  12745. where we know the register is marked as in use }
  12746. hp_new := fFirstMovBlock;
  12747. { Keep track of largest write for this register so it can be optimised later }
  12748. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12749. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12750. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12751. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12752. Break;
  12753. end;
  12754. if not RegMatch then
  12755. InternalError(2021100412);
  12756. end;
  12757. taicpu(hp1).opcode := A_CMOVcc;
  12758. taicpu(hp1).condition := inverted_condition;
  12759. if (fState = tsDoubleBranchDifferent) then
  12760. begin
  12761. { Store these writes to search for duplicates later on }
  12762. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12763. Inc(Writes);
  12764. end;
  12765. end;
  12766. fOptimizer.GetNextInstruction(hp1, hp1);
  12767. until (hp1 = fFirstMovBlockStop);
  12768. { Update initialisation MOVs to the smallest possible size }
  12769. for Count := 0 to ConstCount - 1 do
  12770. if Assigned(ConstMovs[Count]) then
  12771. begin
  12772. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12773. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12774. end;
  12775. case fState of
  12776. tsSimple:
  12777. begin
  12778. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12779. { No branch to delete }
  12780. end;
  12781. tsDetour:
  12782. begin
  12783. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12784. { Preserve jump }
  12785. end;
  12786. tsBranching, tsDoubleBranchDifferent:
  12787. begin
  12788. if (fState = tsBranching) then
  12789. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12790. else
  12791. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12792. taicpu(fSecondJump).opcode := A_JCC;
  12793. taicpu(fSecondJump).condition := inverted_condition;
  12794. end;
  12795. tsDouble, tsDoubleBranchSame:
  12796. begin
  12797. if (fState = tsDouble) then
  12798. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12799. else
  12800. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12801. { Delete second jump }
  12802. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12803. fOptimizer.RemoveInstruction(fSecondJump);
  12804. end;
  12805. tsDoubleSecondBranching:
  12806. begin
  12807. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12808. { Delete second jump, preserve third jump as conditional }
  12809. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12810. fOptimizer.RemoveInstruction(fSecondJump);
  12811. taicpu(fThirdJump).opcode := A_JCC;
  12812. taicpu(fThirdJump).condition := condition;
  12813. end;
  12814. else
  12815. InternalError(2023110720);
  12816. end;
  12817. { Now we can safely decrement the reference count }
  12818. tasmlabel(fLabel).decrefs;
  12819. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12820. { Remove the original jump }
  12821. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12822. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12823. fState := tsProcessed;
  12824. end;
  12825. {$endif 8086}
  12826. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12827. var
  12828. hp1,hp2: tai;
  12829. carryadd_opcode : TAsmOp;
  12830. symbol: TAsmSymbol;
  12831. increg, tmpreg: TRegister;
  12832. {$ifndef i8086}
  12833. CMOVTracking: PCMOVTracking;
  12834. hp3,hp4,hp5: tai;
  12835. {$endif i8086}
  12836. TempBool: Boolean;
  12837. begin
  12838. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12839. DoJumpOptimizations(p, TempBool) then
  12840. Exit(True);
  12841. result:=false;
  12842. if GetNextInstruction(p,hp1) then
  12843. begin
  12844. if (hp1.typ=ait_label) then
  12845. begin
  12846. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12847. Exit;
  12848. end
  12849. else if (hp1.typ<>ait_instruction) then
  12850. Exit;
  12851. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12852. if (
  12853. (
  12854. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12855. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12856. (Taicpu(hp1).oper[0]^.val=1)
  12857. ) or
  12858. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12859. ) and
  12860. GetNextInstruction(hp1,hp2) and
  12861. FindLabel(TAsmLabel(symbol), hp2) then
  12862. { jb @@1 cmc
  12863. inc/dec operand --> adc/sbb operand,0
  12864. @@1:
  12865. ... and ...
  12866. jnb @@1
  12867. inc/dec operand --> adc/sbb operand,0
  12868. @@1: }
  12869. begin
  12870. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12871. begin
  12872. case taicpu(hp1).opcode of
  12873. A_INC,
  12874. A_ADD:
  12875. carryadd_opcode:=A_ADC;
  12876. A_DEC,
  12877. A_SUB:
  12878. carryadd_opcode:=A_SBB;
  12879. else
  12880. InternalError(2021011001);
  12881. end;
  12882. Taicpu(p).clearop(0);
  12883. Taicpu(p).ops:=0;
  12884. Taicpu(p).is_jmp:=false;
  12885. Taicpu(p).opcode:=A_CMC;
  12886. Taicpu(p).condition:=C_NONE;
  12887. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12888. Taicpu(hp1).ops:=2;
  12889. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12890. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12891. else
  12892. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12893. Taicpu(hp1).loadconst(0,0);
  12894. Taicpu(hp1).opcode:=carryadd_opcode;
  12895. result:=true;
  12896. exit;
  12897. end
  12898. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12899. begin
  12900. case taicpu(hp1).opcode of
  12901. A_INC,
  12902. A_ADD:
  12903. carryadd_opcode:=A_ADC;
  12904. A_DEC,
  12905. A_SUB:
  12906. carryadd_opcode:=A_SBB;
  12907. else
  12908. InternalError(2021011002);
  12909. end;
  12910. Taicpu(hp1).ops:=2;
  12911. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12912. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12913. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12914. else
  12915. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12916. Taicpu(hp1).loadconst(0,0);
  12917. Taicpu(hp1).opcode:=carryadd_opcode;
  12918. RemoveCurrentP(p, hp1);
  12919. result:=true;
  12920. exit;
  12921. end
  12922. {
  12923. jcc @@1 setcc tmpreg
  12924. inc/dec/add/sub operand -> (movzx tmpreg)
  12925. @@1: add/sub tmpreg,operand
  12926. While this increases code size slightly, it makes the code much faster if the
  12927. jump is unpredictable
  12928. }
  12929. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12930. begin
  12931. { search for an available register which is volatile }
  12932. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12933. if increg <> NR_NO then
  12934. begin
  12935. { We don't need to check if tmpreg is in hp1 or not, because
  12936. it will be marked as in use at p (if not, this is
  12937. indictive of a compiler bug). }
  12938. TAsmLabel(symbol).decrefs;
  12939. Taicpu(p).clearop(0);
  12940. Taicpu(p).ops:=1;
  12941. Taicpu(p).is_jmp:=false;
  12942. Taicpu(p).opcode:=A_SETcc;
  12943. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12944. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12945. Taicpu(p).loadreg(0,increg);
  12946. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12947. begin
  12948. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12949. R_SUBW:
  12950. begin
  12951. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12952. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12953. end;
  12954. R_SUBD:
  12955. begin
  12956. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12957. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12958. end;
  12959. {$ifdef x86_64}
  12960. R_SUBQ:
  12961. begin
  12962. { MOVZX doesn't have a 64-bit variant, because
  12963. the 32-bit version implicitly zeroes the
  12964. upper 32-bits of the destination register }
  12965. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12966. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12967. setsubreg(tmpreg, R_SUBQ);
  12968. end;
  12969. {$endif x86_64}
  12970. else
  12971. Internalerror(2020030601);
  12972. end;
  12973. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12974. asml.InsertAfter(hp2,p);
  12975. end
  12976. else
  12977. tmpreg := increg;
  12978. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12979. begin
  12980. Taicpu(hp1).ops:=2;
  12981. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12982. end;
  12983. Taicpu(hp1).loadreg(0,tmpreg);
  12984. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12985. Result := True;
  12986. { p is no longer a Jcc instruction, so exit }
  12987. Exit;
  12988. end;
  12989. end;
  12990. end;
  12991. { Detect the following:
  12992. jmp<cond> @Lbl1
  12993. jmp @Lbl2
  12994. ...
  12995. @Lbl1:
  12996. ret
  12997. Change to:
  12998. jmp<inv_cond> @Lbl2
  12999. ret
  13000. }
  13001. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  13002. begin
  13003. hp2:=getlabelwithsym(TAsmLabel(symbol));
  13004. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  13005. MatchInstruction(hp2,A_RET,[S_NO]) then
  13006. begin
  13007. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  13008. { Change label address to that of the unconditional jump }
  13009. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  13010. TAsmLabel(symbol).DecRefs;
  13011. taicpu(hp1).opcode := A_RET;
  13012. taicpu(hp1).is_jmp := false;
  13013. taicpu(hp1).ops := taicpu(hp2).ops;
  13014. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  13015. case taicpu(hp2).ops of
  13016. 0:
  13017. taicpu(hp1).clearop(0);
  13018. 1:
  13019. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  13020. else
  13021. internalerror(2016041302);
  13022. end;
  13023. end;
  13024. {$ifndef i8086}
  13025. end
  13026. {
  13027. convert
  13028. j<c> .L1
  13029. mov 1,reg
  13030. jmp .L2
  13031. .L1
  13032. mov 0,reg
  13033. .L2
  13034. into
  13035. mov 0,reg
  13036. set<not(c)> reg
  13037. take care of alignment and that the mov 0,reg is not converted into a xor as this
  13038. would destroy the flag contents
  13039. }
  13040. else if MatchInstruction(hp1,A_MOV,[]) and
  13041. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13042. {$ifdef i386}
  13043. (
  13044. { Under i386, ESI, EDI, EBP and ESP
  13045. don't have an 8-bit representation }
  13046. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  13047. ) and
  13048. {$endif i386}
  13049. (taicpu(hp1).oper[0]^.val=1) and
  13050. GetNextInstruction(hp1,hp2) and
  13051. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  13052. GetNextInstruction(hp2,hp3) and
  13053. (hp3.typ=ait_label) and
  13054. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  13055. (tai_label(hp3).labsym.getrefs=1) and
  13056. GetNextInstruction(hp3,hp4) and
  13057. MatchInstruction(hp4,A_MOV,[]) and
  13058. MatchOpType(taicpu(hp4),top_const,top_reg) and
  13059. (taicpu(hp4).oper[0]^.val=0) and
  13060. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  13061. GetNextInstruction(hp4,hp5) and
  13062. (hp5.typ=ait_label) and
  13063. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  13064. (tai_label(hp5).labsym.getrefs=1) then
  13065. begin
  13066. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  13067. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  13068. { remove last label }
  13069. RemoveInstruction(hp5);
  13070. { remove second label }
  13071. RemoveInstruction(hp3);
  13072. { remove jmp }
  13073. RemoveInstruction(hp2);
  13074. if taicpu(hp1).opsize=S_B then
  13075. RemoveInstruction(hp1)
  13076. else
  13077. taicpu(hp1).loadconst(0,0);
  13078. taicpu(hp4).opcode:=A_SETcc;
  13079. taicpu(hp4).opsize:=S_B;
  13080. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  13081. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  13082. taicpu(hp4).opercnt:=1;
  13083. taicpu(hp4).ops:=1;
  13084. taicpu(hp4).freeop(1);
  13085. RemoveCurrentP(p);
  13086. Result:=true;
  13087. exit;
  13088. end
  13089. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  13090. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  13091. begin
  13092. { check for
  13093. jCC xxx
  13094. <several movs>
  13095. xxx:
  13096. Also spot:
  13097. Jcc xxx
  13098. <several movs>
  13099. jmp xxx
  13100. Change to:
  13101. <several cmovs with inverted condition>
  13102. jmp xxx (only for the 2nd case)
  13103. }
  13104. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  13105. if CMOVTracking^.State <> tsInvalid then
  13106. begin
  13107. CMovTracking^.Process(p);
  13108. Result := True;
  13109. end;
  13110. CMOVTracking^.Done;
  13111. {$endif i8086}
  13112. end;
  13113. end;
  13114. end;
  13115. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  13116. var
  13117. hp1,hp2,hp3: tai;
  13118. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  13119. NewSize: TOpSize;
  13120. NewRegSize: TSubRegister;
  13121. Limit: TCgInt;
  13122. SwapOper: POper;
  13123. begin
  13124. result:=false;
  13125. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  13126. GetNextInstruction(p,hp1) and
  13127. (hp1.typ = ait_instruction);
  13128. if reg_and_hp1_is_instr and
  13129. (
  13130. (taicpu(hp1).opcode <> A_LEA) or
  13131. { If the LEA instruction can be converted into an arithmetic instruction,
  13132. it may be possible to then fold it. }
  13133. (
  13134. { If the flags register is in use, don't change the instruction
  13135. to an ADD otherwise this will scramble the flags. [Kit] }
  13136. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13137. ConvertLEA(taicpu(hp1))
  13138. )
  13139. ) and
  13140. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  13141. GetNextInstruction(hp1,hp2) and
  13142. MatchInstruction(hp2,A_MOV,[]) and
  13143. (taicpu(hp2).oper[0]^.typ = top_reg) and
  13144. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  13145. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  13146. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  13147. {$ifdef i386}
  13148. { not all registers have byte size sub registers on i386 }
  13149. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  13150. {$endif i386}
  13151. (((taicpu(hp1).ops=2) and
  13152. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  13153. ((taicpu(hp1).ops=1) and
  13154. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  13155. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  13156. begin
  13157. { change movsX/movzX reg/ref, reg2
  13158. add/sub/or/... reg3/$const, reg2
  13159. mov reg2 reg/ref
  13160. to add/sub/or/... reg3/$const, reg/ref }
  13161. { by example:
  13162. movswl %si,%eax movswl %si,%eax p
  13163. decl %eax addl %edx,%eax hp1
  13164. movw %ax,%si movw %ax,%si hp2
  13165. ->
  13166. movswl %si,%eax movswl %si,%eax p
  13167. decw %eax addw %edx,%eax hp1
  13168. movw %ax,%si movw %ax,%si hp2
  13169. }
  13170. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  13171. {
  13172. ->
  13173. movswl %si,%eax movswl %si,%eax p
  13174. decw %si addw %dx,%si hp1
  13175. movw %ax,%si movw %ax,%si hp2
  13176. }
  13177. case taicpu(hp1).ops of
  13178. 1:
  13179. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  13180. 2:
  13181. begin
  13182. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  13183. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  13184. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  13185. end;
  13186. else
  13187. internalerror(2008042702);
  13188. end;
  13189. {
  13190. ->
  13191. decw %si addw %dx,%si p
  13192. }
  13193. DebugMsg(SPeepholeOptimization + 'var3',p);
  13194. RemoveCurrentP(p, hp1);
  13195. RemoveInstruction(hp2);
  13196. Result := True;
  13197. Exit;
  13198. end;
  13199. if reg_and_hp1_is_instr and
  13200. (taicpu(hp1).opcode = A_MOV) and
  13201. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13202. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  13203. {$ifdef x86_64}
  13204. { check for implicit extension to 64 bit }
  13205. or
  13206. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13207. (taicpu(hp1).opsize=S_Q) and
  13208. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  13209. )
  13210. {$endif x86_64}
  13211. )
  13212. then
  13213. begin
  13214. { change
  13215. movx %reg1,%reg2
  13216. mov %reg2,%reg3
  13217. dealloc %reg2
  13218. into
  13219. movx %reg,%reg3
  13220. }
  13221. TransferUsedRegs(TmpUsedRegs);
  13222. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13223. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  13224. begin
  13225. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  13226. {$ifdef x86_64}
  13227. if (taicpu(p).opsize in [S_BL,S_WL]) and
  13228. (taicpu(hp1).opsize=S_Q) then
  13229. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  13230. else
  13231. {$endif x86_64}
  13232. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  13233. RemoveInstruction(hp1);
  13234. Result := True;
  13235. Exit;
  13236. end;
  13237. end;
  13238. if reg_and_hp1_is_instr and
  13239. ((taicpu(hp1).opcode=A_MOV) or
  13240. (taicpu(hp1).opcode=A_ADD) or
  13241. (taicpu(hp1).opcode=A_SUB) or
  13242. (taicpu(hp1).opcode=A_CMP) or
  13243. (taicpu(hp1).opcode=A_OR) or
  13244. (taicpu(hp1).opcode=A_XOR) or
  13245. (taicpu(hp1).opcode=A_AND)
  13246. ) and
  13247. (taicpu(hp1).oper[1]^.typ = top_reg) then
  13248. begin
  13249. AndTest := (taicpu(hp1).opcode=A_AND) and
  13250. GetNextInstruction(hp1, hp2) and
  13251. (hp2.typ = ait_instruction) and
  13252. (
  13253. (
  13254. (taicpu(hp2).opcode=A_TEST) and
  13255. (
  13256. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  13257. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  13258. (
  13259. { If the AND and TEST instructions share a constant, this is also valid }
  13260. (taicpu(hp1).oper[0]^.typ = top_const) and
  13261. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  13262. )
  13263. ) and
  13264. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13265. ) or
  13266. (
  13267. (taicpu(hp2).opcode=A_CMP) and
  13268. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  13269. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13270. )
  13271. );
  13272. { change
  13273. movx (oper),%reg2
  13274. and $x,%reg2
  13275. test %reg2,%reg2
  13276. dealloc %reg2
  13277. into
  13278. op %reg1,%reg3
  13279. if the second op accesses only the bits stored in reg1
  13280. }
  13281. if ((taicpu(p).oper[0]^.typ=top_reg) or
  13282. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  13283. (taicpu(hp1).oper[0]^.typ = top_const) and
  13284. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13285. AndTest then
  13286. begin
  13287. { Check if the AND constant is in range }
  13288. case taicpu(p).opsize of
  13289. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13290. begin
  13291. NewSize := S_B;
  13292. Limit := $FF;
  13293. end;
  13294. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13295. begin
  13296. NewSize := S_W;
  13297. Limit := $FFFF;
  13298. end;
  13299. {$ifdef x86_64}
  13300. S_LQ:
  13301. begin
  13302. NewSize := S_L;
  13303. Limit := $FFFFFFFF;
  13304. end;
  13305. {$endif x86_64}
  13306. else
  13307. InternalError(2021120303);
  13308. end;
  13309. if (
  13310. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  13311. { Check for negative operands }
  13312. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  13313. ) and
  13314. GetNextInstruction(hp2,hp3) and
  13315. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  13316. (taicpu(hp3).condition in [C_E,C_NE]) then
  13317. begin
  13318. TransferUsedRegs(TmpUsedRegs);
  13319. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13320. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13321. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  13322. begin
  13323. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  13324. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13325. taicpu(hp1).opcode := A_TEST;
  13326. taicpu(hp1).opsize := NewSize;
  13327. RemoveInstruction(hp2);
  13328. RemoveCurrentP(p, hp1);
  13329. Result:=true;
  13330. exit;
  13331. end;
  13332. end;
  13333. end;
  13334. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13335. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  13336. (taicpu(hp1).opsize=S_B)) or
  13337. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  13338. (taicpu(hp1).opsize=S_W))
  13339. {$ifdef x86_64}
  13340. or ((taicpu(p).opsize=S_LQ) and
  13341. (taicpu(hp1).opsize=S_L))
  13342. {$endif x86_64}
  13343. ) and
  13344. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  13345. begin
  13346. { change
  13347. movx %reg1,%reg2
  13348. op %reg2,%reg3
  13349. dealloc %reg2
  13350. into
  13351. op %reg1,%reg3
  13352. if the second op accesses only the bits stored in reg1
  13353. }
  13354. TransferUsedRegs(TmpUsedRegs);
  13355. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13356. if AndTest then
  13357. begin
  13358. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13359. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13360. end
  13361. else
  13362. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13363. if not RegUsed then
  13364. begin
  13365. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  13366. if taicpu(p).oper[0]^.typ=top_reg then
  13367. begin
  13368. case taicpu(hp1).opsize of
  13369. S_B:
  13370. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  13371. S_W:
  13372. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  13373. S_L:
  13374. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  13375. else
  13376. Internalerror(2020102301);
  13377. end;
  13378. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  13379. end
  13380. else
  13381. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  13382. RemoveCurrentP(p);
  13383. if AndTest then
  13384. RemoveInstruction(hp2);
  13385. result:=true;
  13386. exit;
  13387. end;
  13388. end
  13389. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13390. (
  13391. { Bitwise operations only }
  13392. (taicpu(hp1).opcode=A_AND) or
  13393. (taicpu(hp1).opcode=A_TEST) or
  13394. (
  13395. (taicpu(hp1).oper[0]^.typ = top_const) and
  13396. (
  13397. (taicpu(hp1).opcode=A_OR) or
  13398. (taicpu(hp1).opcode=A_XOR)
  13399. )
  13400. )
  13401. ) and
  13402. (
  13403. (taicpu(hp1).oper[0]^.typ = top_const) or
  13404. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  13405. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13406. ) then
  13407. begin
  13408. { change
  13409. movx %reg2,%reg2
  13410. op const,%reg2
  13411. into
  13412. op const,%reg2 (smaller version)
  13413. movx %reg2,%reg2
  13414. also change
  13415. movx %reg1,%reg2
  13416. and/test (oper),%reg2
  13417. dealloc %reg2
  13418. into
  13419. and/test (oper),%reg1
  13420. }
  13421. case taicpu(p).opsize of
  13422. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13423. begin
  13424. NewSize := S_B;
  13425. NewRegSize := R_SUBL;
  13426. Limit := $FF;
  13427. end;
  13428. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13429. begin
  13430. NewSize := S_W;
  13431. NewRegSize := R_SUBW;
  13432. Limit := $FFFF;
  13433. end;
  13434. {$ifdef x86_64}
  13435. S_LQ:
  13436. begin
  13437. NewSize := S_L;
  13438. NewRegSize := R_SUBD;
  13439. Limit := $FFFFFFFF;
  13440. end;
  13441. {$endif x86_64}
  13442. else
  13443. Internalerror(2021120302);
  13444. end;
  13445. TransferUsedRegs(TmpUsedRegs);
  13446. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13447. if AndTest then
  13448. begin
  13449. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13450. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13451. end
  13452. else
  13453. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13454. if
  13455. (
  13456. (taicpu(p).opcode = A_MOVZX) and
  13457. (
  13458. (taicpu(hp1).opcode=A_AND) or
  13459. (taicpu(hp1).opcode=A_TEST)
  13460. ) and
  13461. not (
  13462. { If both are references, then the final instruction will have
  13463. both operands as references, which is not allowed }
  13464. (taicpu(p).oper[0]^.typ = top_ref) and
  13465. (taicpu(hp1).oper[0]^.typ = top_ref)
  13466. ) and
  13467. not RegUsed
  13468. ) or
  13469. (
  13470. (
  13471. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13472. not RegUsed
  13473. ) and
  13474. (taicpu(p).oper[0]^.typ = top_reg) and
  13475. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13476. (taicpu(hp1).oper[0]^.typ = top_const) and
  13477. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13478. ) then
  13479. begin
  13480. {$if defined(i386) or defined(i8086)}
  13481. { If the target size is 8-bit, make sure we can actually encode it }
  13482. 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
  13483. Exit;
  13484. {$endif i386 or i8086}
  13485. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13486. taicpu(hp1).opsize := NewSize;
  13487. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13488. if AndTest then
  13489. begin
  13490. RemoveInstruction(hp2);
  13491. if not RegUsed then
  13492. begin
  13493. taicpu(hp1).opcode := A_TEST;
  13494. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13495. begin
  13496. { Make sure the reference is the second operand }
  13497. SwapOper := taicpu(hp1).oper[0];
  13498. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13499. taicpu(hp1).oper[1] := SwapOper;
  13500. end;
  13501. end;
  13502. end;
  13503. case taicpu(hp1).oper[0]^.typ of
  13504. top_reg:
  13505. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13506. top_const:
  13507. { For the AND/TEST case }
  13508. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13509. else
  13510. ;
  13511. end;
  13512. if RegUsed then
  13513. begin
  13514. AsmL.Remove(p);
  13515. AsmL.InsertAfter(p, hp1);
  13516. p := hp1;
  13517. end
  13518. else
  13519. RemoveCurrentP(p, hp1);
  13520. result:=true;
  13521. exit;
  13522. end;
  13523. end;
  13524. end;
  13525. if reg_and_hp1_is_instr and
  13526. (taicpu(p).oper[0]^.typ = top_reg) and
  13527. (
  13528. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13529. ) and
  13530. (taicpu(hp1).oper[0]^.typ = top_const) and
  13531. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13532. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13533. { Minimum shift value allowed is the bit difference between the sizes }
  13534. (taicpu(hp1).oper[0]^.val >=
  13535. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13536. 8 * (
  13537. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13538. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13539. )
  13540. ) then
  13541. begin
  13542. { For:
  13543. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13544. shl/sal ##, %reg1
  13545. Remove the movsx/movzx instruction if the shift overwrites the
  13546. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13547. }
  13548. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13549. RemoveCurrentP(p, hp1);
  13550. Result := True;
  13551. Exit;
  13552. end
  13553. else if reg_and_hp1_is_instr and
  13554. (taicpu(p).oper[0]^.typ = top_reg) and
  13555. (
  13556. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13557. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13558. ) and
  13559. (taicpu(hp1).oper[0]^.typ = top_const) and
  13560. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13561. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13562. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13563. (taicpu(hp1).oper[0]^.val <
  13564. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13565. 8 * (
  13566. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13567. )
  13568. ) then
  13569. begin
  13570. { For:
  13571. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13572. sar ##, %reg1 shr ##, %reg1
  13573. Move the shift to before the movx instruction if the shift value
  13574. is not too large.
  13575. }
  13576. asml.Remove(hp1);
  13577. asml.InsertBefore(hp1, p);
  13578. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13579. case taicpu(p).opsize of
  13580. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13581. taicpu(hp1).opsize := S_B;
  13582. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13583. taicpu(hp1).opsize := S_W;
  13584. {$ifdef x86_64}
  13585. S_LQ:
  13586. taicpu(hp1).opsize := S_L;
  13587. {$endif}
  13588. else
  13589. InternalError(2020112401);
  13590. end;
  13591. if (taicpu(hp1).opcode = A_SHR) then
  13592. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13593. else
  13594. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13595. Result := True;
  13596. end;
  13597. if reg_and_hp1_is_instr and
  13598. (taicpu(p).oper[0]^.typ = top_reg) and
  13599. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13600. (
  13601. (taicpu(hp1).opcode = taicpu(p).opcode)
  13602. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13603. {$ifdef x86_64}
  13604. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13605. {$endif x86_64}
  13606. ) then
  13607. begin
  13608. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13609. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13610. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13611. begin
  13612. {
  13613. For example:
  13614. movzbw %al,%ax
  13615. movzwl %ax,%eax
  13616. Compress into:
  13617. movzbl %al,%eax
  13618. }
  13619. RegUsed := False;
  13620. case taicpu(p).opsize of
  13621. S_BW:
  13622. case taicpu(hp1).opsize of
  13623. S_WL:
  13624. begin
  13625. taicpu(p).opsize := S_BL;
  13626. RegUsed := True;
  13627. end;
  13628. {$ifdef x86_64}
  13629. S_WQ:
  13630. begin
  13631. if taicpu(p).opcode = A_MOVZX then
  13632. begin
  13633. taicpu(p).opsize := S_BL;
  13634. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13635. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13636. end
  13637. else
  13638. taicpu(p).opsize := S_BQ;
  13639. RegUsed := True;
  13640. end;
  13641. {$endif x86_64}
  13642. else
  13643. ;
  13644. end;
  13645. {$ifdef x86_64}
  13646. S_BL:
  13647. case taicpu(hp1).opsize of
  13648. S_LQ:
  13649. begin
  13650. if taicpu(p).opcode = A_MOVZX then
  13651. begin
  13652. taicpu(p).opsize := S_BL;
  13653. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13654. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13655. end
  13656. else
  13657. taicpu(p).opsize := S_BQ;
  13658. RegUsed := True;
  13659. end;
  13660. else
  13661. ;
  13662. end;
  13663. S_WL:
  13664. case taicpu(hp1).opsize of
  13665. S_LQ:
  13666. begin
  13667. if taicpu(p).opcode = A_MOVZX then
  13668. begin
  13669. taicpu(p).opsize := S_WL;
  13670. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13671. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13672. end
  13673. else
  13674. taicpu(p).opsize := S_WQ;
  13675. RegUsed := True;
  13676. end;
  13677. else
  13678. ;
  13679. end;
  13680. {$endif x86_64}
  13681. else
  13682. ;
  13683. end;
  13684. if RegUsed then
  13685. begin
  13686. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13687. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13688. RemoveInstruction(hp1);
  13689. Result := True;
  13690. Exit;
  13691. end;
  13692. end;
  13693. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13694. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13695. GetNextInstruction(hp1, hp2) and
  13696. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13697. (
  13698. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13699. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13700. {$ifdef x86_64}
  13701. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13702. {$endif x86_64}
  13703. ) and
  13704. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13705. (
  13706. (
  13707. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13708. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13709. ) or
  13710. (
  13711. { Only allow the operands in reverse order for TEST instructions }
  13712. (taicpu(hp2).opcode = A_TEST) and
  13713. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13714. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13715. )
  13716. ) then
  13717. begin
  13718. {
  13719. For example:
  13720. movzbl %al,%eax
  13721. movzbl (ref),%edx
  13722. andl %edx,%eax
  13723. (%edx deallocated)
  13724. Change to:
  13725. andb (ref),%al
  13726. movzbl %al,%eax
  13727. Rules are:
  13728. - First two instructions have the same opcode and opsize
  13729. - First instruction's operands are the same super-register
  13730. - Second instruction operates on a different register
  13731. - Third instruction is AND, OR, XOR or TEST
  13732. - Third instruction's operands are the destination registers of the first two instructions
  13733. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13734. - Second instruction's destination register is deallocated afterwards
  13735. }
  13736. TransferUsedRegs(TmpUsedRegs);
  13737. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13738. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13739. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13740. begin
  13741. case taicpu(p).opsize of
  13742. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13743. NewSize := S_B;
  13744. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13745. NewSize := S_W;
  13746. {$ifdef x86_64}
  13747. S_LQ:
  13748. NewSize := S_L;
  13749. {$endif x86_64}
  13750. else
  13751. InternalError(2021120301);
  13752. end;
  13753. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13754. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13755. taicpu(hp2).opsize := NewSize;
  13756. RemoveInstruction(hp1);
  13757. { With TEST, it's best to keep the MOVX instruction at the top }
  13758. if (taicpu(hp2).opcode <> A_TEST) then
  13759. begin
  13760. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13761. asml.Remove(p);
  13762. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13763. asml.InsertAfter(p, hp2);
  13764. p := hp2;
  13765. end
  13766. else
  13767. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13768. Result := True;
  13769. Exit;
  13770. end;
  13771. end;
  13772. end;
  13773. if taicpu(p).opcode=A_MOVZX then
  13774. begin
  13775. { removes superfluous And's after movzx's }
  13776. if reg_and_hp1_is_instr and
  13777. (taicpu(hp1).opcode = A_AND) and
  13778. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13779. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13780. {$ifdef x86_64}
  13781. { check for implicit extension to 64 bit }
  13782. or
  13783. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13784. (taicpu(hp1).opsize=S_Q) and
  13785. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13786. )
  13787. {$endif x86_64}
  13788. )
  13789. then
  13790. begin
  13791. case taicpu(p).opsize Of
  13792. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13793. if (taicpu(hp1).oper[0]^.val = $ff) then
  13794. begin
  13795. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13796. RemoveInstruction(hp1);
  13797. Result:=true;
  13798. exit;
  13799. end;
  13800. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13801. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13802. begin
  13803. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13804. RemoveInstruction(hp1);
  13805. Result:=true;
  13806. exit;
  13807. end;
  13808. {$ifdef x86_64}
  13809. S_LQ:
  13810. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13811. begin
  13812. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13813. RemoveInstruction(hp1);
  13814. Result:=true;
  13815. exit;
  13816. end;
  13817. {$endif x86_64}
  13818. else
  13819. ;
  13820. end;
  13821. { we cannot get rid of the and, but can we get rid of the movz ?}
  13822. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13823. begin
  13824. case taicpu(p).opsize Of
  13825. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13826. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13827. begin
  13828. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13829. RemoveCurrentP(p,hp1);
  13830. Result:=true;
  13831. exit;
  13832. end;
  13833. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13834. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13835. begin
  13836. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13837. RemoveCurrentP(p,hp1);
  13838. Result:=true;
  13839. exit;
  13840. end;
  13841. {$ifdef x86_64}
  13842. S_LQ:
  13843. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13844. begin
  13845. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13846. RemoveCurrentP(p,hp1);
  13847. Result:=true;
  13848. exit;
  13849. end;
  13850. {$endif x86_64}
  13851. else
  13852. ;
  13853. end;
  13854. end;
  13855. end;
  13856. { changes some movzx constructs to faster synonyms (all examples
  13857. are given with eax/ax, but are also valid for other registers)}
  13858. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13859. begin
  13860. case taicpu(p).opsize of
  13861. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13862. (the machine code is equivalent to movzbl %al,%eax), but the
  13863. code generator still generates that assembler instruction and
  13864. it is silently converted. This should probably be checked.
  13865. [Kit] }
  13866. S_BW:
  13867. begin
  13868. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13869. (
  13870. not IsMOVZXAcceptable
  13871. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13872. or (
  13873. (cs_opt_size in current_settings.optimizerswitches) and
  13874. (taicpu(p).oper[1]^.reg = NR_AX)
  13875. )
  13876. ) then
  13877. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13878. begin
  13879. DebugMsg(SPeepholeOptimization + 'var7',p);
  13880. taicpu(p).opcode := A_AND;
  13881. taicpu(p).changeopsize(S_W);
  13882. taicpu(p).loadConst(0,$ff);
  13883. Result := True;
  13884. end
  13885. else if not IsMOVZXAcceptable and
  13886. GetNextInstruction(p, hp1) and
  13887. (tai(hp1).typ = ait_instruction) and
  13888. (taicpu(hp1).opcode = A_AND) and
  13889. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13890. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13891. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13892. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13893. begin
  13894. DebugMsg(SPeepholeOptimization + 'var8',p);
  13895. taicpu(p).opcode := A_MOV;
  13896. taicpu(p).changeopsize(S_W);
  13897. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13898. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13899. Result := True;
  13900. end;
  13901. end;
  13902. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13903. S_BL:
  13904. if not IsMOVZXAcceptable then
  13905. begin
  13906. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13907. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13908. begin
  13909. DebugMsg(SPeepholeOptimization + 'var9',p);
  13910. taicpu(p).opcode := A_AND;
  13911. taicpu(p).changeopsize(S_L);
  13912. taicpu(p).loadConst(0,$ff);
  13913. Result := True;
  13914. end
  13915. else if GetNextInstruction(p, hp1) and
  13916. (tai(hp1).typ = ait_instruction) and
  13917. (taicpu(hp1).opcode = A_AND) and
  13918. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13919. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13920. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13921. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13922. begin
  13923. DebugMsg(SPeepholeOptimization + 'var10',p);
  13924. taicpu(p).opcode := A_MOV;
  13925. taicpu(p).changeopsize(S_L);
  13926. { do not use R_SUBWHOLE
  13927. as movl %rdx,%eax
  13928. is invalid in assembler PM }
  13929. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13930. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13931. Result := True;
  13932. end;
  13933. end;
  13934. {$endif i8086}
  13935. S_WL:
  13936. if not IsMOVZXAcceptable then
  13937. begin
  13938. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13939. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13940. begin
  13941. DebugMsg(SPeepholeOptimization + 'var11',p);
  13942. taicpu(p).opcode := A_AND;
  13943. taicpu(p).changeopsize(S_L);
  13944. taicpu(p).loadConst(0,$ffff);
  13945. Result := True;
  13946. end
  13947. else if GetNextInstruction(p, hp1) and
  13948. (tai(hp1).typ = ait_instruction) and
  13949. (taicpu(hp1).opcode = A_AND) and
  13950. (taicpu(hp1).oper[0]^.typ = top_const) and
  13951. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13952. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13953. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13954. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13955. begin
  13956. DebugMsg(SPeepholeOptimization + 'var12',p);
  13957. taicpu(p).opcode := A_MOV;
  13958. taicpu(p).changeopsize(S_L);
  13959. { do not use R_SUBWHOLE
  13960. as movl %rdx,%eax
  13961. is invalid in assembler PM }
  13962. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13963. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13964. Result := True;
  13965. end;
  13966. end;
  13967. else
  13968. InternalError(2017050705);
  13969. end;
  13970. end
  13971. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13972. begin
  13973. if GetNextInstruction(p, hp1) and
  13974. (tai(hp1).typ = ait_instruction) and
  13975. (taicpu(hp1).opcode = A_AND) and
  13976. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13977. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13978. begin
  13979. case taicpu(p).opsize Of
  13980. S_BL:
  13981. if (taicpu(hp1).opsize <> S_L) or
  13982. (taicpu(hp1).oper[0]^.val > $FF) then
  13983. begin
  13984. DebugMsg(SPeepholeOptimization + 'var13',p);
  13985. taicpu(hp1).changeopsize(S_L);
  13986. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13987. Include(OptsToCheck, aoc_ForceNewIteration);
  13988. end;
  13989. S_WL:
  13990. if (taicpu(hp1).opsize <> S_L) or
  13991. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13992. begin
  13993. DebugMsg(SPeepholeOptimization + 'var14',p);
  13994. taicpu(hp1).changeopsize(S_L);
  13995. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13996. Include(OptsToCheck, aoc_ForceNewIteration);
  13997. end;
  13998. S_BW:
  13999. if (taicpu(hp1).opsize <> S_W) or
  14000. (taicpu(hp1).oper[0]^.val > $FF) then
  14001. begin
  14002. DebugMsg(SPeepholeOptimization + 'var15',p);
  14003. taicpu(hp1).changeopsize(S_W);
  14004. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  14005. Include(OptsToCheck, aoc_ForceNewIteration);
  14006. end;
  14007. else
  14008. Internalerror(2017050704)
  14009. end;
  14010. end;
  14011. end;
  14012. end;
  14013. end;
  14014. {$ifdef x86_64}
  14015. function TX86AsmOptimizer.DoZeroUpper32Opt(var mov_p: tai; var and_p: tai): Boolean;
  14016. var
  14017. hp1, old_hp1: tai;
  14018. FullSourceReg, FullTargetReg: TRegister;
  14019. begin
  14020. if (mov_p.typ<>ait_instruction) or
  14021. (taicpu(mov_p).opsize<>S_L) or
  14022. not MatchOpType(taicpu(mov_p),top_reg,top_reg) then
  14023. InternalError(2025062801);
  14024. Result:=False;
  14025. FullSourceReg:=taicpu(mov_p).oper[0]^.reg; setsubreg(FullSourceReg, R_SUBQ);
  14026. FullTargetReg:=taicpu(mov_p).oper[1]^.reg; setsubreg(FullTargetReg, R_SUBQ);
  14027. { Mark the registers in the MOV command as "used" }
  14028. IncludeRegInUsedRegs(FullSourceReg,UsedRegs);
  14029. IncludeRegInUsedRegs(FullTargetReg,UsedRegs);
  14030. { This is a little hack to get DeepMOVOpt to replace the full 64-bit
  14031. registers. The MOV instruction will be put back as it was afterwards
  14032. (unless it got removed). }
  14033. taicpu(mov_p).oper[0]^.reg:=FullSourceReg;
  14034. taicpu(mov_p).oper[1]^.reg:=FullTargetReg;
  14035. { Start after the and_p otherwise that instruction will be considered
  14036. to have modified the source register }
  14037. old_hp1:=and_p;
  14038. while GetNextInstructionUsingReg(old_hp1,hp1,FullTargetReg) and
  14039. (hp1.typ=ait_instruction) do
  14040. begin
  14041. if RegReadByInstruction(FullTargetReg,hp1) and
  14042. not RegModifiedBetween(FullSourceReg,old_hp1,hp1) and
  14043. DeepMOVOpt(taicpu(mov_p),taicpu(hp1)) then
  14044. begin
  14045. { A change has occurred, just not in mov_p }
  14046. Include(OptsToCheck, aoc_ForceNewIteration);
  14047. TransferUsedRegs(TmpUsedRegs);
  14048. UpdateUsedRegsBetween(TmpUsedRegs,tai(mov_p.Next), hp1);
  14049. if not RegUsedAfterInstruction(FullTargetReg,hp1,TmpUsedRegs) and
  14050. { Just in case something didn't get modified (e.g. an
  14051. implicit register) }
  14052. not RegReadByInstruction(FullTargetReg,hp1) then
  14053. begin
  14054. { We can remove the original MOV }
  14055. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3d done',mov_p);
  14056. RemoveCurrentP(mov_p);
  14057. Result := True;
  14058. Exit;
  14059. end;
  14060. end
  14061. else
  14062. Break;
  14063. old_hp1:=hp1;
  14064. end;
  14065. { Put the MOV instruction back as it was }
  14066. setsubreg(taicpu(mov_p).oper[0]^.reg,R_SUBD);
  14067. setsubreg(taicpu(mov_p).oper[1]^.reg,R_SUBD);
  14068. end;
  14069. {$endif x86_64}
  14070. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  14071. var
  14072. hp1, hp2 : tai;
  14073. MaskLength : Cardinal;
  14074. MaskedBits : TCgInt;
  14075. ActiveReg : TRegister;
  14076. begin
  14077. Result:=false;
  14078. { There are no optimisations for reference targets }
  14079. if (taicpu(p).oper[1]^.typ <> top_reg) then
  14080. Exit;
  14081. { Saves on a bunch of dereferences }
  14082. ActiveReg := taicpu(p).oper[1]^.reg;
  14083. while GetNextInstruction(p, hp1) and
  14084. (hp1.typ = ait_instruction) do
  14085. begin
  14086. if (taicpu(p).oper[0]^.typ = top_const) then
  14087. begin
  14088. case taicpu(hp1).opcode of
  14089. A_AND:
  14090. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  14091. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  14092. { the second register must contain the first one, so compare their subreg types }
  14093. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  14094. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  14095. { change
  14096. and const1, reg
  14097. and const2, reg
  14098. to
  14099. and (const1 and const2), reg
  14100. }
  14101. begin
  14102. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  14103. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  14104. RemoveCurrentP(p, hp1);
  14105. Result:=true;
  14106. exit;
  14107. end;
  14108. A_CMP:
  14109. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  14110. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  14111. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  14112. { Just check that the condition on the next instruction is compatible }
  14113. GetNextInstruction(hp1, hp2) and
  14114. (hp2.typ = ait_instruction) and
  14115. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  14116. then
  14117. { change
  14118. and 2^n, reg
  14119. cmp 2^n, reg
  14120. j(c) / set(c) / cmov(c) (c is equal or not equal)
  14121. to
  14122. and 2^n, reg
  14123. test reg, reg
  14124. j(~c) / set(~c) / cmov(~c)
  14125. }
  14126. begin
  14127. { Keep TEST instruction in, rather than remove it, because
  14128. it may trigger other optimisations such as MovAndTest2Test }
  14129. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  14130. taicpu(hp1).opcode := A_TEST;
  14131. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  14132. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  14133. Result := True;
  14134. Exit;
  14135. end
  14136. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  14137. MatchOpType(taicpu(hp1),top_const,top_reg) and
  14138. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  14139. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  14140. { change
  14141. and $ff/$ff/$ffff, reg
  14142. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  14143. dealloc reg
  14144. to
  14145. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  14146. }
  14147. begin
  14148. TransferUsedRegs(TmpUsedRegs);
  14149. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14150. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  14151. begin
  14152. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  14153. case taicpu(p).oper[0]^.val of
  14154. $ff:
  14155. begin
  14156. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  14157. taicpu(hp1).opsize:=S_B;
  14158. end;
  14159. $ffff:
  14160. begin
  14161. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  14162. taicpu(hp1).opsize:=S_W;
  14163. end;
  14164. $ffffffff:
  14165. begin
  14166. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  14167. taicpu(hp1).opsize:=S_L;
  14168. end;
  14169. else
  14170. Internalerror(2023030401);
  14171. end;
  14172. RemoveCurrentP(p);
  14173. Result := True;
  14174. Exit;
  14175. end;
  14176. end;
  14177. A_MOVZX:
  14178. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  14179. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  14180. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  14181. (
  14182. (
  14183. (taicpu(p).opsize=S_W) and
  14184. (taicpu(hp1).opsize=S_BW)
  14185. ) or
  14186. (
  14187. (taicpu(p).opsize=S_L) and
  14188. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  14189. )
  14190. {$ifdef x86_64}
  14191. or
  14192. (
  14193. (taicpu(p).opsize=S_Q) and
  14194. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  14195. )
  14196. {$endif x86_64}
  14197. ) then
  14198. begin
  14199. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  14200. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  14201. ) or
  14202. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  14203. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  14204. then
  14205. begin
  14206. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  14207. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  14208. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  14209. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  14210. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  14211. }
  14212. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  14213. RemoveInstruction(hp1);
  14214. { See if there are other optimisations possible }
  14215. Continue;
  14216. end;
  14217. end;
  14218. A_SHL:
  14219. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  14220. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  14221. begin
  14222. {$ifopt R+}
  14223. {$define RANGE_WAS_ON}
  14224. {$R-}
  14225. {$endif}
  14226. { get length of potential and mask }
  14227. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  14228. { really a mask? }
  14229. {$ifdef RANGE_WAS_ON}
  14230. {$R+}
  14231. {$endif}
  14232. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  14233. { unmasked part shifted out? }
  14234. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  14235. begin
  14236. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  14237. RemoveCurrentP(p, hp1);
  14238. Result:=true;
  14239. exit;
  14240. end;
  14241. end;
  14242. A_SHR:
  14243. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  14244. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  14245. (taicpu(hp1).oper[0]^.val <= 63) then
  14246. begin
  14247. { Does SHR combined with the AND cover all the bits?
  14248. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  14249. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  14250. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  14251. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  14252. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  14253. begin
  14254. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  14255. RemoveCurrentP(p, hp1);
  14256. Result := True;
  14257. Exit;
  14258. end;
  14259. end;
  14260. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14261. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  14262. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14263. begin
  14264. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14265. (
  14266. (
  14267. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  14268. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  14269. ) or (
  14270. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  14271. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  14272. {$ifdef x86_64}
  14273. ) or (
  14274. (taicpu(hp1).opsize = S_LQ) and
  14275. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  14276. {$endif x86_64}
  14277. )
  14278. ) then
  14279. begin
  14280. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  14281. begin
  14282. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  14283. RemoveInstruction(hp1);
  14284. { See if there are other optimisations possible }
  14285. Continue;
  14286. end;
  14287. { The super-registers are the same though.
  14288. Note that this change by itself doesn't improve
  14289. code speed, but it opens up other optimisations. }
  14290. {$ifdef x86_64}
  14291. { Convert 64-bit register to 32-bit }
  14292. case taicpu(hp1).opsize of
  14293. S_BQ:
  14294. begin
  14295. taicpu(hp1).opsize := S_BL;
  14296. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14297. end;
  14298. S_WQ:
  14299. begin
  14300. taicpu(hp1).opsize := S_WL;
  14301. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14302. end
  14303. else
  14304. ;
  14305. end;
  14306. {$endif x86_64}
  14307. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  14308. taicpu(hp1).opcode := A_MOVZX;
  14309. { See if there are other optimisations possible }
  14310. Continue;
  14311. end;
  14312. end;
  14313. else
  14314. ;
  14315. end;
  14316. end
  14317. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  14318. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14319. begin
  14320. {$ifdef x86_64}
  14321. if (taicpu(p).opsize = S_Q) then
  14322. begin
  14323. { Never necessary }
  14324. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  14325. RemoveCurrentP(p, hp1);
  14326. Result := True;
  14327. Exit;
  14328. end;
  14329. {$endif x86_64}
  14330. { Forward check to determine necessity of and %reg,%reg }
  14331. TransferUsedRegs(TmpUsedRegs);
  14332. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14333. case taicpu(hp1).opcode of
  14334. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14335. if (
  14336. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14337. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14338. ) and
  14339. (
  14340. (taicpu(hp1).opcode <> A_MOV) or
  14341. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  14342. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  14343. ) and
  14344. not (
  14345. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  14346. (taicpu(hp1).opcode = A_MOV) and
  14347. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  14348. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  14349. ) and
  14350. (
  14351. (
  14352. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14353. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  14354. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  14355. ) or
  14356. (
  14357. {$ifdef x86_64}
  14358. (
  14359. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  14360. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  14361. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  14362. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  14363. ) and
  14364. {$endif x86_64}
  14365. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  14366. )
  14367. ) then
  14368. begin
  14369. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  14370. RemoveCurrentP(p, hp1);
  14371. Result := True;
  14372. Exit;
  14373. end;
  14374. A_ADD,
  14375. A_AND,
  14376. A_BSF,
  14377. A_BSR,
  14378. A_BTC,
  14379. A_BTR,
  14380. A_BTS,
  14381. A_OR,
  14382. A_SUB,
  14383. A_XOR:
  14384. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  14385. if (
  14386. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14387. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14388. ) and
  14389. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  14390. begin
  14391. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  14392. RemoveCurrentP(p, hp1);
  14393. Result := True;
  14394. Exit;
  14395. end;
  14396. A_CMP,
  14397. A_TEST:
  14398. if (
  14399. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14400. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14401. ) and
  14402. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  14403. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  14404. begin
  14405. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  14406. RemoveCurrentP(p, hp1);
  14407. Result := True;
  14408. Exit;
  14409. end;
  14410. A_BSWAP,
  14411. A_NEG,
  14412. A_NOT:
  14413. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  14414. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  14415. begin
  14416. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  14417. RemoveCurrentP(p, hp1);
  14418. Result := True;
  14419. Exit;
  14420. end;
  14421. else
  14422. ;
  14423. end;
  14424. end;
  14425. if (taicpu(hp1).is_jmp) and
  14426. (taicpu(hp1).opcode<>A_JMP) and
  14427. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  14428. begin
  14429. { change
  14430. and x, reg
  14431. jxx
  14432. to
  14433. test x, reg
  14434. jxx
  14435. if reg is deallocated before the
  14436. jump, but only if it's a conditional jump (PFV)
  14437. }
  14438. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  14439. taicpu(p).opcode := A_TEST;
  14440. Exit;
  14441. end;
  14442. Break;
  14443. end;
  14444. { Lone AND tests }
  14445. if (taicpu(p).oper[0]^.typ = top_const) then
  14446. begin
  14447. {
  14448. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  14449. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  14450. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  14451. }
  14452. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  14453. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  14454. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  14455. begin
  14456. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  14457. if taicpu(p).opsize = S_L then
  14458. begin
  14459. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  14460. Result := True;
  14461. end;
  14462. end;
  14463. end;
  14464. { Backward check to determine necessity of and %reg,%reg }
  14465. if (taicpu(p).oper[0]^.typ = top_reg) and
  14466. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  14467. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14468. begin
  14469. hp2:=p;
  14470. while GetLastInstruction(hp2, hp2) and
  14471. (cs_opt_level3 in current_settings.optimizerswitches) and
  14472. (hp2.typ=ait_instruction) and
  14473. not RegModifiedByInstruction(ActiveReg,hp2) do { loop };
  14474. if Assigned(hp2) and
  14475. RegModifiedByInstruction(ActiveReg,hp2) and { Also checks if hp2 is an instruction }
  14476. { Check size of instruction to determine if the AND is effectively
  14477. a null operation }
  14478. (
  14479. (taicpu(p).opsize = taicpu(hp2).opsize) or
  14480. { Note: Don't include S_Q }
  14481. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  14482. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  14483. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  14484. ) then
  14485. begin
  14486. { AND %reg,%reg is unnecessary to zero the upper 32 bits. }
  14487. DebugMsg(SPeepholeOptimization + 'AND %reg,%reg proven unnecessary after backward search (And2Nop)', p);
  14488. RemoveCurrentP(p, hp1);
  14489. Result:=True;
  14490. Exit;
  14491. end;
  14492. end;
  14493. end;
  14494. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14495. var
  14496. hp1, hp2: tai;
  14497. NewRef: TReference;
  14498. Distance: Cardinal;
  14499. TempTracking: TAllUsedRegs;
  14500. DoAddMov2Lea: Boolean;
  14501. { This entire nested function is used in an if-statement below, but we
  14502. want to avoid all the used reg transfers and GetNextInstruction calls
  14503. until we really have to check }
  14504. function MemRegisterNotUsedLater: Boolean; inline;
  14505. var
  14506. hp2: tai;
  14507. begin
  14508. TransferUsedRegs(TmpUsedRegs);
  14509. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14510. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14511. else
  14512. { p and hp1 will be adjacent }
  14513. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14514. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14515. end;
  14516. begin
  14517. Result := False;
  14518. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14519. (taicpu(p).oper[1]^.typ = top_reg) then
  14520. begin
  14521. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14522. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14523. (hp1.typ <> ait_instruction) or
  14524. not
  14525. (
  14526. (cs_opt_level3 in current_settings.optimizerswitches) or
  14527. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14528. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14529. ) then
  14530. Exit;
  14531. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14532. addq $x, %rax
  14533. movq %rax, %rdx
  14534. sarq $63, %rdx
  14535. (%rax still in use)
  14536. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14537. leaq $x(%rax),%rdx
  14538. addq $x, %rax
  14539. sarq $63, %rdx
  14540. ...which is okay since it breaks the dependency chain between
  14541. addq and movq, but if OptPass2MOV is called first:
  14542. addq $x, %rax
  14543. cqto
  14544. ...which is better in all ways, taking only 2 cycles to execute
  14545. and much smaller in code size.
  14546. }
  14547. { The extra register tracking is quite strenuous }
  14548. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14549. MatchInstruction(hp1, A_MOV, []) then
  14550. begin
  14551. { Update the register tracking to the MOV instruction }
  14552. CopyUsedRegs(TempTracking);
  14553. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14554. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14555. else
  14556. { p and hp1 will be adjacent }
  14557. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14558. hp2 := hp1;
  14559. if OptPass2MOV(hp1) then
  14560. Include(OptsToCheck, aoc_ForceNewIteration);
  14561. { Reset the tracking to the current instruction }
  14562. RestoreUsedRegs(TempTracking);
  14563. ReleaseUsedRegs(TempTracking);
  14564. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14565. OptPass2ADD get called again }
  14566. if (hp1 <> hp2) then
  14567. begin
  14568. Result := True;
  14569. Exit;
  14570. end;
  14571. end;
  14572. { Change:
  14573. add %reg2,%reg1
  14574. (%reg2 not modified in between)
  14575. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14576. To:
  14577. mov/s/z #(%reg1,%reg2),%reg1
  14578. }
  14579. if (taicpu(p).oper[0]^.typ = top_reg) and
  14580. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14581. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14582. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14583. (
  14584. (
  14585. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14586. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14587. { r/esp cannot be an index }
  14588. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14589. ) or (
  14590. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14591. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14592. )
  14593. ) and (
  14594. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14595. (
  14596. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14597. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14598. MemRegisterNotUsedLater
  14599. )
  14600. ) then
  14601. begin
  14602. if (
  14603. { Instructions are guaranteed to be adjacent on -O2 and under }
  14604. (cs_opt_level3 in current_settings.optimizerswitches) and
  14605. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14606. ) then
  14607. begin
  14608. { If the other register is used in between, move the MOV
  14609. instruction to right after the ADD instruction so a
  14610. saving can still be made }
  14611. Asml.Remove(hp1);
  14612. Asml.InsertAfter(hp1, p);
  14613. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14614. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14615. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14616. RemoveCurrentp(p, hp1);
  14617. end
  14618. else
  14619. begin
  14620. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14621. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14622. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14623. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14624. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14625. { hp1 may not be the immediate next instruction under -O3 }
  14626. RemoveCurrentp(p)
  14627. else
  14628. RemoveCurrentp(p, hp1);
  14629. end;
  14630. Result := True;
  14631. Exit;
  14632. end;
  14633. { Change:
  14634. addl/q $x,%reg1
  14635. movl/q %reg1,%reg2
  14636. To:
  14637. leal/q $x(%reg1),%reg2
  14638. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14639. Breaks the dependency chain.
  14640. }
  14641. if (taicpu(p).oper[0]^.typ = top_const) and
  14642. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14643. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14644. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14645. (
  14646. { Instructions are guaranteed to be adjacent on -O2 and under }
  14647. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14648. (
  14649. { If the flags are used, don't make the optimisation,
  14650. otherwise they will be scrambled. Fixes #41148 }
  14651. (
  14652. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14653. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14654. ) and
  14655. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14656. )
  14657. ) then
  14658. begin
  14659. TransferUsedRegs(TmpUsedRegs);
  14660. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14661. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14662. else
  14663. { p and hp1 will be adjacent }
  14664. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14665. if (
  14666. SetAndTest(
  14667. (
  14668. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14669. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14670. ),
  14671. DoAddMov2Lea
  14672. ) or
  14673. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14674. not (cs_opt_size in current_settings.optimizerswitches)
  14675. ) then
  14676. begin
  14677. { Change the MOV instruction to a LEA instruction, and update the
  14678. first operand }
  14679. reference_reset(NewRef, 1, []);
  14680. NewRef.base := taicpu(p).oper[1]^.reg;
  14681. NewRef.scalefactor := 1;
  14682. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14683. taicpu(hp1).opcode := A_LEA;
  14684. taicpu(hp1).loadref(0, NewRef);
  14685. if DoAddMov2Lea then
  14686. begin
  14687. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14688. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14689. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14690. { hp1 may not be the immediate next instruction under -O3 }
  14691. RemoveCurrentp(p)
  14692. else
  14693. RemoveCurrentp(p, hp1);
  14694. end
  14695. else
  14696. begin
  14697. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14698. { Move what is now the LEA instruction to before the ADD instruction }
  14699. Asml.Remove(hp1);
  14700. Asml.InsertBefore(hp1, p);
  14701. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14702. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14703. p := hp1;
  14704. end;
  14705. Result := True;
  14706. end;
  14707. end;
  14708. end;
  14709. end;
  14710. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14711. var
  14712. SubReg: TSubRegister;
  14713. hp1, hp2: tai;
  14714. CallJmp: Boolean;
  14715. begin
  14716. Result := False;
  14717. CallJmp := False;
  14718. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14719. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14720. with taicpu(p).oper[0]^.ref^ do
  14721. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14722. if (offset = 0) then
  14723. begin
  14724. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14725. begin
  14726. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14727. taicpu(p).opcode := A_ADD;
  14728. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14729. Result := True;
  14730. end
  14731. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14732. begin
  14733. if (base <> NR_NO) then
  14734. begin
  14735. if (scalefactor <= 1) then
  14736. begin
  14737. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14738. taicpu(p).opcode := A_ADD;
  14739. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14740. Result := True;
  14741. end;
  14742. end
  14743. else
  14744. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14745. if (scalefactor in [2, 4, 8]) then
  14746. begin
  14747. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14748. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14749. taicpu(p).opcode := A_SHL;
  14750. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14751. Result := True;
  14752. end;
  14753. end;
  14754. end
  14755. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14756. lot of latency, so break off the offset if %reg3 is used soon
  14757. afterwards }
  14758. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14759. { If 3-component addresses don't have additional latency, don't
  14760. perform this optimisation }
  14761. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14762. GetNextInstruction(p, hp1) and
  14763. (hp1.typ = ait_instruction) and
  14764. (
  14765. (
  14766. { Permit jumps and calls since they have a larger degree of overhead }
  14767. (
  14768. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14769. (
  14770. { ... unless the register specifies the location }
  14771. (taicpu(hp1).ops > 0) and
  14772. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14773. )
  14774. ) and
  14775. (
  14776. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14777. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14778. )
  14779. )
  14780. or
  14781. (
  14782. { Check up to two instructions ahead }
  14783. GetNextInstruction(hp1, hp2) and
  14784. (hp2.typ = ait_instruction) and
  14785. (
  14786. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14787. (
  14788. { Same as above }
  14789. (taicpu(hp2).ops > 0) and
  14790. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14791. )
  14792. ) and
  14793. (
  14794. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14795. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14796. )
  14797. )
  14798. ) then
  14799. begin
  14800. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14801. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14802. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14803. offset := 0;
  14804. if Assigned(symbol) or Assigned(relsymbol) then
  14805. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14806. else
  14807. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14808. { Inserting before the next instruction rather than after the
  14809. current instruction gives more accurate register tracking }
  14810. asml.InsertBefore(hp2, hp1);
  14811. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14812. Result := True;
  14813. end;
  14814. end;
  14815. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14816. var
  14817. hp1, hp2: tai;
  14818. NewRef: TReference;
  14819. Distance: Cardinal;
  14820. TempTracking: TAllUsedRegs;
  14821. DoSubMov2Lea: Boolean;
  14822. begin
  14823. Result := False;
  14824. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14825. MatchOpType(taicpu(p),top_const,top_reg) then
  14826. begin
  14827. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14828. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14829. (hp1.typ <> ait_instruction) or
  14830. not
  14831. (
  14832. (cs_opt_level3 in current_settings.optimizerswitches) or
  14833. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14834. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14835. ) then
  14836. Exit;
  14837. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14838. subq $x, %rax
  14839. movq %rax, %rdx
  14840. sarq $63, %rdx
  14841. (%rax still in use)
  14842. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14843. leaq $-x(%rax),%rdx
  14844. movq $x, %rax
  14845. sarq $63, %rdx
  14846. ...which is okay since it breaks the dependency chain between
  14847. subq and movq, but if OptPass2MOV is called first:
  14848. subq $x, %rax
  14849. cqto
  14850. ...which is better in all ways, taking only 2 cycles to execute
  14851. and much smaller in code size.
  14852. }
  14853. { The extra register tracking is quite strenuous }
  14854. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14855. MatchInstruction(hp1, A_MOV, []) then
  14856. begin
  14857. { Update the register tracking to the MOV instruction }
  14858. CopyUsedRegs(TempTracking);
  14859. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14860. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14861. else
  14862. { p and hp1 will be adjacent }
  14863. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14864. hp2 := hp1;
  14865. if OptPass2MOV(hp1) then
  14866. Include(OptsToCheck, aoc_ForceNewIteration);
  14867. { Reset the tracking to the current instruction }
  14868. RestoreUsedRegs(TempTracking);
  14869. ReleaseUsedRegs(TempTracking);
  14870. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14871. OptPass2SUB get called again }
  14872. if (hp1 <> hp2) then
  14873. begin
  14874. Result := True;
  14875. Exit;
  14876. end;
  14877. end;
  14878. { Change:
  14879. subl/q $x,%reg1
  14880. movl/q %reg1,%reg2
  14881. To:
  14882. leal/q $-x(%reg1),%reg2
  14883. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14884. Breaks the dependency chain and potentially permits the removal of
  14885. a CMP instruction if one follows.
  14886. }
  14887. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14888. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14889. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14890. (
  14891. { Instructions are guaranteed to be adjacent on -O2 and under }
  14892. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14893. (
  14894. { If the flags are used, don't make the optimisation,
  14895. otherwise they will be scrambled. Fixes #41148 }
  14896. (
  14897. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14898. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14899. ) and
  14900. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14901. )
  14902. ) then
  14903. begin
  14904. TransferUsedRegs(TmpUsedRegs);
  14905. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14906. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14907. else
  14908. { p and hp1 will be adjacent }
  14909. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14910. if (
  14911. SetAndTest(
  14912. (
  14913. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14914. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14915. ),
  14916. DoSubMov2Lea
  14917. ) or
  14918. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14919. not (cs_opt_size in current_settings.optimizerswitches)
  14920. ) then
  14921. begin
  14922. { Change the MOV instruction to a LEA instruction, and update the
  14923. first operand }
  14924. reference_reset(NewRef, 1, []);
  14925. NewRef.base := taicpu(p).oper[1]^.reg;
  14926. NewRef.scalefactor := 1;
  14927. NewRef.offset := -taicpu(p).oper[0]^.val;
  14928. taicpu(hp1).opcode := A_LEA;
  14929. taicpu(hp1).loadref(0, NewRef);
  14930. if DoSubMov2Lea then
  14931. begin
  14932. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14933. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14934. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14935. { hp1 may not be the immediate next instruction under -O3 }
  14936. RemoveCurrentp(p)
  14937. else
  14938. RemoveCurrentp(p, hp1);
  14939. end
  14940. else
  14941. begin
  14942. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14943. { Move what is now the LEA instruction to before the SUB instruction }
  14944. Asml.Remove(hp1);
  14945. Asml.InsertBefore(hp1, p);
  14946. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14947. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14948. p := hp1;
  14949. end;
  14950. Result := True;
  14951. end;
  14952. end;
  14953. end;
  14954. end;
  14955. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14956. begin
  14957. { we can skip all instructions not messing with the stack pointer }
  14958. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14959. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14960. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14961. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14962. ({(taicpu(hp1).ops=0) or }
  14963. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14964. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14965. ) and }
  14966. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14967. )
  14968. ) do
  14969. GetNextInstruction(hp1,hp1);
  14970. Result:=assigned(hp1);
  14971. end;
  14972. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14973. var
  14974. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14975. begin
  14976. Result:=false;
  14977. {$ifdef x86_64}
  14978. { Change:
  14979. lea x(%reg1d,%reg2d),%reg3d
  14980. To:
  14981. lea x(%reg1q,%reg2q),%reg3d
  14982. Reduces the number of bytes of machine code
  14983. }
  14984. if (getsubreg(taicpu(p).oper[1]^.reg)=R_SUBD) and
  14985. (
  14986. (getsubreg(taicpu(p).oper[0]^.ref^.base)=R_SUBD) or
  14987. (getsubreg(taicpu(p).oper[0]^.ref^.index)=R_SUBD)
  14988. ) then
  14989. begin
  14990. DebugMsg(SPeepholeOptimization + 'Changed 32-bit registers in reference to 64-bit (reduces instruction size)', p);
  14991. if (getsubreg(taicpu(p).oper[0]^.ref^.base)=R_SUBD) then
  14992. setsubreg(taicpu(p).oper[0]^.ref^.base,R_SUBQ);
  14993. if (getsubreg(taicpu(p).oper[0]^.ref^.index)=R_SUBD) then
  14994. setsubreg(taicpu(p).oper[0]^.ref^.index,R_SUBQ);
  14995. { No reason to set Result to true }
  14996. end;
  14997. {$endif x86_64}
  14998. hp5:=nil;
  14999. hp6:=nil;
  15000. hp7:=nil;
  15001. hp8:=nil;
  15002. { replace
  15003. leal(q) x(<stackpointer>),<stackpointer>
  15004. <optional .seh_stackalloc ...>
  15005. <optional .seh_endprologue ...>
  15006. call procname
  15007. <optional NOP>
  15008. leal(q) -x(<stackpointer>),<stackpointer>
  15009. <optional VZEROUPPER>
  15010. ret
  15011. by
  15012. jmp procname
  15013. but do it only on level 4 because it destroys stack back traces
  15014. }
  15015. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15016. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  15017. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  15018. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  15019. { the -8, -24, -40 are not required, but bail out early if possible,
  15020. higher values are unlikely }
  15021. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  15022. (taicpu(p).oper[0]^.ref^.offset=-24) or
  15023. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  15024. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  15025. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  15026. GetNextInstruction(p, hp1) and
  15027. { Take a copy of hp1 }
  15028. SetAndTest(hp1, hp4) and
  15029. { trick to skip label }
  15030. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  15031. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  15032. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  15033. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  15034. SkipSimpleInstructions(hp1) and
  15035. MatchInstruction(hp1,A_CALL,[S_NO]) and
  15036. GetNextInstruction(hp1, hp2) and
  15037. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  15038. { skip nop instruction on win64 }
  15039. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  15040. SetAndTest(hp2,hp6) and
  15041. GetNextInstruction(hp2,hp2) and
  15042. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  15043. ) and
  15044. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  15045. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  15046. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  15047. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  15048. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  15049. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  15050. { Segment register will be NR_NO }
  15051. GetNextInstruction(hp2, hp3) and
  15052. { trick to skip label }
  15053. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  15054. (MatchInstruction(hp3,A_RET,[S_NO]) or
  15055. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  15056. SetAndTest(hp3,hp5) and
  15057. GetNextInstruction(hp3,hp3) and
  15058. MatchInstruction(hp3,A_RET,[S_NO])
  15059. )
  15060. ) and
  15061. (taicpu(hp3).ops=0) then
  15062. begin
  15063. taicpu(hp1).opcode := A_JMP;
  15064. taicpu(hp1).is_jmp := true;
  15065. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  15066. { search for the stackalloc directive and remove it }
  15067. hp7:=tai(p.next);
  15068. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  15069. begin
  15070. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  15071. begin
  15072. { sanity check }
  15073. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  15074. Internalerror(2024012201);
  15075. hp8:=tai(hp7.next);
  15076. RemoveInstruction(tai(hp7));
  15077. hp7:=hp8;
  15078. break;
  15079. end
  15080. else
  15081. hp7:=tai(hp7.next);
  15082. end;
  15083. RemoveCurrentP(p, hp4);
  15084. RemoveInstruction(hp2);
  15085. RemoveInstruction(hp3);
  15086. { if there is a vzeroupper instruction then move it before the jmp }
  15087. if Assigned(hp5) then
  15088. begin
  15089. AsmL.Remove(hp5);
  15090. ASmL.InsertBefore(hp5,hp1)
  15091. end;
  15092. { remove nop on win64 }
  15093. if Assigned(hp6) then
  15094. RemoveInstruction(hp6);
  15095. Result:=true;
  15096. end;
  15097. end;
  15098. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  15099. {$ifdef x86_64}
  15100. var
  15101. hp1, hp2, hp3, hp4, hp5: tai;
  15102. {$endif x86_64}
  15103. begin
  15104. Result:=false;
  15105. {$ifdef x86_64}
  15106. hp5:=nil;
  15107. { replace
  15108. push %rax
  15109. call procname
  15110. pop %rcx
  15111. ret
  15112. by
  15113. jmp procname
  15114. but do it only on level 4 because it destroys stack back traces
  15115. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  15116. for all supported calling conventions
  15117. }
  15118. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15119. MatchOpType(taicpu(p),top_reg) and
  15120. (taicpu(p).oper[0]^.reg=NR_RAX) and
  15121. GetNextInstruction(p, hp1) and
  15122. { Take a copy of hp1 }
  15123. SetAndTest(hp1, hp4) and
  15124. { trick to skip label }
  15125. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  15126. SkipSimpleInstructions(hp1) and
  15127. MatchInstruction(hp1,A_CALL,[S_NO]) and
  15128. GetNextInstruction(hp1, hp2) and
  15129. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  15130. MatchOpType(taicpu(hp2),top_reg) and
  15131. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  15132. GetNextInstruction(hp2, hp3) and
  15133. { trick to skip label }
  15134. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  15135. (MatchInstruction(hp3,A_RET,[S_NO]) or
  15136. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  15137. SetAndTest(hp3,hp5) and
  15138. GetNextInstruction(hp3,hp3) and
  15139. MatchInstruction(hp3,A_RET,[S_NO])
  15140. )
  15141. ) and
  15142. (taicpu(hp3).ops=0) then
  15143. begin
  15144. taicpu(hp1).opcode := A_JMP;
  15145. taicpu(hp1).is_jmp := true;
  15146. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  15147. RemoveCurrentP(p, hp4);
  15148. RemoveInstruction(hp2);
  15149. RemoveInstruction(hp3);
  15150. if Assigned(hp5) then
  15151. begin
  15152. AsmL.Remove(hp5);
  15153. ASmL.InsertBefore(hp5,hp1)
  15154. end;
  15155. Result:=true;
  15156. end;
  15157. {$endif x86_64}
  15158. end;
  15159. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  15160. var
  15161. Value, RegName: string;
  15162. hp1: tai;
  15163. begin
  15164. Result:=false;
  15165. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  15166. begin
  15167. case taicpu(p).oper[0]^.val of
  15168. 0:
  15169. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  15170. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  15171. (
  15172. { See if we can still convert the instruction }
  15173. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  15174. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  15175. ) then
  15176. begin
  15177. { change "mov $0,%reg" into "xor %reg,%reg" }
  15178. taicpu(p).opcode := A_XOR;
  15179. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  15180. Result := True;
  15181. {$ifdef x86_64}
  15182. end
  15183. else if (taicpu(p).opsize = S_Q) then
  15184. begin
  15185. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  15186. { The actual optimization }
  15187. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15188. taicpu(p).changeopsize(S_L);
  15189. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  15190. Result := True;
  15191. end;
  15192. $1..$FFFFFFFF:
  15193. begin
  15194. { Code size reduction by J. Gareth "Kit" Moreton }
  15195. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  15196. case taicpu(p).opsize of
  15197. S_Q:
  15198. begin
  15199. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  15200. Value := debug_tostr(taicpu(p).oper[0]^.val);
  15201. { The actual optimization }
  15202. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15203. taicpu(p).changeopsize(S_L);
  15204. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  15205. Result := True;
  15206. end;
  15207. else
  15208. { Do nothing };
  15209. end;
  15210. {$endif x86_64}
  15211. end;
  15212. -1:
  15213. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  15214. if (cs_opt_size in current_settings.optimizerswitches) and
  15215. (taicpu(p).opsize <> S_B) and
  15216. (
  15217. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  15218. (
  15219. { See if we can still convert the instruction }
  15220. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  15221. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  15222. )
  15223. ) then
  15224. begin
  15225. { change "mov $-1,%reg" into "or $-1,%reg" }
  15226. { NOTES:
  15227. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  15228. - This operation creates a false dependency on the register, so only do it when optimising for size
  15229. - 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
  15230. }
  15231. taicpu(p).opcode := A_OR;
  15232. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  15233. Result := True;
  15234. end;
  15235. else
  15236. { Do nothing };
  15237. end;
  15238. end;
  15239. end;
  15240. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  15241. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  15242. begin
  15243. Result := False;
  15244. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  15245. Exit;
  15246. { For sizes less than S_L, the byte size is equal or larger with BTx,
  15247. so don't bother optimising }
  15248. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  15249. Exit;
  15250. if (taicpu(p).oper[0]^.typ <> top_const) or
  15251. { If the value can fit into an 8-bit signed integer, a smaller
  15252. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  15253. falls within this range }
  15254. (
  15255. (taicpu(p).oper[0]^.val > -128) and
  15256. (taicpu(p).oper[0]^.val <= 127)
  15257. ) then
  15258. Exit;
  15259. { If we're optimising for size, this is acceptable }
  15260. if (cs_opt_size in current_settings.optimizerswitches) then
  15261. Exit(True);
  15262. if (taicpu(p).oper[1]^.typ = top_reg) and
  15263. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  15264. Exit(True);
  15265. if (taicpu(p).oper[1]^.typ <> top_reg) and
  15266. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  15267. Exit(True);
  15268. end;
  15269. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  15270. var
  15271. hp1: tai;
  15272. Value: TCGInt;
  15273. begin
  15274. Result := False;
  15275. if MatchOpType(taicpu(p), top_const, top_reg) then
  15276. begin
  15277. { Detect:
  15278. andw x, %ax (0 <= x < $8000)
  15279. ...
  15280. movzwl %ax,%eax
  15281. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  15282. }
  15283. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  15284. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  15285. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  15286. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  15287. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  15288. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  15289. begin
  15290. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  15291. taicpu(hp1).opcode := A_CWDE;
  15292. taicpu(hp1).clearop(0);
  15293. taicpu(hp1).clearop(1);
  15294. taicpu(hp1).ops := 0;
  15295. { A change was made, but not with p, so don't set Result, but
  15296. notify the compiler that a change was made }
  15297. Include(OptsToCheck, aoc_ForceNewIteration);
  15298. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  15299. end;
  15300. end;
  15301. { If "not x" is a power of 2 (popcnt = 1), change:
  15302. and $x, %reg/ref
  15303. To:
  15304. btr lb(x), %reg/ref
  15305. }
  15306. if IsBTXAcceptable(p) and
  15307. (
  15308. { Make sure a TEST doesn't follow that plays with the register }
  15309. not GetNextInstruction(p, hp1) or
  15310. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  15311. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  15312. ) then
  15313. begin
  15314. {$push}{$R-}{$Q-}
  15315. { Value is a sign-extended 32-bit integer - just correct it
  15316. if it's represented as an unsigned value. Also, IsBTXAcceptable
  15317. checks to see if this operand is an immediate. }
  15318. Value := not taicpu(p).oper[0]^.val;
  15319. {$pop}
  15320. {$ifdef x86_64}
  15321. if taicpu(p).opsize = S_L then
  15322. {$endif x86_64}
  15323. Value := Value and $FFFFFFFF;
  15324. if (PopCnt(QWord(Value)) = 1) then
  15325. begin
  15326. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  15327. taicpu(p).opcode := A_BTR;
  15328. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  15329. Result := True;
  15330. Exit;
  15331. end;
  15332. end;
  15333. end;
  15334. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  15335. begin
  15336. Result := False;
  15337. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  15338. Exit;
  15339. { Convert:
  15340. movswl %ax,%eax -> cwtl
  15341. movslq %eax,%rax -> cdqe
  15342. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  15343. refer to the same opcode and depends only on the assembler's
  15344. current operand-size attribute. [Kit]
  15345. }
  15346. with taicpu(p) do
  15347. case opsize of
  15348. S_WL:
  15349. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  15350. begin
  15351. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  15352. opcode := A_CWDE;
  15353. clearop(0);
  15354. clearop(1);
  15355. ops := 0;
  15356. Result := True;
  15357. end;
  15358. {$ifdef x86_64}
  15359. S_LQ:
  15360. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  15361. begin
  15362. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  15363. opcode := A_CDQE;
  15364. clearop(0);
  15365. clearop(1);
  15366. ops := 0;
  15367. Result := True;
  15368. end;
  15369. {$endif x86_64}
  15370. else
  15371. ;
  15372. end;
  15373. end;
  15374. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  15375. var
  15376. hp1: tai;
  15377. begin
  15378. Result := False;
  15379. { All these optimisations work on "shr const,%reg" }
  15380. if not MatchOpType(taicpu(p), top_const, top_reg) then
  15381. Exit;
  15382. if HandleSHRMerge(p, True) then
  15383. begin
  15384. Result := True;
  15385. Exit;
  15386. end;
  15387. { Detect the following (looking backwards):
  15388. shr %cl,%reg
  15389. shr x, %reg
  15390. Swap the two SHR instructions to minimise a pipeline stall.
  15391. }
  15392. if GetLastInstruction(p, hp1) and
  15393. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15394. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15395. { First operand will be %cl }
  15396. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15397. { Just to be sure }
  15398. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15399. begin
  15400. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15401. { Moving the entries this way ensures the register tracking remains correct }
  15402. Asml.Remove(p);
  15403. Asml.InsertBefore(p, hp1);
  15404. p := hp1;
  15405. { Don't set Result to True because the current instruction is now
  15406. "shr %cl,%reg" and there's nothing more we can do with it }
  15407. end;
  15408. end;
  15409. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15410. var
  15411. hp1, hp2: tai;
  15412. Opposite, SecondOpposite: TAsmOp;
  15413. NewCond: TAsmCond;
  15414. begin
  15415. Result := False;
  15416. { Change:
  15417. add/sub 128,(dest)
  15418. To:
  15419. sub/add -128,(dest)
  15420. This generaally takes fewer bytes to encode because -128 can be stored
  15421. in a signed byte, whereas +128 cannot.
  15422. }
  15423. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15424. begin
  15425. if taicpu(p).opcode = A_ADD then
  15426. Opposite := A_SUB
  15427. else
  15428. Opposite := A_ADD;
  15429. { Be careful if the flags are in use, because the CF flag inverts
  15430. when changing from ADD to SUB and vice versa }
  15431. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15432. GetNextInstruction(p, hp1) then
  15433. begin
  15434. TransferUsedRegs(TmpUsedRegs);
  15435. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15436. hp2 := hp1;
  15437. { Scan ahead to check if everything's safe }
  15438. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15439. begin
  15440. if (hp1.typ <> ait_instruction) then
  15441. { Probably unsafe since the flags are still in use }
  15442. Exit;
  15443. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15444. { Stop searching at an unconditional jump }
  15445. Break;
  15446. if not
  15447. (
  15448. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15449. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15450. ) and
  15451. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15452. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15453. Exit;
  15454. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15455. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15456. { Move to the next instruction }
  15457. GetNextInstruction(hp1, hp1);
  15458. end;
  15459. while Assigned(hp2) and (hp2 <> hp1) do
  15460. begin
  15461. NewCond := C_None;
  15462. case taicpu(hp2).condition of
  15463. C_A, C_NBE:
  15464. NewCond := C_BE;
  15465. C_B, C_C, C_NAE:
  15466. NewCond := C_AE;
  15467. C_AE, C_NB, C_NC:
  15468. NewCond := C_B;
  15469. C_BE, C_NA:
  15470. NewCond := C_A;
  15471. else
  15472. { No change needed };
  15473. end;
  15474. if NewCond <> C_None then
  15475. begin
  15476. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15477. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15478. taicpu(hp2).condition := NewCond;
  15479. end
  15480. else
  15481. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15482. begin
  15483. { Because of the flipping of the carry bit, to ensure
  15484. the operation remains equivalent, ADC becomes SBB
  15485. and vice versa, and the constant is not-inverted.
  15486. If multiple ADCs or SBBs appear in a row, each one
  15487. changed causes the carry bit to invert, so they all
  15488. need to be flipped }
  15489. if taicpu(hp2).opcode = A_ADC then
  15490. SecondOpposite := A_SBB
  15491. else
  15492. SecondOpposite := A_ADC;
  15493. if taicpu(hp2).oper[0]^.typ <> top_const then
  15494. { Should have broken out of this optimisation already }
  15495. InternalError(2021112901);
  15496. 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]^) + ' -> ' +
  15497. 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);
  15498. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15499. taicpu(hp2).opcode := SecondOpposite;
  15500. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15501. end;
  15502. { Move to the next instruction }
  15503. GetNextInstruction(hp2, hp2);
  15504. end;
  15505. if (hp2 <> hp1) then
  15506. InternalError(2021111501);
  15507. end;
  15508. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15509. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15510. taicpu(p).opcode := Opposite;
  15511. taicpu(p).oper[0]^.val := -128;
  15512. { No further optimisations can be made on this instruction, so move
  15513. onto the next one to save time }
  15514. p := tai(p.Next);
  15515. UpdateUsedRegs(p);
  15516. Result := True;
  15517. Exit;
  15518. end;
  15519. { Detect:
  15520. add/sub %reg2,(dest)
  15521. add/sub x, (dest)
  15522. (dest can be a register or a reference)
  15523. Swap the instructions to minimise a pipeline stall. This reverses the
  15524. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15525. optimisations could be made.
  15526. }
  15527. if (taicpu(p).oper[0]^.typ = top_reg) and
  15528. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15529. (
  15530. (
  15531. (taicpu(p).oper[1]^.typ = top_reg) and
  15532. { We can try searching further ahead if we're writing to a register }
  15533. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15534. ) or
  15535. (
  15536. (taicpu(p).oper[1]^.typ = top_ref) and
  15537. GetNextInstruction(p, hp1)
  15538. )
  15539. ) and
  15540. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15541. (taicpu(hp1).oper[0]^.typ = top_const) and
  15542. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15543. begin
  15544. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15545. TransferUsedRegs(TmpUsedRegs);
  15546. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15547. hp2 := p;
  15548. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15549. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15550. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15551. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15552. begin
  15553. asml.remove(hp1);
  15554. asml.InsertBefore(hp1, p);
  15555. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15556. Result := True;
  15557. end;
  15558. end;
  15559. end;
  15560. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15561. var
  15562. hp1: tai;
  15563. begin
  15564. Result:=false;
  15565. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15566. while GetNextInstruction(p, hp1) and
  15567. TrySwapMovCmp(p, hp1) do
  15568. begin
  15569. if MatchInstruction(hp1, A_MOV, []) then
  15570. begin
  15571. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15572. begin
  15573. { A little hacky, but since CMP doesn't read the flags, only
  15574. modify them, it's safe if they get scrambled by MOV -> XOR }
  15575. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15576. Result := PostPeepholeOptMov(hp1);
  15577. {$ifdef x86_64}
  15578. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15579. { Used to shrink instruction size }
  15580. PostPeepholeOptXor(hp1);
  15581. {$endif x86_64}
  15582. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15583. end
  15584. else
  15585. begin
  15586. Result := PostPeepholeOptMov(hp1);
  15587. {$ifdef x86_64}
  15588. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15589. { Used to shrink instruction size }
  15590. PostPeepholeOptXor(hp1);
  15591. {$endif x86_64}
  15592. end;
  15593. end;
  15594. { Enabling this flag is actually a null operation, but it marks
  15595. the code as 'modified' during this pass }
  15596. Include(OptsToCheck, aoc_ForceNewIteration);
  15597. end;
  15598. { change "cmp $0, %reg" to "test %reg, %reg" }
  15599. if MatchOpType(taicpu(p),top_const,top_reg) and
  15600. (taicpu(p).oper[0]^.val = 0) then
  15601. begin
  15602. taicpu(p).opcode := A_TEST;
  15603. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15604. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15605. Result:=true;
  15606. end;
  15607. end;
  15608. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15609. var
  15610. IsTestConstX, IsValid : Boolean;
  15611. hp1,hp2 : tai;
  15612. begin
  15613. Result:=false;
  15614. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15615. if (taicpu(p).opcode = A_TEST) then
  15616. while GetNextInstruction(p, hp1) and
  15617. TrySwapMovCmp(p, hp1) do
  15618. begin
  15619. if MatchInstruction(hp1, A_MOV, []) then
  15620. begin
  15621. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15622. begin
  15623. { A little hacky, but since TEST doesn't read the flags, only
  15624. modify them, it's safe if they get scrambled by MOV -> XOR }
  15625. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15626. Result := PostPeepholeOptMov(hp1);
  15627. {$ifdef x86_64}
  15628. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15629. { Used to shrink instruction size }
  15630. PostPeepholeOptXor(hp1);
  15631. {$endif x86_64}
  15632. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15633. end
  15634. else
  15635. begin
  15636. Result := PostPeepholeOptMov(hp1);
  15637. {$ifdef x86_64}
  15638. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15639. { Used to shrink instruction size }
  15640. PostPeepholeOptXor(hp1);
  15641. {$endif x86_64}
  15642. end;
  15643. end;
  15644. { Enabling this flag is actually a null operation, but it marks
  15645. the code as 'modified' during this pass }
  15646. Include(OptsToCheck, aoc_ForceNewIteration);
  15647. end;
  15648. { If x is a power of 2 (popcnt = 1), change:
  15649. or $x, %reg/ref
  15650. To:
  15651. bts lb(x), %reg/ref
  15652. }
  15653. if (taicpu(p).opcode = A_OR) and
  15654. IsBTXAcceptable(p) and
  15655. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15656. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15657. (
  15658. { Don't optimise if a test instruction follows }
  15659. not GetNextInstruction(p, hp1) or
  15660. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15661. ) then
  15662. begin
  15663. 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);
  15664. taicpu(p).opcode := A_BTS;
  15665. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15666. Result := True;
  15667. Exit;
  15668. end;
  15669. { If x is a power of 2 (popcnt = 1), change:
  15670. test $x, %reg/ref
  15671. je / sete / cmove (or jne / setne)
  15672. To:
  15673. bt lb(x), %reg/ref
  15674. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15675. }
  15676. if (taicpu(p).opcode = A_TEST) and
  15677. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15678. (taicpu(p).oper[0]^.typ = top_const) and
  15679. (
  15680. (cs_opt_size in current_settings.optimizerswitches) or
  15681. (
  15682. (taicpu(p).oper[1]^.typ = top_reg) and
  15683. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15684. ) or
  15685. (
  15686. (taicpu(p).oper[1]^.typ <> top_reg) and
  15687. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15688. )
  15689. ) and
  15690. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15691. { For sizes less than S_L, the byte size is equal or larger with BT,
  15692. so don't bother optimising }
  15693. (taicpu(p).opsize >= S_L) then
  15694. begin
  15695. IsValid := True;
  15696. { Check the next set of instructions, watching the FLAGS register
  15697. and the conditions used }
  15698. TransferUsedRegs(TmpUsedRegs);
  15699. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15700. hp1 := p;
  15701. hp2 := nil;
  15702. while GetNextInstruction(hp1, hp1) do
  15703. begin
  15704. if not Assigned(hp2) then
  15705. { The first instruction after TEST }
  15706. hp2 := hp1;
  15707. if (hp1.typ <> ait_instruction) then
  15708. begin
  15709. { If the flags are no longer in use, everything is fine }
  15710. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15711. IsValid := False;
  15712. Break;
  15713. end;
  15714. case taicpu(hp1).condition of
  15715. C_None:
  15716. begin
  15717. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15718. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15719. { Something is not quite normal, so play safe and don't change }
  15720. IsValid := False;
  15721. Break;
  15722. end;
  15723. C_E, C_Z, C_NE, C_NZ:
  15724. { This is fine };
  15725. else
  15726. begin
  15727. { Unsupported condition }
  15728. IsValid := False;
  15729. Break;
  15730. end;
  15731. end;
  15732. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15733. end;
  15734. if IsValid then
  15735. begin
  15736. while hp2 <> hp1 do
  15737. begin
  15738. case taicpu(hp2).condition of
  15739. C_Z, C_E:
  15740. taicpu(hp2).condition := C_NC;
  15741. C_NZ, C_NE:
  15742. taicpu(hp2).condition := C_C;
  15743. else
  15744. { Should not get this by this point }
  15745. InternalError(2022110701);
  15746. end;
  15747. GetNextInstruction(hp2, hp2);
  15748. end;
  15749. 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);
  15750. taicpu(p).opcode := A_BT;
  15751. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15752. Result := True;
  15753. Exit;
  15754. end;
  15755. end;
  15756. { removes the line marked with (x) from the sequence
  15757. and/or/xor/add/sub/... $x, %y
  15758. test/or %y, %y | test $-1, %y (x)
  15759. j(n)z _Label
  15760. as the first instruction already adjusts the ZF
  15761. %y operand may also be a reference }
  15762. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15763. MatchOperand(taicpu(p).oper[0]^,-1);
  15764. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15765. GetLastInstruction(p, hp1) and
  15766. (tai(hp1).typ = ait_instruction) and
  15767. GetNextInstruction(p,hp2) and
  15768. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15769. case taicpu(hp1).opcode Of
  15770. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15771. { These two instructions set the zero flag if the result is zero }
  15772. A_POPCNT, A_LZCNT:
  15773. begin
  15774. if (
  15775. { With POPCNT, an input of zero will set the zero flag
  15776. because the population count of zero is zero }
  15777. (taicpu(hp1).opcode = A_POPCNT) and
  15778. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15779. (
  15780. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15781. { Faster than going through the second half of the 'or'
  15782. condition below }
  15783. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15784. )
  15785. ) or (
  15786. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15787. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15788. { and in case of carry for A(E)/B(E)/C/NC }
  15789. (
  15790. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15791. (
  15792. (taicpu(hp1).opcode <> A_ADD) and
  15793. (taicpu(hp1).opcode <> A_SUB) and
  15794. (taicpu(hp1).opcode <> A_LZCNT)
  15795. )
  15796. )
  15797. ) then
  15798. begin
  15799. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15800. RemoveCurrentP(p, hp2);
  15801. Result:=true;
  15802. Exit;
  15803. end;
  15804. end;
  15805. A_SHL, A_SAL, A_SHR, A_SAR:
  15806. begin
  15807. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15808. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15809. { therefore, it's only safe to do this optimization for }
  15810. { shifts by a (nonzero) constant }
  15811. (taicpu(hp1).oper[0]^.typ = top_const) and
  15812. (taicpu(hp1).oper[0]^.val <> 0) and
  15813. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15814. { and in case of carry for A(E)/B(E)/C/NC }
  15815. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15816. begin
  15817. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15818. RemoveCurrentP(p, hp2);
  15819. Result:=true;
  15820. Exit;
  15821. end;
  15822. end;
  15823. A_DEC, A_INC, A_NEG:
  15824. begin
  15825. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15826. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15827. { and in case of carry for A(E)/B(E)/C/NC }
  15828. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15829. begin
  15830. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15831. RemoveCurrentP(p, hp2);
  15832. Result:=true;
  15833. Exit;
  15834. end;
  15835. end;
  15836. A_ANDN, A_BZHI:
  15837. begin
  15838. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15839. { Only the zero and sign flags are consistent with what the result is }
  15840. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15841. begin
  15842. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15843. RemoveCurrentP(p, hp2);
  15844. Result:=true;
  15845. Exit;
  15846. end;
  15847. end;
  15848. A_BEXTR:
  15849. begin
  15850. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15851. { Only the zero flag is set }
  15852. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15853. begin
  15854. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15855. RemoveCurrentP(p, hp2);
  15856. Result:=true;
  15857. Exit;
  15858. end;
  15859. end;
  15860. else
  15861. ;
  15862. end; { case }
  15863. { change "test $-1,%reg" into "test %reg,%reg" }
  15864. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15865. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15866. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15867. if MatchInstruction(p, A_OR, []) and
  15868. { Can only match if they're both registers }
  15869. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15870. begin
  15871. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15872. taicpu(p).opcode := A_TEST;
  15873. { No need to set Result to True, as we've done all the optimisations we can }
  15874. end;
  15875. end;
  15876. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15877. var
  15878. hp1,hp3 : tai;
  15879. {$ifndef x86_64}
  15880. hp2 : taicpu;
  15881. {$endif x86_64}
  15882. begin
  15883. Result:=false;
  15884. hp3:=nil;
  15885. {$ifndef x86_64}
  15886. { don't do this on modern CPUs, this really hurts them due to
  15887. broken call/ret pairing }
  15888. if (current_settings.optimizecputype < cpu_Pentium2) and
  15889. not(cs_create_pic in current_settings.moduleswitches) and
  15890. GetNextInstruction(p, hp1) and
  15891. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15892. MatchOpType(taicpu(hp1),top_ref) and
  15893. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15894. begin
  15895. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15896. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15897. InsertLLItem(p.previous, p, hp2);
  15898. taicpu(p).opcode := A_JMP;
  15899. taicpu(p).is_jmp := true;
  15900. RemoveInstruction(hp1);
  15901. Result:=true;
  15902. end
  15903. else
  15904. {$endif x86_64}
  15905. { replace
  15906. call procname
  15907. ret
  15908. by
  15909. jmp procname
  15910. but do it only on level 4 because it destroys stack back traces
  15911. else if the subroutine is marked as no return, remove the ret
  15912. }
  15913. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15914. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15915. GetNextInstruction(p, hp1) and
  15916. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15917. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15918. SetAndTest(hp1,hp3) and
  15919. GetNextInstruction(hp1,hp1) and
  15920. MatchInstruction(hp1,A_RET,[S_NO])
  15921. )
  15922. ) and
  15923. (taicpu(hp1).ops=0) then
  15924. begin
  15925. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15926. { we might destroy stack alignment here if we do not do a call }
  15927. (target_info.stackalign<=sizeof(SizeUInt)) then
  15928. begin
  15929. taicpu(p).opcode := A_JMP;
  15930. taicpu(p).is_jmp := true;
  15931. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15932. end
  15933. else
  15934. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15935. RemoveInstruction(hp1);
  15936. if Assigned(hp3) then
  15937. begin
  15938. AsmL.Remove(hp3);
  15939. AsmL.InsertBefore(hp3,p)
  15940. end;
  15941. Result:=true;
  15942. end;
  15943. end;
  15944. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15945. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15946. begin
  15947. case OpSize of
  15948. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15949. Result := (Val <= $FF) and (Val >= -128);
  15950. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15951. Result := (Val <= $FFFF) and (Val >= -32768);
  15952. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15953. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15954. else
  15955. Result := True;
  15956. end;
  15957. end;
  15958. var
  15959. hp1, hp2 : tai;
  15960. SizeChange: Boolean;
  15961. PreMessage: string;
  15962. begin
  15963. Result := False;
  15964. if (taicpu(p).oper[0]^.typ = top_reg) and
  15965. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15966. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15967. begin
  15968. { Change (using movzbl %al,%eax as an example):
  15969. movzbl %al, %eax movzbl %al, %eax
  15970. cmpl x, %eax testl %eax,%eax
  15971. To:
  15972. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15973. movzbl %al, %eax movzbl %al, %eax
  15974. Smaller instruction and minimises pipeline stall as the CPU
  15975. doesn't have to wait for the register to get zero-extended. [Kit]
  15976. Also allow if the smaller of the two registers is being checked,
  15977. as this still removes the false dependency.
  15978. }
  15979. if
  15980. (
  15981. (
  15982. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15983. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15984. ) or (
  15985. { If MatchOperand returns True, they must both be registers }
  15986. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15987. )
  15988. ) and
  15989. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15990. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15991. begin
  15992. 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);
  15993. asml.Remove(hp1);
  15994. asml.InsertBefore(hp1, p);
  15995. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15996. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15997. begin
  15998. taicpu(hp1).opcode := A_TEST;
  15999. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  16000. end;
  16001. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  16002. case taicpu(p).opsize of
  16003. S_BW, S_BL:
  16004. begin
  16005. SizeChange := taicpu(hp1).opsize <> S_B;
  16006. taicpu(hp1).changeopsize(S_B);
  16007. end;
  16008. S_WL:
  16009. begin
  16010. SizeChange := taicpu(hp1).opsize <> S_W;
  16011. taicpu(hp1).changeopsize(S_W);
  16012. end
  16013. else
  16014. InternalError(2020112701);
  16015. end;
  16016. UpdateUsedRegs(tai(p.Next));
  16017. { Check if the register is used aferwards - if not, we can
  16018. remove the movzx instruction completely }
  16019. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  16020. begin
  16021. { Hp1 is a better position than p for debugging purposes }
  16022. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  16023. RemoveCurrentp(p, hp1);
  16024. Result := True;
  16025. end;
  16026. if SizeChange then
  16027. DebugMsg(SPeepholeOptimization + PreMessage +
  16028. 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)
  16029. else
  16030. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  16031. Exit;
  16032. end;
  16033. { Change (using movzwl %ax,%eax as an example):
  16034. movzwl %ax, %eax
  16035. movb %al, (dest) (Register is smaller than read register in movz)
  16036. To:
  16037. movb %al, (dest) (Move one back to avoid a false dependency)
  16038. movzwl %ax, %eax
  16039. }
  16040. if (taicpu(hp1).opcode = A_MOV) and
  16041. (taicpu(hp1).oper[0]^.typ = top_reg) and
  16042. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  16043. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  16044. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  16045. begin
  16046. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  16047. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  16048. asml.Remove(hp1);
  16049. asml.InsertBefore(hp1, p);
  16050. if taicpu(hp1).oper[1]^.typ = top_reg then
  16051. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  16052. { Check if the register is used aferwards - if not, we can
  16053. remove the movzx instruction completely }
  16054. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  16055. begin
  16056. { Hp1 is a better position than p for debugging purposes }
  16057. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  16058. RemoveCurrentp(p, hp1);
  16059. Result := True;
  16060. end;
  16061. Exit;
  16062. end;
  16063. end;
  16064. end;
  16065. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  16066. var
  16067. hp1: tai;
  16068. {$ifdef x86_64}
  16069. PreMessage, RegName: string;
  16070. {$endif x86_64}
  16071. begin
  16072. Result := False;
  16073. { If x is a power of 2 (popcnt = 1), change:
  16074. xor $x, %reg/ref
  16075. To:
  16076. btc lb(x), %reg/ref
  16077. }
  16078. if IsBTXAcceptable(p) and
  16079. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  16080. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  16081. (
  16082. { Don't optimise if a test instruction follows }
  16083. not GetNextInstruction(p, hp1) or
  16084. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  16085. ) then
  16086. begin
  16087. 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);
  16088. taicpu(p).opcode := A_BTC;
  16089. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  16090. Result := True;
  16091. Exit;
  16092. end;
  16093. {$ifdef x86_64}
  16094. { Code size reduction by J. Gareth "Kit" Moreton }
  16095. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  16096. as this removes the REX prefix }
  16097. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  16098. Exit;
  16099. if taicpu(p).oper[0]^.typ <> top_reg then
  16100. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  16101. InternalError(2018011500);
  16102. case taicpu(p).opsize of
  16103. S_Q:
  16104. begin
  16105. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  16106. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  16107. { The actual optimization }
  16108. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  16109. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  16110. taicpu(p).changeopsize(S_L);
  16111. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  16112. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  16113. end;
  16114. else
  16115. ;
  16116. end;
  16117. {$endif x86_64}
  16118. end;
  16119. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  16120. var
  16121. XReg: TRegister;
  16122. begin
  16123. Result := False;
  16124. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  16125. Smaller encoding and slightly faster on some platforms (also works for
  16126. ZMM-sized registers) }
  16127. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  16128. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  16129. begin
  16130. XReg := taicpu(p).oper[0]^.reg;
  16131. if (taicpu(p).oper[1]^.reg = XReg) then
  16132. begin
  16133. taicpu(p).changeopsize(S_XMM);
  16134. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  16135. if (cs_opt_size in current_settings.optimizerswitches) then
  16136. begin
  16137. { Change input registers to %xmm0 to reduce size. Note that
  16138. there's a risk of a false dependency doing this, so only
  16139. optimise for size here }
  16140. XReg := NR_XMM0;
  16141. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  16142. end
  16143. else
  16144. begin
  16145. setsubreg(XReg, R_SUBMMX);
  16146. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  16147. end;
  16148. taicpu(p).oper[0]^.reg := XReg;
  16149. taicpu(p).oper[1]^.reg := XReg;
  16150. Result := True;
  16151. end;
  16152. end;
  16153. end;
  16154. function TX86AsmOptimizer.PostPeepholeOptRET(var p: tai): Boolean;
  16155. var
  16156. hp1, p_new: tai;
  16157. begin
  16158. Result := False;
  16159. { Check for:
  16160. ret
  16161. .Lbl:
  16162. ret
  16163. Remove first 'ret'
  16164. }
  16165. if GetNextInstruction(p, hp1) and
  16166. { Remember where the label is }
  16167. SetAndTest(hp1, p_new) and
  16168. (hp1.typ in [ait_align, ait_label]) and
  16169. SkipLabels(hp1, hp1) and
  16170. MatchInstruction(hp1, A_RET, []) and
  16171. { To be safe, make sure the RET instructions are identical }
  16172. (taicpu(p).ops = taicpu(hp1).ops) and
  16173. (
  16174. (taicpu(p).ops = 0) or
  16175. (
  16176. (taicpu(p).ops = 1) and
  16177. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^)
  16178. )
  16179. ) then
  16180. begin
  16181. DebugMsg(SPeepholeOptimization + 'Removed superfluous RET', p);
  16182. UpdateUsedRegs(tai(p.Next));
  16183. RemoveCurrentP(p, p_new);
  16184. Result := True;
  16185. Exit;
  16186. end;
  16187. end;
  16188. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  16189. var
  16190. OperIdx: Integer;
  16191. begin
  16192. for OperIdx := 0 to p.ops - 1 do
  16193. if p.oper[OperIdx]^.typ = top_ref then
  16194. optimize_ref(p.oper[OperIdx]^.ref^, False);
  16195. end;
  16196. end.