aoptx86.pas 758 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676
  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. procedure DebugMsg(const s : string; p : tai);inline;
  118. class function IsExitCode(p : tai) : boolean; static;
  119. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  120. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  121. procedure RemoveLastDeallocForFuncRes(p : tai);
  122. function DoArithCombineOpt(var p : tai) : Boolean;
  123. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  124. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  125. function HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  126. function PrePeepholeOptSxx(var p : tai) : boolean;
  127. function PrePeepholeOptIMUL(var p : tai) : boolean;
  128. function PrePeepholeOptAND(var p : tai) : boolean;
  129. function OptPass1Test(var p: tai): boolean;
  130. function OptPass1Add(var p: tai): boolean;
  131. function OptPass1AND(var p : tai) : boolean;
  132. function OptPass1CMOVcc(var p: tai): Boolean;
  133. function OptPass1_V_MOVAP(var p : tai) : boolean;
  134. function OptPass1VOP(var p : tai) : boolean;
  135. function OptPass1MOV(var p : tai) : boolean;
  136. function OptPass1Movx(var p : tai) : boolean;
  137. function OptPass1MOVXX(var p : tai) : boolean;
  138. function OptPass1OP(var p : tai) : boolean;
  139. function OptPass1LEA(var p : tai) : boolean;
  140. function OptPass1Sub(var p : tai) : boolean;
  141. function OptPass1SHLSAL(var p : tai) : boolean;
  142. function OptPass1SHR(var p : tai) : boolean;
  143. function OptPass1FSTP(var p : tai) : boolean;
  144. function OptPass1FLD(var p : tai) : boolean;
  145. function OptPass1Cmp(var p : tai) : boolean;
  146. function OptPass1PXor(var p : tai) : boolean;
  147. function OptPass1VPXor(var p: tai): boolean;
  148. function OptPass1Imul(var p : tai) : boolean;
  149. function OptPass1Jcc(var p : tai) : boolean;
  150. function OptPass1SHXX(var p: tai): boolean;
  151. function OptPass1VMOVDQ(var p: tai): Boolean;
  152. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  153. function OptPass1STCCLC(var p: tai): Boolean;
  154. function OptPass2STCCLC(var p: tai): Boolean;
  155. function OptPass2CMOVcc(var p: tai): Boolean;
  156. function OptPass2Movx(var p : tai): Boolean;
  157. function OptPass2MOV(var p : tai) : boolean;
  158. function OptPass2Imul(var p : tai) : boolean;
  159. function OptPass2Jmp(var p : tai) : boolean;
  160. function OptPass2Jcc(var p : tai) : boolean;
  161. function OptPass2Lea(var p: tai): Boolean;
  162. function OptPass2SUB(var p: tai): Boolean;
  163. function OptPass2ADD(var p : tai): Boolean;
  164. function OptPass2SETcc(var p : tai) : boolean;
  165. function OptPass2Cmp(var p: tai): Boolean;
  166. function OptPass2Test(var p: tai): Boolean;
  167. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  168. function PostPeepholeOptMov(var p : tai) : Boolean;
  169. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  170. function PostPeepholeOptXor(var p : tai) : Boolean;
  171. function PostPeepholeOptAnd(var p : tai) : boolean;
  172. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  173. function PostPeepholeOptCmp(var p : tai) : Boolean;
  174. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  175. function PostPeepholeOptCall(var p : tai) : Boolean;
  176. function PostPeepholeOptLea(var p : tai) : Boolean;
  177. function PostPeepholeOptPush(var p: tai): Boolean;
  178. function PostPeepholeOptShr(var p : tai) : boolean;
  179. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  180. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  181. function PostPeepholeOptRET(var p: tai): Boolean;
  182. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  183. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  184. function TrySwapMovOp(var p, hp1: tai): Boolean;
  185. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  186. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  187. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  188. { Processor-dependent reference optimisation }
  189. class procedure OptimizeRefs(var p: taicpu); static;
  190. end;
  191. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  192. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  193. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  194. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  195. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  196. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  197. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  198. {$if max_operands>2}
  199. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  200. {$endif max_operands>2}
  201. function RefsEqual(const r1, r2: treference): boolean;
  202. { Like RefsEqual, but doesn't compare the offsets }
  203. function RefsAlmostEqual(const r1, r2: treference): boolean;
  204. { Note that Result is set to True if the references COULD overlap but the
  205. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  206. might still overlap because %reg2 could be equal to %reg1-4 }
  207. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  208. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  209. { returns true, if ref is a reference using only the registers passed as base and index
  210. and having an offset }
  211. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  212. implementation
  213. uses
  214. cutils,verbose,
  215. systems,
  216. globals,
  217. cpuinfo,
  218. procinfo,
  219. paramgr,
  220. aasmbase,
  221. aoptbase,aoptutils,
  222. symconst,symsym,
  223. cgx86,
  224. itcpugas;
  225. {$ifndef 8086}
  226. const
  227. MAX_CMOV_INSTRUCTIONS = 4;
  228. MAX_CMOV_REGISTERS = 8;
  229. type
  230. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  231. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  232. tsProcessed);
  233. { For OptPass2Jcc }
  234. TCMOVTracking = object
  235. private
  236. CMOVScore, ConstCount: LongInt;
  237. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  238. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  239. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  240. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  241. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  242. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  243. fOptimizer: TX86AsmOptimizer;
  244. fLabel: TAsmSymbol;
  245. fInsertionPoint,
  246. fCondition,
  247. fInitialJump,
  248. fFirstMovBlock,
  249. fFirstMovBlockStop,
  250. fSecondJump,
  251. fThirdJump,
  252. fSecondMovBlock,
  253. fSecondMovBlockStop,
  254. fMidLabel,
  255. fEndLabel,
  256. fAllocationRange: tai;
  257. fState: TCMovTrackingState;
  258. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  259. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  260. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  261. public
  262. RegisterTracking: TAllUsedRegs;
  263. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  264. destructor Done;
  265. procedure Process(out new_p: tai);
  266. property State: TCMovTrackingState read fState;
  267. end;
  268. PCMOVTracking = ^TCMOVTracking;
  269. {$endif 8086}
  270. {$ifdef DEBUG_AOPTCPU}
  271. const
  272. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  273. {$else DEBUG_AOPTCPU}
  274. { Empty strings help the optimizer to remove string concatenations that won't
  275. ever appear to the user on release builds. [Kit] }
  276. const
  277. SPeepholeOptimization = '';
  278. {$endif DEBUG_AOPTCPU}
  279. LIST_STEP_SIZE = 4;
  280. type
  281. TJumpTrackingItem = class(TLinkedListItem)
  282. private
  283. FSymbol: TAsmSymbol;
  284. FRefs: LongInt;
  285. public
  286. constructor Create(ASymbol: TAsmSymbol);
  287. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  288. property Symbol: TAsmSymbol read FSymbol;
  289. property Refs: LongInt read FRefs;
  290. end;
  291. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  292. begin
  293. inherited Create;
  294. FSymbol := ASymbol;
  295. FRefs := 0;
  296. end;
  297. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  298. begin
  299. Inc(FRefs);
  300. end;
  301. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  302. begin
  303. result :=
  304. (instr.typ = ait_instruction) and
  305. (taicpu(instr).opcode = op) and
  306. ((opsize = []) or (taicpu(instr).opsize in opsize));
  307. end;
  308. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  309. begin
  310. result :=
  311. (instr.typ = ait_instruction) and
  312. ((taicpu(instr).opcode = op1) or
  313. (taicpu(instr).opcode = op2)
  314. ) and
  315. ((opsize = []) or (taicpu(instr).opsize in opsize));
  316. end;
  317. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  318. begin
  319. result :=
  320. (instr.typ = ait_instruction) and
  321. ((taicpu(instr).opcode = op1) or
  322. (taicpu(instr).opcode = op2) or
  323. (taicpu(instr).opcode = op3)
  324. ) and
  325. ((opsize = []) or (taicpu(instr).opsize in opsize));
  326. end;
  327. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  328. const opsize : topsizes) : boolean;
  329. var
  330. op : TAsmOp;
  331. begin
  332. result:=false;
  333. if (instr.typ <> ait_instruction) or
  334. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  335. exit;
  336. for op in ops do
  337. begin
  338. if taicpu(instr).opcode = op then
  339. begin
  340. result:=true;
  341. exit;
  342. end;
  343. end;
  344. end;
  345. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  346. begin
  347. result := (oper.typ = top_reg) and (oper.reg = reg);
  348. end;
  349. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  350. begin
  351. result := (oper.typ = top_const) and (oper.val = a);
  352. end;
  353. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  354. begin
  355. result := oper1.typ = oper2.typ;
  356. if result then
  357. case oper1.typ of
  358. top_const:
  359. Result:=oper1.val = oper2.val;
  360. top_reg:
  361. Result:=oper1.reg = oper2.reg;
  362. top_ref:
  363. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  364. else
  365. internalerror(2013102801);
  366. end
  367. end;
  368. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  369. begin
  370. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  371. if result then
  372. case oper1.typ of
  373. top_const:
  374. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  375. top_reg:
  376. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  377. top_ref:
  378. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  379. else
  380. internalerror(2020052401);
  381. end
  382. end;
  383. function RefsEqual(const r1, r2: treference): boolean;
  384. begin
  385. RefsEqual :=
  386. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  387. (r1.relsymbol = r2.relsymbol) and
  388. (r1.segment = r2.segment) and (r1.base = r2.base) and
  389. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  390. (r1.offset = r2.offset) and
  391. (r1.volatility + r2.volatility = []);
  392. end;
  393. function RefsAlmostEqual(const r1, r2: treference): boolean;
  394. begin
  395. RefsAlmostEqual :=
  396. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  397. (r1.relsymbol = r2.relsymbol) and
  398. (r1.segment = r2.segment) and (r1.base = r2.base) and
  399. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  400. { Don't compare the offsets }
  401. (r1.volatility + r2.volatility = []);
  402. end;
  403. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  404. begin
  405. if (r1.symbol<>r2.symbol) then
  406. { If the index registers are different, there's a chance one could
  407. be set so it equals the other symbol }
  408. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  409. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  410. (r1.relsymbol = r2.relsymbol) and
  411. (r1.segment = r2.segment) and (r1.base = r2.base) and
  412. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  413. (r1.volatility + r2.volatility = []) then
  414. { In this case, it all depends on the offsets }
  415. Exit(abs(r1.offset - r2.offset) < Range);
  416. { There's a chance things MIGHT overlap, so take no chances }
  417. Result := True;
  418. end;
  419. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  420. begin
  421. Result:=(ref.offset=0) and
  422. (ref.scalefactor in [0,1]) and
  423. (ref.segment=NR_NO) and
  424. (ref.symbol=nil) and
  425. (ref.relsymbol=nil) and
  426. ((base=NR_INVALID) or
  427. (ref.base=base)) and
  428. ((index=NR_INVALID) or
  429. (ref.index=index)) and
  430. (ref.volatility=[]);
  431. end;
  432. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  433. begin
  434. Result:=(ref.scalefactor in [0,1]) and
  435. (ref.segment=NR_NO) and
  436. (ref.symbol=nil) and
  437. (ref.relsymbol=nil) and
  438. ((base=NR_INVALID) or
  439. (ref.base=base)) and
  440. ((index=NR_INVALID) or
  441. (ref.index=index)) and
  442. (ref.volatility=[]);
  443. end;
  444. function InstrReadsFlags(p: tai): boolean;
  445. begin
  446. InstrReadsFlags := true;
  447. case p.typ of
  448. ait_instruction:
  449. if InsProp[taicpu(p).opcode].Ch*
  450. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  451. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  452. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  453. exit;
  454. ait_label:
  455. exit;
  456. else
  457. ;
  458. end;
  459. InstrReadsFlags := false;
  460. end;
  461. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  462. begin
  463. Next:=Current;
  464. repeat
  465. Result:=GetNextInstruction(Next,Next);
  466. until not (Result) or
  467. not(cs_opt_level3 in current_settings.optimizerswitches) or
  468. (Next.typ<>ait_instruction) or
  469. RegInInstruction(reg,Next) or
  470. is_calljmp(taicpu(Next).opcode);
  471. end;
  472. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  473. var
  474. GetNextResult: Boolean;
  475. begin
  476. Result:=0;
  477. Next:=Current;
  478. repeat
  479. GetNextResult := GetNextInstruction(Next,Next);
  480. if GetNextResult then
  481. Inc(Result)
  482. else
  483. { Must return zero upon hitting the end of the linked list without a match }
  484. Result := 0;
  485. until not (GetNextResult) or
  486. not(cs_opt_level3 in current_settings.optimizerswitches) or
  487. (Next.typ<>ait_instruction) or
  488. RegInInstruction(reg,Next) or
  489. is_calljmp(taicpu(Next).opcode);
  490. end;
  491. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  492. procedure TrackJump(Symbol: TAsmSymbol);
  493. var
  494. Search: TJumpTrackingItem;
  495. begin
  496. { See if an entry already exists in our jump tracking list
  497. (faster to search backwards due to the higher chance of
  498. matching destinations) }
  499. Search := TJumpTrackingItem(JumpTracking.Last);
  500. while Assigned(Search) do
  501. begin
  502. if Search.Symbol = Symbol then
  503. begin
  504. { Found it - remove it so it can be pushed to the front }
  505. JumpTracking.Remove(Search);
  506. Break;
  507. end;
  508. Search := TJumpTrackingItem(Search.Previous);
  509. end;
  510. if not Assigned(Search) then
  511. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  512. JumpTracking.Concat(Search);
  513. Search.IncRefs;
  514. end;
  515. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  516. var
  517. Search: TJumpTrackingItem;
  518. begin
  519. Result := False;
  520. { See if this label appears in the tracking list }
  521. Search := TJumpTrackingItem(JumpTracking.Last);
  522. while Assigned(Search) do
  523. begin
  524. if Search.Symbol = Symbol then
  525. begin
  526. { Found it - let's see what we can discover }
  527. if Search.Symbol.getrefs = Search.Refs then
  528. begin
  529. { Success - all the references are accounted for }
  530. JumpTracking.Remove(Search);
  531. Search.Free;
  532. { It is logically impossible for CrossJump to be false here
  533. because we must have run into a conditional jump for
  534. this label at some point }
  535. if not CrossJump then
  536. InternalError(2022041710);
  537. if JumpTracking.First = nil then
  538. { Tracking list is now empty - no more cross jumps }
  539. CrossJump := False;
  540. Result := True;
  541. Exit;
  542. end;
  543. { If the references don't match, it's possible to enter
  544. this label through other means, so drop out }
  545. Exit;
  546. end;
  547. Search := TJumpTrackingItem(Search.Previous);
  548. end;
  549. end;
  550. var
  551. Next_Label: tai;
  552. begin
  553. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  554. Next := Current;
  555. repeat
  556. Result := GetNextInstruction(Next,Next);
  557. if not Result then
  558. Break;
  559. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  560. if is_calljmpuncondret(taicpu(Next).opcode) then
  561. begin
  562. if (taicpu(Next).opcode = A_JMP) and
  563. { Remove dead code now to save time }
  564. RemoveDeadCodeAfterJump(taicpu(Next)) then
  565. { A jump was removed, but not the current instruction, and
  566. Result doesn't necessarily translate into an optimisation
  567. routine's Result, so use the "Force New Iteration" flag so
  568. mark a new pass }
  569. Include(OptsToCheck, aoc_ForceNewIteration);
  570. if not Assigned(JumpTracking) then
  571. begin
  572. { Cross-label optimisations often causes other optimisations
  573. to perform worse because they're not given the chance to
  574. optimise locally. In this case, don't do the cross-label
  575. optimisations yet, but flag them as a potential possibility
  576. for the next iteration of Pass 1 }
  577. if not NotFirstIteration then
  578. Include(OptsToCheck, aoc_ForceNewIteration);
  579. end
  580. else if IsJumpToLabel(taicpu(Next)) and
  581. GetNextInstruction(Next, Next_Label) then
  582. begin
  583. { If we have JMP .lbl, and the label after it has all of its
  584. references tracked, then this is probably an if-else style of
  585. block and we can keep tracking. If the label for this jump
  586. then appears later and is fully tracked, then it's the end
  587. of the if-else blocks and the code paths converge (thus
  588. marking the end of the cross-jump) }
  589. if (Next_Label.typ = ait_label) then
  590. begin
  591. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  592. begin
  593. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  594. Next := Next_Label;
  595. { CrossJump gets set to false by LabelAccountedFor if the
  596. list is completely emptied (as it indicates that all
  597. code paths have converged). We could avoid this nuance
  598. by moving the TrackJump call to before the
  599. LabelAccountedFor call, but this is slower in situations
  600. where LabelAccountedFor would return False due to the
  601. creation of a new object that is not used and destroyed
  602. soon after. }
  603. CrossJump := True;
  604. Continue;
  605. end;
  606. end
  607. else if (Next_Label.typ <> ait_marker) then
  608. { We just did a RemoveDeadCodeAfterJump, so either we find
  609. a label, the end of the procedure or some kind of marker}
  610. InternalError(2022041720);
  611. end;
  612. Result := False;
  613. Exit;
  614. end
  615. else
  616. begin
  617. if not Assigned(JumpTracking) then
  618. begin
  619. { Cross-label optimisations often causes other optimisations
  620. to perform worse because they're not given the chance to
  621. optimise locally. In this case, don't do the cross-label
  622. optimisations yet, but flag them as a potential possibility
  623. for the next iteration of Pass 1 }
  624. if not NotFirstIteration then
  625. Include(OptsToCheck, aoc_ForceNewIteration);
  626. end
  627. else if IsJumpToLabel(taicpu(Next)) then
  628. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  629. else
  630. { Conditional jumps should always be a jump to label }
  631. InternalError(2022041701);
  632. CrossJump := True;
  633. Continue;
  634. end;
  635. if Next.typ = ait_label then
  636. begin
  637. if not Assigned(JumpTracking) then
  638. begin
  639. { Cross-label optimisations often causes other optimisations
  640. to perform worse because they're not given the chance to
  641. optimise locally. In this case, don't do the cross-label
  642. optimisations yet, but flag them as a potential possibility
  643. for the next iteration of Pass 1 }
  644. if not NotFirstIteration then
  645. Include(OptsToCheck, aoc_ForceNewIteration);
  646. end
  647. else if LabelAccountedFor(tai_label(Next).labsym) then
  648. Continue;
  649. { If we reach here, we're at a label that hasn't been seen before
  650. (or JumpTracking was nil) }
  651. Break;
  652. end;
  653. until not Result or
  654. not (cs_opt_level3 in current_settings.optimizerswitches) or
  655. not (Next.typ in [ait_label, ait_instruction]) or
  656. RegInInstruction(reg,Next);
  657. end;
  658. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  659. begin
  660. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  661. begin
  662. Result:=GetNextInstruction(Current,Next);
  663. exit;
  664. end;
  665. Next:=tai(Current.Next);
  666. Result:=false;
  667. while assigned(Next) do
  668. begin
  669. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  670. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  671. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  672. exit
  673. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  674. begin
  675. Result:=true;
  676. exit;
  677. end;
  678. Next:=tai(Next.Next);
  679. end;
  680. end;
  681. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  682. begin
  683. Result:=RegReadByInstruction(reg,hp);
  684. end;
  685. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  686. var
  687. p: taicpu;
  688. opcount: longint;
  689. begin
  690. RegReadByInstruction := false;
  691. if hp.typ <> ait_instruction then
  692. exit;
  693. p := taicpu(hp);
  694. case p.opcode of
  695. A_CALL:
  696. regreadbyinstruction := true;
  697. A_IMUL:
  698. case p.ops of
  699. 1:
  700. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  701. (
  702. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  703. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  704. );
  705. 2,3:
  706. regReadByInstruction :=
  707. reginop(reg,p.oper[0]^) or
  708. reginop(reg,p.oper[1]^);
  709. else
  710. InternalError(2019112801);
  711. end;
  712. A_MUL:
  713. begin
  714. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  715. (
  716. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  717. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  718. );
  719. end;
  720. A_IDIV,A_DIV:
  721. begin
  722. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  723. (
  724. (getregtype(reg)=R_INTREGISTER) and
  725. (
  726. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  727. )
  728. );
  729. end;
  730. else
  731. begin
  732. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  733. begin
  734. RegReadByInstruction := false;
  735. exit;
  736. end;
  737. for opcount := 0 to p.ops-1 do
  738. if (p.oper[opCount]^.typ = top_ref) and
  739. RegInRef(reg,p.oper[opcount]^.ref^) then
  740. begin
  741. RegReadByInstruction := true;
  742. exit
  743. end;
  744. { special handling for SSE MOVSD }
  745. if (p.opcode=A_MOVSD) and (p.ops>0) then
  746. begin
  747. if p.ops<>2 then
  748. internalerror(2017042702);
  749. regReadByInstruction := reginop(reg,p.oper[0]^) or
  750. (
  751. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  752. );
  753. exit;
  754. end;
  755. with insprop[p.opcode] do
  756. begin
  757. case getregtype(reg) of
  758. R_INTREGISTER:
  759. begin
  760. case getsupreg(reg) of
  761. RS_EAX:
  762. if [Ch_REAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  763. begin
  764. RegReadByInstruction := true;
  765. exit
  766. end;
  767. RS_ECX:
  768. if [Ch_RECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  769. begin
  770. RegReadByInstruction := true;
  771. exit
  772. end;
  773. RS_EDX:
  774. if [Ch_REDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  775. begin
  776. RegReadByInstruction := true;
  777. exit
  778. end;
  779. RS_EBX:
  780. if [Ch_REBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  781. begin
  782. RegReadByInstruction := true;
  783. exit
  784. end;
  785. RS_ESP:
  786. if [Ch_RESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  787. begin
  788. RegReadByInstruction := true;
  789. exit
  790. end;
  791. RS_EBP:
  792. if [Ch_REBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  793. begin
  794. RegReadByInstruction := true;
  795. exit
  796. end;
  797. RS_ESI:
  798. if [Ch_RESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  799. begin
  800. RegReadByInstruction := true;
  801. exit
  802. end;
  803. RS_EDI:
  804. if [Ch_REDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  805. begin
  806. RegReadByInstruction := true;
  807. exit
  808. end;
  809. end;
  810. end;
  811. R_MMREGISTER:
  812. begin
  813. case getsupreg(reg) of
  814. RS_XMM0:
  815. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  816. begin
  817. RegReadByInstruction := true;
  818. exit
  819. end;
  820. end;
  821. end;
  822. else
  823. ;
  824. end;
  825. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  826. begin
  827. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  828. begin
  829. case p.condition of
  830. C_A,C_NBE, { CF=0 and ZF=0 }
  831. C_BE,C_NA: { CF=1 or ZF=1 }
  832. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  833. C_AE,C_NB,C_NC, { CF=0 }
  834. C_B,C_NAE,C_C: { CF=1 }
  835. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  836. C_NE,C_NZ, { ZF=0 }
  837. C_E,C_Z: { ZF=1 }
  838. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  839. C_G,C_NLE, { ZF=0 and SF=OF }
  840. C_LE,C_NG: { ZF=1 or SF<>OF }
  841. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  842. C_GE,C_NL, { SF=OF }
  843. C_L,C_NGE: { SF<>OF }
  844. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  845. C_NO, { OF=0 }
  846. C_O: { OF=1 }
  847. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  848. C_NP,C_PO, { PF=0 }
  849. C_P,C_PE: { PF=1 }
  850. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  851. C_NS, { SF=0 }
  852. C_S: { SF=1 }
  853. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  854. else
  855. internalerror(2017042701);
  856. end;
  857. if RegReadByInstruction then
  858. exit;
  859. end;
  860. case getsubreg(reg) of
  861. R_SUBW,R_SUBD,R_SUBQ:
  862. RegReadByInstruction :=
  863. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  864. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  865. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  866. R_SUBFLAGCARRY:
  867. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  868. R_SUBFLAGPARITY:
  869. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  870. R_SUBFLAGAUXILIARY:
  871. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  872. R_SUBFLAGZERO:
  873. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  874. R_SUBFLAGSIGN:
  875. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  876. R_SUBFLAGOVERFLOW:
  877. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  878. R_SUBFLAGINTERRUPT:
  879. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  880. R_SUBFLAGDIRECTION:
  881. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  882. else
  883. internalerror(2017042601);
  884. end;
  885. exit;
  886. end;
  887. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  888. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  889. (p.oper[0]^.reg=p.oper[1]^.reg) then
  890. exit;
  891. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  892. begin
  893. RegReadByInstruction := true;
  894. exit
  895. end;
  896. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  897. begin
  898. RegReadByInstruction := true;
  899. exit
  900. end;
  901. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  902. begin
  903. RegReadByInstruction := true;
  904. exit
  905. end;
  906. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  907. begin
  908. RegReadByInstruction := true;
  909. exit
  910. end;
  911. end;
  912. end;
  913. end;
  914. end;
  915. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  916. begin
  917. result:=false;
  918. if p1.typ<>ait_instruction then
  919. exit;
  920. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  921. exit(true);
  922. if (getregtype(reg)=R_INTREGISTER) and
  923. { change information for xmm movsd are not correct }
  924. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  925. begin
  926. { Handle instructions that behave differently depending on the size and operand count }
  927. case taicpu(p1).opcode of
  928. A_MUL, A_DIV, A_IDIV:
  929. if taicpu(p1).opsize = S_B then
  930. Result := (getsupreg(Reg) = RS_EAX)
  931. else
  932. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  933. A_IMUL:
  934. if taicpu(p1).ops = 1 then
  935. begin
  936. if taicpu(p1).opsize = S_B then
  937. Result := (getsupreg(Reg) = RS_EAX)
  938. else
  939. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  940. end;
  941. { If ops are greater than 1, call inherited method }
  942. else
  943. case getsupreg(reg) of
  944. { RS_EAX = RS_RAX on x86-64 }
  945. RS_EAX:
  946. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  947. RS_ECX:
  948. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  949. RS_EDX:
  950. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  951. RS_EBX:
  952. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  953. RS_ESP:
  954. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  955. RS_EBP:
  956. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  957. RS_ESI:
  958. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  959. RS_EDI:
  960. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  961. else
  962. ;
  963. end;
  964. end;
  965. if result then
  966. exit;
  967. end
  968. else if getregtype(reg)=R_MMREGISTER then
  969. begin
  970. case getsupreg(reg) of
  971. RS_XMM0:
  972. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  973. else
  974. ;
  975. end;
  976. if result then
  977. exit;
  978. end
  979. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  980. begin
  981. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  982. exit(true);
  983. case getsubreg(reg) of
  984. R_SUBFLAGCARRY:
  985. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  986. R_SUBFLAGPARITY:
  987. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  988. R_SUBFLAGAUXILIARY:
  989. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  990. R_SUBFLAGZERO:
  991. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  992. R_SUBFLAGSIGN:
  993. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  994. R_SUBFLAGOVERFLOW:
  995. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  996. R_SUBFLAGINTERRUPT:
  997. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  998. R_SUBFLAGDIRECTION:
  999. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  1000. R_SUBW,R_SUBD,R_SUBQ:
  1001. { Everything except the direction bits }
  1002. Result:=
  1003. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1004. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1005. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1006. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1007. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1008. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1009. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1010. else
  1011. ;
  1012. end;
  1013. if result then
  1014. exit;
  1015. end
  1016. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1017. exit(true);
  1018. Result:=inherited RegInInstruction(Reg, p1);
  1019. end;
  1020. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1021. const
  1022. WriteOps: array[0..3] of set of TInsChange =
  1023. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1024. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1025. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1026. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1027. var
  1028. OperIdx: Integer;
  1029. begin
  1030. Result := False;
  1031. if p1.typ <> ait_instruction then
  1032. exit;
  1033. with insprop[taicpu(p1).opcode] do
  1034. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1035. begin
  1036. case getsubreg(reg) of
  1037. R_SUBW,R_SUBD,R_SUBQ:
  1038. Result :=
  1039. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1040. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1041. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1042. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1043. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1044. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1045. R_SUBFLAGCARRY:
  1046. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1047. R_SUBFLAGPARITY:
  1048. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1049. R_SUBFLAGAUXILIARY:
  1050. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1051. R_SUBFLAGZERO:
  1052. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1053. R_SUBFLAGSIGN:
  1054. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1055. R_SUBFLAGOVERFLOW:
  1056. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1057. R_SUBFLAGINTERRUPT:
  1058. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1059. R_SUBFLAGDIRECTION:
  1060. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1061. else
  1062. internalerror(2017042602);
  1063. end;
  1064. exit;
  1065. end;
  1066. case taicpu(p1).opcode of
  1067. A_CALL:
  1068. { We could potentially set Result to False if the register in
  1069. question is non-volatile for the subroutine's calling convention,
  1070. but this would require detecting the calling convention in use and
  1071. also assuming that the routine doesn't contain malformed assembly
  1072. language, for example... so it could only be done under -O4 as it
  1073. would be considered a side-effect. [Kit] }
  1074. Result := True;
  1075. A_MOVSD:
  1076. { special handling for SSE MOVSD }
  1077. if (taicpu(p1).ops>0) then
  1078. begin
  1079. if taicpu(p1).ops<>2 then
  1080. internalerror(2017042703);
  1081. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1082. end;
  1083. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1084. so fix it here (FK)
  1085. }
  1086. A_VMOVSS,
  1087. A_VMOVSD:
  1088. begin
  1089. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1090. exit;
  1091. end;
  1092. A_MUL, A_DIV, A_IDIV:
  1093. begin
  1094. if taicpu(p1).opsize = S_B then
  1095. Result := (getsupreg(Reg) = RS_EAX)
  1096. else
  1097. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1098. end;
  1099. A_IMUL:
  1100. begin
  1101. if taicpu(p1).ops = 1 then
  1102. begin
  1103. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1104. end
  1105. else
  1106. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1107. Exit;
  1108. end;
  1109. else
  1110. ;
  1111. end;
  1112. if Result then
  1113. exit;
  1114. with insprop[taicpu(p1).opcode] do
  1115. begin
  1116. if getregtype(reg)=R_INTREGISTER then
  1117. begin
  1118. case getsupreg(reg) of
  1119. RS_EAX:
  1120. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1121. begin
  1122. Result := True;
  1123. exit
  1124. end;
  1125. RS_ECX:
  1126. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1127. begin
  1128. Result := True;
  1129. exit
  1130. end;
  1131. RS_EDX:
  1132. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1133. begin
  1134. Result := True;
  1135. exit
  1136. end;
  1137. RS_EBX:
  1138. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1139. begin
  1140. Result := True;
  1141. exit
  1142. end;
  1143. RS_ESP:
  1144. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1145. begin
  1146. Result := True;
  1147. exit
  1148. end;
  1149. RS_EBP:
  1150. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1151. begin
  1152. Result := True;
  1153. exit
  1154. end;
  1155. RS_ESI:
  1156. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1157. begin
  1158. Result := True;
  1159. exit
  1160. end;
  1161. RS_EDI:
  1162. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1163. begin
  1164. Result := True;
  1165. exit
  1166. end;
  1167. end;
  1168. end;
  1169. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1170. if (WriteOps[OperIdx]*Ch<>[]) and
  1171. { The register doesn't get modified inside a reference }
  1172. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1173. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1174. begin
  1175. Result := true;
  1176. exit
  1177. end;
  1178. end;
  1179. end;
  1180. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1181. const
  1182. WriteOps: array[0..3] of set of TInsChange =
  1183. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1184. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1185. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1186. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1187. var
  1188. X: Integer;
  1189. CurrentP1Size: asizeint;
  1190. begin
  1191. Result := (
  1192. (Ref.base <> NR_NO) and
  1193. {$ifdef x86_64}
  1194. (Ref.base <> NR_RIP) and
  1195. {$endif x86_64}
  1196. RegModifiedBetween(Ref.base, p1, p2)
  1197. ) or
  1198. (
  1199. (Ref.index <> NR_NO) and
  1200. (Ref.index <> Ref.base) and
  1201. RegModifiedBetween(Ref.index, p1, p2)
  1202. );
  1203. { Now check to see if the memory itself is written to }
  1204. if not Result then
  1205. begin
  1206. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1207. if p1.typ = ait_instruction then
  1208. begin
  1209. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1210. with insprop[taicpu(p1).opcode] do
  1211. for X := 0 to taicpu(p1).ops - 1 do
  1212. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1213. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1214. { Catch any potential overlaps }
  1215. (
  1216. (RefSize = 0) or
  1217. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1218. ) and
  1219. (
  1220. (CurrentP1Size = 0) or
  1221. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1222. ) and
  1223. { Reference is used, but does the instruction write to it? }
  1224. (
  1225. (Ch_All in Ch) or
  1226. ((WriteOps[X] * Ch) <> [])
  1227. ) then
  1228. begin
  1229. Result := True;
  1230. Break;
  1231. end;
  1232. end;
  1233. end;
  1234. end;
  1235. {$ifdef DEBUG_AOPTCPU}
  1236. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1237. begin
  1238. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1239. end;
  1240. function debug_tostr(i: tcgint): string; inline;
  1241. begin
  1242. Result := tostr(i);
  1243. end;
  1244. function debug_hexstr(i: tcgint): string;
  1245. begin
  1246. Result := '0x';
  1247. case i of
  1248. 0..$FF:
  1249. Result := Result + hexstr(i, 2);
  1250. $100..$FFFF:
  1251. Result := Result + hexstr(i, 4);
  1252. $10000..$FFFFFF:
  1253. Result := Result + hexstr(i, 6);
  1254. $1000000..$FFFFFFFF:
  1255. Result := Result + hexstr(i, 8);
  1256. else
  1257. Result := Result + hexstr(i, 16);
  1258. end;
  1259. end;
  1260. function debug_regname(r: TRegister): string; inline;
  1261. begin
  1262. Result := '%' + std_regname(r);
  1263. end;
  1264. { Debug output function - creates a string representation of an operator }
  1265. function debug_operstr(oper: TOper): string;
  1266. begin
  1267. case oper.typ of
  1268. top_const:
  1269. Result := '$' + debug_tostr(oper.val);
  1270. top_reg:
  1271. Result := debug_regname(oper.reg);
  1272. top_ref:
  1273. begin
  1274. if oper.ref^.offset <> 0 then
  1275. Result := debug_tostr(oper.ref^.offset) + '('
  1276. else
  1277. Result := '(';
  1278. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1279. begin
  1280. Result := Result + debug_regname(oper.ref^.base);
  1281. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1282. Result := Result + ',' + debug_regname(oper.ref^.index);
  1283. end
  1284. else
  1285. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1286. Result := Result + debug_regname(oper.ref^.index);
  1287. if (oper.ref^.scalefactor > 1) then
  1288. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1289. else
  1290. Result := Result + ')';
  1291. end;
  1292. else
  1293. Result := '[UNKNOWN]';
  1294. end;
  1295. end;
  1296. function debug_op2str(opcode: tasmop): string; inline;
  1297. begin
  1298. Result := std_op2str[opcode];
  1299. end;
  1300. function debug_opsize2str(opsize: topsize): string; inline;
  1301. begin
  1302. Result := gas_opsize2str[opsize];
  1303. end;
  1304. {$else DEBUG_AOPTCPU}
  1305. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1306. begin
  1307. end;
  1308. function debug_tostr(i: tcgint): string; inline;
  1309. begin
  1310. Result := '';
  1311. end;
  1312. function debug_hexstr(i: tcgint): string; inline;
  1313. begin
  1314. Result := '';
  1315. end;
  1316. function debug_regname(r: TRegister): string; inline;
  1317. begin
  1318. Result := '';
  1319. end;
  1320. function debug_operstr(oper: TOper): string; inline;
  1321. begin
  1322. Result := '';
  1323. end;
  1324. function debug_op2str(opcode: tasmop): string; inline;
  1325. begin
  1326. Result := '';
  1327. end;
  1328. function debug_opsize2str(opsize: topsize): string; inline;
  1329. begin
  1330. Result := '';
  1331. end;
  1332. {$endif DEBUG_AOPTCPU}
  1333. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1334. begin
  1335. {$ifdef x86_64}
  1336. { Always fine on x86-64 }
  1337. Result := True;
  1338. {$else x86_64}
  1339. Result :=
  1340. {$ifdef i8086}
  1341. (current_settings.cputype >= cpu_386) and
  1342. {$endif i8086}
  1343. (
  1344. { Always accept if optimising for size }
  1345. (cs_opt_size in current_settings.optimizerswitches) or
  1346. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1347. (current_settings.optimizecputype >= cpu_Pentium2)
  1348. );
  1349. {$endif x86_64}
  1350. end;
  1351. { Attempts to allocate a volatile integer register for use between p and hp,
  1352. using AUsedRegs for the current register usage information. Returns NR_NO
  1353. if no free register could be found }
  1354. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1355. var
  1356. RegSet: TCPURegisterSet;
  1357. CurrentSuperReg: Integer;
  1358. CurrentReg: TRegister;
  1359. Currentp: tai;
  1360. Breakout: Boolean;
  1361. begin
  1362. Result := NR_NO;
  1363. RegSet :=
  1364. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1365. current_procinfo.saved_regs_int;
  1366. (*
  1367. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1368. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1369. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1370. *)
  1371. for CurrentSuperReg in RegSet do
  1372. begin
  1373. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1374. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1375. {$if defined(i386) or defined(i8086)}
  1376. { If the target size is 8-bit, make sure we can actually encode it }
  1377. and (
  1378. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1379. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1380. )
  1381. {$endif i386 or i8086}
  1382. then
  1383. begin
  1384. Currentp := p;
  1385. Breakout := False;
  1386. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1387. begin
  1388. case Currentp.typ of
  1389. ait_instruction:
  1390. begin
  1391. if RegInInstruction(CurrentReg, Currentp) then
  1392. begin
  1393. Breakout := True;
  1394. Break;
  1395. end;
  1396. { Cannot allocate across an unconditional jump }
  1397. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1398. Exit;
  1399. end;
  1400. ait_marker:
  1401. { Don't try anything more if a marker is hit }
  1402. Exit;
  1403. ait_regalloc:
  1404. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1405. begin
  1406. Breakout := True;
  1407. Break;
  1408. end;
  1409. else
  1410. ;
  1411. end;
  1412. end;
  1413. if Breakout then
  1414. { Try the next register }
  1415. Continue;
  1416. { We have a free register available }
  1417. Result := CurrentReg;
  1418. if not DontAlloc then
  1419. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1420. Exit;
  1421. end;
  1422. end;
  1423. end;
  1424. { Attempts to allocate a volatile MM register for use between p and hp,
  1425. using AUsedRegs for the current register usage information. Returns NR_NO
  1426. if no free register could be found }
  1427. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1428. var
  1429. RegSet: TCPURegisterSet;
  1430. CurrentSuperReg: Integer;
  1431. CurrentReg: TRegister;
  1432. Currentp: tai;
  1433. Breakout: Boolean;
  1434. begin
  1435. Result := NR_NO;
  1436. RegSet :=
  1437. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1438. current_procinfo.saved_regs_mm;
  1439. for CurrentSuperReg in RegSet do
  1440. begin
  1441. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1442. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1443. begin
  1444. Currentp := p;
  1445. Breakout := False;
  1446. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1447. begin
  1448. case Currentp.typ of
  1449. ait_instruction:
  1450. begin
  1451. if RegInInstruction(CurrentReg, Currentp) then
  1452. begin
  1453. Breakout := True;
  1454. Break;
  1455. end;
  1456. { Cannot allocate across an unconditional jump }
  1457. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1458. Exit;
  1459. end;
  1460. ait_marker:
  1461. { Don't try anything more if a marker is hit }
  1462. Exit;
  1463. ait_regalloc:
  1464. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1465. begin
  1466. Breakout := True;
  1467. Break;
  1468. end;
  1469. else
  1470. ;
  1471. end;
  1472. end;
  1473. if Breakout then
  1474. { Try the next register }
  1475. Continue;
  1476. { We have a free register available }
  1477. Result := CurrentReg;
  1478. if not DontAlloc then
  1479. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1480. Exit;
  1481. end;
  1482. end;
  1483. end;
  1484. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1485. begin
  1486. if not SuperRegistersEqual(reg1,reg2) then
  1487. exit(false);
  1488. if getregtype(reg1)<>R_INTREGISTER then
  1489. exit(true); {because SuperRegisterEqual is true}
  1490. case getsubreg(reg1) of
  1491. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1492. higher, it preserves the high bits, so the new value depends on
  1493. reg2's previous value. In other words, it is equivalent to doing:
  1494. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1495. R_SUBL:
  1496. exit(getsubreg(reg2)=R_SUBL);
  1497. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1498. higher, it actually does a:
  1499. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1500. R_SUBH:
  1501. exit(getsubreg(reg2)=R_SUBH);
  1502. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1503. bits of reg2:
  1504. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1505. R_SUBW:
  1506. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1507. { a write to R_SUBD always overwrites every other subregister,
  1508. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1509. R_SUBD,
  1510. R_SUBQ:
  1511. exit(true);
  1512. else
  1513. internalerror(2017042801);
  1514. end;
  1515. end;
  1516. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1517. begin
  1518. if not SuperRegistersEqual(reg1,reg2) then
  1519. exit(false);
  1520. if getregtype(reg1)<>R_INTREGISTER then
  1521. exit(true); {because SuperRegisterEqual is true}
  1522. case getsubreg(reg1) of
  1523. R_SUBL:
  1524. exit(getsubreg(reg2)<>R_SUBH);
  1525. R_SUBH:
  1526. exit(getsubreg(reg2)<>R_SUBL);
  1527. R_SUBW,
  1528. R_SUBD,
  1529. R_SUBQ:
  1530. exit(true);
  1531. else
  1532. internalerror(2017042802);
  1533. end;
  1534. end;
  1535. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1536. var
  1537. hp1 : tai;
  1538. l : TCGInt;
  1539. begin
  1540. result:=false;
  1541. if not(GetNextInstruction(p, hp1)) then
  1542. exit;
  1543. { changes the code sequence
  1544. shr/sar const1, x
  1545. shl const2, x
  1546. to
  1547. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1548. if (taicpu(p).oper[0]^.typ = top_const) and
  1549. MatchInstruction(hp1,A_SHL,[]) and
  1550. (taicpu(hp1).oper[0]^.typ = top_const) and
  1551. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1552. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1553. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1554. begin
  1555. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1556. not(cs_opt_size in current_settings.optimizerswitches)
  1557. {$ifdef x86_64}
  1558. and (
  1559. (taicpu(p).opsize <> S_Q) or
  1560. { 64-bit AND can only store signed 32-bit immediates }
  1561. (taicpu(p).oper[0]^.val < 32)
  1562. )
  1563. {$endif x86_64}
  1564. then
  1565. begin
  1566. { shr/sar const1, %reg
  1567. shl const2, %reg
  1568. with const1 > const2 }
  1569. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1570. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1571. taicpu(hp1).opcode := A_AND;
  1572. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1573. case taicpu(p).opsize Of
  1574. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1575. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1576. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1577. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1578. else
  1579. Internalerror(2017050703)
  1580. end;
  1581. end
  1582. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1583. not(cs_opt_size in current_settings.optimizerswitches)
  1584. {$ifdef x86_64}
  1585. and (
  1586. (taicpu(p).opsize <> S_Q) or
  1587. { 64-bit AND can only store signed 32-bit immediates }
  1588. (taicpu(p).oper[0]^.val < 32)
  1589. )
  1590. {$endif x86_64}
  1591. then
  1592. begin
  1593. { shr/sar const1, %reg
  1594. shl const2, %reg
  1595. with const1 < const2 }
  1596. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1597. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1598. taicpu(p).opcode := A_AND;
  1599. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1600. case taicpu(p).opsize Of
  1601. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1602. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1603. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1604. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1605. else
  1606. Internalerror(2017050702)
  1607. end;
  1608. end
  1609. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val)
  1610. {$ifdef x86_64}
  1611. and (
  1612. (taicpu(p).opsize <> S_Q) or
  1613. { 64-bit AND can only store signed 32-bit immediates }
  1614. (taicpu(p).oper[0]^.val < 32)
  1615. )
  1616. {$endif x86_64}
  1617. then
  1618. begin
  1619. { shr/sar const1, %reg
  1620. shl const2, %reg
  1621. with const1 = const2 }
  1622. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1623. taicpu(p).opcode := A_AND;
  1624. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1625. case taicpu(p).opsize Of
  1626. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1627. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1628. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1629. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1630. else
  1631. Internalerror(2017050701)
  1632. end;
  1633. RemoveInstruction(hp1);
  1634. end;
  1635. end;
  1636. end;
  1637. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1638. var
  1639. opsize : topsize;
  1640. hp1, hp2 : tai;
  1641. tmpref : treference;
  1642. ShiftValue : Cardinal;
  1643. BaseValue : TCGInt;
  1644. begin
  1645. result:=false;
  1646. opsize:=taicpu(p).opsize;
  1647. { changes certain "imul const, %reg"'s to lea sequences }
  1648. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1649. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1650. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1651. if (taicpu(p).oper[0]^.val = 1) then
  1652. if (taicpu(p).ops = 2) then
  1653. { remove "imul $1, reg" }
  1654. begin
  1655. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1656. Result := RemoveCurrentP(p);
  1657. end
  1658. else
  1659. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1660. begin
  1661. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1662. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1663. asml.InsertAfter(hp1, p);
  1664. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1665. RemoveCurrentP(p, hp1);
  1666. Result := True;
  1667. end
  1668. else if ((taicpu(p).ops <= 2) or
  1669. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1670. not(cs_opt_size in current_settings.optimizerswitches) and
  1671. (not(GetNextInstruction(p, hp1)) or
  1672. not((tai(hp1).typ = ait_instruction) and
  1673. ((taicpu(hp1).opcode=A_Jcc) and
  1674. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1675. begin
  1676. {
  1677. imul X, reg1, reg2 to
  1678. lea (reg1,reg1,Y), reg2
  1679. shl ZZ,reg2
  1680. imul XX, reg1 to
  1681. lea (reg1,reg1,YY), reg1
  1682. shl ZZ,reg2
  1683. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1684. it does not exist as a separate optimization target in FPC though.
  1685. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1686. at most two zeros
  1687. }
  1688. reference_reset(tmpref,1,[]);
  1689. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1690. begin
  1691. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1692. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1693. TmpRef.base := taicpu(p).oper[1]^.reg;
  1694. TmpRef.index := taicpu(p).oper[1]^.reg;
  1695. if not(BaseValue in [3,5,9]) then
  1696. Internalerror(2018110101);
  1697. TmpRef.ScaleFactor := BaseValue-1;
  1698. if (taicpu(p).ops = 2) then
  1699. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1700. else
  1701. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1702. AsmL.InsertAfter(hp1,p);
  1703. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1704. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1705. RemoveCurrentP(p, hp1);
  1706. if ShiftValue>0 then
  1707. begin
  1708. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1709. AsmL.InsertAfter(hp2,hp1);
  1710. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1711. end;
  1712. Result := True;
  1713. end;
  1714. end;
  1715. end;
  1716. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1717. begin
  1718. Result := False;
  1719. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1720. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1721. begin
  1722. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1723. taicpu(p).opcode := A_MOV;
  1724. Result := True;
  1725. end;
  1726. end;
  1727. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1728. var
  1729. p: taicpu absolute hp; { Implicit typecast }
  1730. i: Integer;
  1731. begin
  1732. Result := False;
  1733. if not assigned(hp) or
  1734. (hp.typ <> ait_instruction) then
  1735. Exit;
  1736. Prefetch(insprop[p.opcode]);
  1737. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1738. with insprop[p.opcode] do
  1739. begin
  1740. case getsubreg(reg) of
  1741. R_SUBW,R_SUBD,R_SUBQ:
  1742. Result:=
  1743. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1744. uncommon flags are checked first }
  1745. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1746. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1747. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1748. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1749. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1750. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1751. R_SUBFLAGCARRY:
  1752. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1753. R_SUBFLAGPARITY:
  1754. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1755. R_SUBFLAGAUXILIARY:
  1756. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1757. R_SUBFLAGZERO:
  1758. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1759. R_SUBFLAGSIGN:
  1760. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1761. R_SUBFLAGOVERFLOW:
  1762. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1763. R_SUBFLAGINTERRUPT:
  1764. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1765. R_SUBFLAGDIRECTION:
  1766. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1767. else
  1768. internalerror(2017050501);
  1769. end;
  1770. exit;
  1771. end;
  1772. { Handle special cases first }
  1773. case p.opcode of
  1774. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1775. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1776. begin
  1777. Result :=
  1778. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1779. (p.oper[1]^.typ = top_reg) and
  1780. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1781. (
  1782. (p.oper[0]^.typ = top_const) or
  1783. (
  1784. (p.oper[0]^.typ = top_reg) and
  1785. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1786. ) or (
  1787. (p.oper[0]^.typ = top_ref) and
  1788. not RegInRef(reg,p.oper[0]^.ref^)
  1789. )
  1790. );
  1791. end;
  1792. A_MUL, A_IMUL:
  1793. Result :=
  1794. (
  1795. (p.ops=3) and { IMUL only }
  1796. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1797. (
  1798. (
  1799. (p.oper[1]^.typ=top_reg) and
  1800. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1801. ) or (
  1802. (p.oper[1]^.typ=top_ref) and
  1803. not RegInRef(reg,p.oper[1]^.ref^)
  1804. )
  1805. )
  1806. ) or (
  1807. (
  1808. (p.ops=1) and
  1809. (
  1810. (
  1811. (
  1812. (p.oper[0]^.typ=top_reg) and
  1813. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1814. )
  1815. ) or (
  1816. (p.oper[0]^.typ=top_ref) and
  1817. not RegInRef(reg,p.oper[0]^.ref^)
  1818. )
  1819. ) and (
  1820. (
  1821. (p.opsize=S_B) and
  1822. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1823. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1824. ) or (
  1825. (p.opsize=S_W) and
  1826. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1827. ) or (
  1828. (p.opsize=S_L) and
  1829. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1830. {$ifdef x86_64}
  1831. ) or (
  1832. (p.opsize=S_Q) and
  1833. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1834. {$endif x86_64}
  1835. )
  1836. )
  1837. )
  1838. );
  1839. A_CBW:
  1840. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1841. {$ifndef x86_64}
  1842. A_LDS:
  1843. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1844. A_LES:
  1845. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1846. {$endif not x86_64}
  1847. A_LFS:
  1848. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1849. A_LGS:
  1850. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1851. A_LSS:
  1852. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1853. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1854. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1855. A_LODSB:
  1856. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1857. A_LODSW:
  1858. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1859. {$ifdef x86_64}
  1860. A_LODSQ:
  1861. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1862. {$endif x86_64}
  1863. A_LODSD:
  1864. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1865. A_FSTSW, A_FNSTSW:
  1866. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1867. else
  1868. begin
  1869. with insprop[p.opcode] do
  1870. begin
  1871. if (
  1872. { xor %reg,%reg etc. is classed as a new value }
  1873. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1874. MatchOpType(p, top_reg, top_reg) and
  1875. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1876. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1877. ) then
  1878. begin
  1879. Result := True;
  1880. Exit;
  1881. end;
  1882. { Make sure the entire register is overwritten }
  1883. if (getregtype(reg) = R_INTREGISTER) then
  1884. begin
  1885. if (p.ops > 0) then
  1886. begin
  1887. if RegInOp(reg, p.oper[0]^) then
  1888. begin
  1889. if (p.oper[0]^.typ = top_ref) then
  1890. begin
  1891. if RegInRef(reg, p.oper[0]^.ref^) then
  1892. begin
  1893. Result := False;
  1894. Exit;
  1895. end;
  1896. end
  1897. else if (p.oper[0]^.typ = top_reg) then
  1898. begin
  1899. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1900. begin
  1901. Result := False;
  1902. Exit;
  1903. end
  1904. else if ([Ch_WOp1]*Ch<>[]) then
  1905. begin
  1906. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1907. Result := True
  1908. else
  1909. begin
  1910. Result := False;
  1911. Exit;
  1912. end;
  1913. end;
  1914. end;
  1915. end;
  1916. if (p.ops > 1) then
  1917. begin
  1918. if RegInOp(reg, p.oper[1]^) then
  1919. begin
  1920. if (p.oper[1]^.typ = top_ref) then
  1921. begin
  1922. if RegInRef(reg, p.oper[1]^.ref^) then
  1923. begin
  1924. Result := False;
  1925. Exit;
  1926. end;
  1927. end
  1928. else if (p.oper[1]^.typ = top_reg) then
  1929. begin
  1930. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1931. begin
  1932. Result := False;
  1933. Exit;
  1934. end
  1935. else if ([Ch_WOp2]*Ch<>[]) then
  1936. begin
  1937. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1938. Result := True
  1939. else
  1940. begin
  1941. Result := False;
  1942. Exit;
  1943. end;
  1944. end;
  1945. end;
  1946. end;
  1947. if (p.ops > 2) then
  1948. begin
  1949. if RegInOp(reg, p.oper[2]^) then
  1950. begin
  1951. if (p.oper[2]^.typ = top_ref) then
  1952. begin
  1953. if RegInRef(reg, p.oper[2]^.ref^) then
  1954. begin
  1955. Result := False;
  1956. Exit;
  1957. end;
  1958. end
  1959. else if (p.oper[2]^.typ = top_reg) then
  1960. begin
  1961. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1962. begin
  1963. Result := False;
  1964. Exit;
  1965. end
  1966. else if ([Ch_WOp3]*Ch<>[]) then
  1967. begin
  1968. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1969. Result := True
  1970. else
  1971. begin
  1972. Result := False;
  1973. Exit;
  1974. end;
  1975. end;
  1976. end;
  1977. end;
  1978. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1979. begin
  1980. if (p.oper[3]^.typ = top_ref) then
  1981. begin
  1982. if RegInRef(reg, p.oper[3]^.ref^) then
  1983. begin
  1984. Result := False;
  1985. Exit;
  1986. end;
  1987. end
  1988. else if (p.oper[3]^.typ = top_reg) then
  1989. begin
  1990. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1991. begin
  1992. Result := False;
  1993. Exit;
  1994. end
  1995. else if ([Ch_WOp4]*Ch<>[]) then
  1996. begin
  1997. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1998. Result := True
  1999. else
  2000. begin
  2001. Result := False;
  2002. Exit;
  2003. end;
  2004. end;
  2005. end;
  2006. end;
  2007. end;
  2008. end;
  2009. end;
  2010. { Don't do these ones first in case an input operand is equal to an explicit output register }
  2011. case getsupreg(reg) of
  2012. RS_EAX:
  2013. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  2014. begin
  2015. Result := True;
  2016. Exit;
  2017. end;
  2018. RS_ECX:
  2019. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  2020. begin
  2021. Result := True;
  2022. Exit;
  2023. end;
  2024. RS_EDX:
  2025. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2026. begin
  2027. Result := True;
  2028. Exit;
  2029. end;
  2030. RS_EBX:
  2031. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2032. begin
  2033. Result := True;
  2034. Exit;
  2035. end;
  2036. RS_ESP:
  2037. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2038. begin
  2039. Result := True;
  2040. Exit;
  2041. end;
  2042. RS_EBP:
  2043. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2044. begin
  2045. Result := True;
  2046. Exit;
  2047. end;
  2048. RS_ESI:
  2049. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2050. begin
  2051. Result := True;
  2052. Exit;
  2053. end;
  2054. RS_EDI:
  2055. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2056. begin
  2057. Result := True;
  2058. Exit;
  2059. end;
  2060. else
  2061. ;
  2062. end;
  2063. end;
  2064. end;
  2065. end;
  2066. end;
  2067. end;
  2068. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2069. var
  2070. hp2,hp3 : tai;
  2071. begin
  2072. { some x86-64 issue a NOP before the real exit code }
  2073. if MatchInstruction(p,A_NOP,[]) then
  2074. GetNextInstruction(p,p);
  2075. result:=assigned(p) and (p.typ=ait_instruction) and
  2076. ((taicpu(p).opcode = A_RET) or
  2077. ((taicpu(p).opcode=A_LEAVE) and
  2078. GetNextInstruction(p,hp2) and
  2079. MatchInstruction(hp2,A_RET,[S_NO])
  2080. ) or
  2081. (((taicpu(p).opcode=A_LEA) and
  2082. MatchOpType(taicpu(p),top_ref,top_reg) and
  2083. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2084. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2085. ) and
  2086. GetNextInstruction(p,hp2) and
  2087. MatchInstruction(hp2,A_RET,[S_NO])
  2088. ) or
  2089. ((((taicpu(p).opcode=A_MOV) and
  2090. MatchOpType(taicpu(p),top_reg,top_reg) and
  2091. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2092. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2093. ((taicpu(p).opcode=A_LEA) and
  2094. MatchOpType(taicpu(p),top_ref,top_reg) and
  2095. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2096. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2097. )
  2098. ) and
  2099. GetNextInstruction(p,hp2) and
  2100. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2101. MatchOpType(taicpu(hp2),top_reg) and
  2102. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2103. GetNextInstruction(hp2,hp3) and
  2104. MatchInstruction(hp3,A_RET,[S_NO])
  2105. )
  2106. );
  2107. end;
  2108. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2109. begin
  2110. isFoldableArithOp := False;
  2111. case hp1.opcode of
  2112. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2113. isFoldableArithOp :=
  2114. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2115. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2116. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2117. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2118. (taicpu(hp1).oper[1]^.reg = reg);
  2119. A_INC,A_DEC,A_NEG,A_NOT:
  2120. isFoldableArithOp :=
  2121. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2122. (taicpu(hp1).oper[0]^.reg = reg);
  2123. else
  2124. ;
  2125. end;
  2126. end;
  2127. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2128. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2129. var
  2130. hp2: tai;
  2131. begin
  2132. hp2 := p;
  2133. repeat
  2134. hp2 := tai(hp2.previous);
  2135. if assigned(hp2) and
  2136. (hp2.typ = ait_regalloc) and
  2137. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2138. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2139. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2140. begin
  2141. RemoveInstruction(hp2);
  2142. break;
  2143. end;
  2144. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2145. end;
  2146. begin
  2147. case current_procinfo.procdef.returndef.typ of
  2148. arraydef,recorddef,pointerdef,
  2149. stringdef,enumdef,procdef,objectdef,errordef,
  2150. filedef,setdef,procvardef,
  2151. classrefdef,forwarddef:
  2152. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2153. orddef:
  2154. if current_procinfo.procdef.returndef.size <> 0 then
  2155. begin
  2156. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2157. { for int64/qword }
  2158. if current_procinfo.procdef.returndef.size = 8 then
  2159. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2160. end;
  2161. else
  2162. ;
  2163. end;
  2164. end;
  2165. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2166. var
  2167. hp1: tai;
  2168. operswap: poper;
  2169. begin
  2170. Result := False;
  2171. { Optimise:
  2172. cmov(c) %reg1,%reg2
  2173. mov %reg2,%reg1
  2174. (%reg2 dealloc.)
  2175. To:
  2176. cmov(~c) %reg2,%reg1
  2177. }
  2178. if (taicpu(p).oper[0]^.typ = top_reg) then
  2179. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2180. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2181. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2182. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2183. begin
  2184. TransferUsedRegs(TmpUsedRegs);
  2185. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2186. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2187. begin
  2188. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2189. { Save time by swapping the pointers (they're both registers, so
  2190. we don't need to worry about reference counts) }
  2191. operswap := taicpu(p).oper[0];
  2192. taicpu(p).oper[0] := taicpu(p).oper[1];
  2193. taicpu(p).oper[1] := operswap;
  2194. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2195. RemoveInstruction(hp1);
  2196. { It's still a CMOV, so we can look further ahead }
  2197. Include(OptsToCheck, aoc_ForceNewIteration);
  2198. { But first, let's see if this will get optimised again
  2199. (probably won't happen, but best to be sure) }
  2200. Continue;
  2201. end;
  2202. Break;
  2203. end;
  2204. end;
  2205. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2206. var
  2207. hp1,hp2 : tai;
  2208. begin
  2209. result:=false;
  2210. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2211. begin
  2212. { vmova* reg1,reg1
  2213. =>
  2214. <nop> }
  2215. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2216. begin
  2217. RemoveCurrentP(p);
  2218. result:=true;
  2219. exit;
  2220. end;
  2221. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2222. (hp1.typ = ait_instruction) and
  2223. (
  2224. { Under -O2 and below, the instructions are always adjacent }
  2225. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2226. (taicpu(hp1).ops <= 1) or
  2227. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2228. { If reg1 = reg3, reg1 must not be modified in between }
  2229. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2230. ) then
  2231. begin
  2232. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2233. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2234. begin
  2235. { vmova* reg1,reg2
  2236. ...
  2237. vmova* reg2,reg3
  2238. dealloc reg2
  2239. =>
  2240. vmova* reg1,reg3 }
  2241. TransferUsedRegs(TmpUsedRegs);
  2242. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2243. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2244. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2245. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2246. begin
  2247. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2248. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2249. TransferUsedRegs(TmpUsedRegs);
  2250. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2251. RemoveInstruction(hp1);
  2252. result:=true;
  2253. exit;
  2254. end;
  2255. { special case:
  2256. vmova* reg1,<op>
  2257. ...
  2258. vmova* <op>,reg1
  2259. =>
  2260. vmova* reg1,<op> }
  2261. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2262. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2263. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2264. ) then
  2265. begin
  2266. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2267. RemoveInstruction(hp1);
  2268. result:=true;
  2269. exit;
  2270. end
  2271. end
  2272. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2273. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2274. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2275. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2276. ) and
  2277. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2278. begin
  2279. { vmova* reg1,reg2
  2280. ...
  2281. vmovs* reg2,<op>
  2282. dealloc reg2
  2283. =>
  2284. vmovs* reg1,<op> }
  2285. TransferUsedRegs(TmpUsedRegs);
  2286. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2287. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2288. begin
  2289. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2290. taicpu(p).opcode:=taicpu(hp1).opcode;
  2291. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2292. TransferUsedRegs(TmpUsedRegs);
  2293. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2294. RemoveInstruction(hp1);
  2295. result:=true;
  2296. exit;
  2297. end
  2298. end;
  2299. if MatchInstruction(hp1,[A_VFMADDPD,
  2300. A_VFMADD132PD,
  2301. A_VFMADD132PS,
  2302. A_VFMADD132SD,
  2303. A_VFMADD132SS,
  2304. A_VFMADD213PD,
  2305. A_VFMADD213PS,
  2306. A_VFMADD213SD,
  2307. A_VFMADD213SS,
  2308. A_VFMADD231PD,
  2309. A_VFMADD231PS,
  2310. A_VFMADD231SD,
  2311. A_VFMADD231SS,
  2312. A_VFMADDSUB132PD,
  2313. A_VFMADDSUB132PS,
  2314. A_VFMADDSUB213PD,
  2315. A_VFMADDSUB213PS,
  2316. A_VFMADDSUB231PD,
  2317. A_VFMADDSUB231PS,
  2318. A_VFMSUB132PD,
  2319. A_VFMSUB132PS,
  2320. A_VFMSUB132SD,
  2321. A_VFMSUB132SS,
  2322. A_VFMSUB213PD,
  2323. A_VFMSUB213PS,
  2324. A_VFMSUB213SD,
  2325. A_VFMSUB213SS,
  2326. A_VFMSUB231PD,
  2327. A_VFMSUB231PS,
  2328. A_VFMSUB231SD,
  2329. A_VFMSUB231SS,
  2330. A_VFMSUBADD132PD,
  2331. A_VFMSUBADD132PS,
  2332. A_VFMSUBADD213PD,
  2333. A_VFMSUBADD213PS,
  2334. A_VFMSUBADD231PD,
  2335. A_VFMSUBADD231PS,
  2336. A_VFNMADD132PD,
  2337. A_VFNMADD132PS,
  2338. A_VFNMADD132SD,
  2339. A_VFNMADD132SS,
  2340. A_VFNMADD213PD,
  2341. A_VFNMADD213PS,
  2342. A_VFNMADD213SD,
  2343. A_VFNMADD213SS,
  2344. A_VFNMADD231PD,
  2345. A_VFNMADD231PS,
  2346. A_VFNMADD231SD,
  2347. A_VFNMADD231SS,
  2348. A_VFNMSUB132PD,
  2349. A_VFNMSUB132PS,
  2350. A_VFNMSUB132SD,
  2351. A_VFNMSUB132SS,
  2352. A_VFNMSUB213PD,
  2353. A_VFNMSUB213PS,
  2354. A_VFNMSUB213SD,
  2355. A_VFNMSUB213SS,
  2356. A_VFNMSUB231PD,
  2357. A_VFNMSUB231PS,
  2358. A_VFNMSUB231SD,
  2359. A_VFNMSUB231SS],[S_NO]) and
  2360. { we mix single and double opperations here because we assume that the compiler
  2361. generates vmovapd only after double operations and vmovaps only after single operations }
  2362. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2363. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2364. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2365. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2366. begin
  2367. TransferUsedRegs(TmpUsedRegs);
  2368. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2369. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2370. begin
  2371. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2372. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2373. RemoveCurrentP(p)
  2374. else
  2375. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2376. RemoveInstruction(hp2);
  2377. end;
  2378. end
  2379. else if (hp1.typ = ait_instruction) and
  2380. (((taicpu(p).opcode=A_MOVAPS) and
  2381. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2382. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2383. ((taicpu(p).opcode=A_MOVAPD) and
  2384. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2385. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2386. ) and
  2387. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2388. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2389. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2390. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2391. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2392. { change
  2393. movapX reg,reg2
  2394. addsX/subsX/... reg3, reg2
  2395. movapX reg2,reg
  2396. to
  2397. addsX/subsX/... reg3,reg
  2398. }
  2399. begin
  2400. TransferUsedRegs(TmpUsedRegs);
  2401. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2402. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2403. begin
  2404. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2405. debug_op2str(taicpu(p).opcode)+' '+
  2406. debug_op2str(taicpu(hp1).opcode)+' '+
  2407. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2408. { we cannot eliminate the first move if
  2409. the operations uses the same register for source and dest }
  2410. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2411. { Remember that hp1 is not necessarily the immediate
  2412. next instruction }
  2413. RemoveCurrentP(p);
  2414. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2415. RemoveInstruction(hp2);
  2416. result:=true;
  2417. end;
  2418. end
  2419. else if (hp1.typ = ait_instruction) and
  2420. (((taicpu(p).opcode=A_VMOVAPD) and
  2421. (taicpu(hp1).opcode=A_VCOMISD)) or
  2422. ((taicpu(p).opcode=A_VMOVAPS) and
  2423. ((taicpu(hp1).opcode=A_VCOMISS))
  2424. )
  2425. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2426. { change
  2427. movapX reg,reg1
  2428. vcomisX reg1,reg1
  2429. to
  2430. vcomisX reg,reg
  2431. }
  2432. begin
  2433. TransferUsedRegs(TmpUsedRegs);
  2434. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2435. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2436. begin
  2437. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2438. debug_op2str(taicpu(p).opcode)+' '+
  2439. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2440. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2441. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2442. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2443. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2444. RemoveCurrentP(p);
  2445. result:=true;
  2446. exit;
  2447. end;
  2448. end
  2449. end;
  2450. end;
  2451. end;
  2452. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2453. var
  2454. hp1 : tai;
  2455. begin
  2456. result:=false;
  2457. { replace
  2458. V<Op>X %mreg1,%mreg2,%mreg3
  2459. VMovX %mreg3,%mreg4
  2460. dealloc %mreg3
  2461. by
  2462. V<Op>X %mreg1,%mreg2,%mreg4
  2463. ?
  2464. }
  2465. if GetNextInstruction(p,hp1) and
  2466. { we mix single and double operations here because we assume that the compiler
  2467. generates vmovapd only after double operations and vmovaps only after single operations }
  2468. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2469. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2470. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2471. begin
  2472. TransferUsedRegs(TmpUsedRegs);
  2473. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2474. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2475. begin
  2476. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2477. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2478. RemoveInstruction(hp1);
  2479. result:=true;
  2480. end;
  2481. end;
  2482. end;
  2483. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2484. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2485. begin
  2486. Result := False;
  2487. { For safety reasons, only check for exact register matches }
  2488. { Check base register }
  2489. if (ref.base = AOldReg) then
  2490. begin
  2491. ref.base := ANewReg;
  2492. Result := True;
  2493. end;
  2494. { Check index register }
  2495. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2496. begin
  2497. ref.index := ANewReg;
  2498. Result := True;
  2499. end;
  2500. end;
  2501. { Replaces all references to AOldReg in an operand to ANewReg }
  2502. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2503. var
  2504. OldSupReg, NewSupReg: TSuperRegister;
  2505. OldSubReg, NewSubReg: TSubRegister;
  2506. OldRegType: TRegisterType;
  2507. ThisOper: POper;
  2508. begin
  2509. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2510. Result := False;
  2511. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2512. InternalError(2020011801);
  2513. OldSupReg := getsupreg(AOldReg);
  2514. OldSubReg := getsubreg(AOldReg);
  2515. OldRegType := getregtype(AOldReg);
  2516. NewSupReg := getsupreg(ANewReg);
  2517. NewSubReg := getsubreg(ANewReg);
  2518. if OldRegType <> getregtype(ANewReg) then
  2519. InternalError(2020011802);
  2520. if OldSubReg <> NewSubReg then
  2521. InternalError(2020011803);
  2522. case ThisOper^.typ of
  2523. top_reg:
  2524. if (
  2525. (ThisOper^.reg = AOldReg) or
  2526. (
  2527. (OldRegType = R_INTREGISTER) and
  2528. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2529. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2530. (
  2531. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2532. {$ifndef x86_64}
  2533. and (
  2534. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2535. don't have an 8-bit representation }
  2536. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2537. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2538. )
  2539. {$endif x86_64}
  2540. )
  2541. )
  2542. ) then
  2543. begin
  2544. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2545. Result := True;
  2546. end;
  2547. top_ref:
  2548. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2549. Result := True;
  2550. else
  2551. ;
  2552. end;
  2553. end;
  2554. { Replaces all references to AOldReg in an instruction to ANewReg }
  2555. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2556. const
  2557. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2558. var
  2559. OperIdx: Integer;
  2560. begin
  2561. Result := False;
  2562. for OperIdx := 0 to p.ops - 1 do
  2563. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2564. begin
  2565. { The shift and rotate instructions can only use CL }
  2566. if not (
  2567. (OperIdx = 0) and
  2568. { This second condition just helps to avoid unnecessarily
  2569. calling MatchInstruction for 10 different opcodes }
  2570. (p.oper[0]^.reg = NR_CL) and
  2571. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2572. ) then
  2573. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2574. end
  2575. else if p.oper[OperIdx]^.typ = top_ref then
  2576. { It's okay to replace registers in references that get written to }
  2577. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2578. end;
  2579. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2580. begin
  2581. Result :=
  2582. (ref^.index = NR_NO) and
  2583. (
  2584. {$ifdef x86_64}
  2585. (
  2586. (ref^.base = NR_RIP) and
  2587. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2588. ) or
  2589. {$endif x86_64}
  2590. (ref^.refaddr = addr_full) or
  2591. (ref^.base = NR_STACK_POINTER_REG) or
  2592. (ref^.base = current_procinfo.framepointer)
  2593. );
  2594. end;
  2595. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2596. var
  2597. l: asizeint;
  2598. begin
  2599. Result := False;
  2600. { Should have been checked previously }
  2601. if p.opcode <> A_LEA then
  2602. InternalError(2020072501);
  2603. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2604. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2605. not(cs_opt_size in current_settings.optimizerswitches) then
  2606. exit;
  2607. with p.oper[0]^.ref^ do
  2608. begin
  2609. if (base <> p.oper[1]^.reg) or
  2610. (index <> NR_NO) or
  2611. assigned(symbol) then
  2612. exit;
  2613. l:=offset;
  2614. if (l=1) and UseIncDec then
  2615. begin
  2616. p.opcode:=A_INC;
  2617. p.loadreg(0,p.oper[1]^.reg);
  2618. p.ops:=1;
  2619. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2620. end
  2621. else if (l=-1) and UseIncDec then
  2622. begin
  2623. p.opcode:=A_DEC;
  2624. p.loadreg(0,p.oper[1]^.reg);
  2625. p.ops:=1;
  2626. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2627. end
  2628. else
  2629. begin
  2630. if (l<0) and (l<>-2147483648) then
  2631. begin
  2632. p.opcode:=A_SUB;
  2633. p.loadConst(0,-l);
  2634. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2635. end
  2636. else
  2637. begin
  2638. p.opcode:=A_ADD;
  2639. p.loadConst(0,l);
  2640. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2641. end;
  2642. end;
  2643. end;
  2644. Result := True;
  2645. end;
  2646. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2647. var
  2648. CurrentReg, ReplaceReg: TRegister;
  2649. begin
  2650. Result := False;
  2651. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2652. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2653. case hp.opcode of
  2654. A_FSTSW, A_FNSTSW,
  2655. A_IN, A_INS, A_OUT, A_OUTS,
  2656. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2657. { These routines have explicit operands, but they are restricted in
  2658. what they can be (e.g. IN and OUT can only read from AL, AX or
  2659. EAX. }
  2660. Exit;
  2661. A_IMUL:
  2662. begin
  2663. { The 1-operand version writes to implicit registers
  2664. The 2-operand version reads from the first operator, and reads
  2665. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2666. the 3-operand version reads from a register that it doesn't write to
  2667. }
  2668. case hp.ops of
  2669. 1:
  2670. if (
  2671. (
  2672. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2673. ) or
  2674. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2675. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2676. begin
  2677. Result := True;
  2678. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2679. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2680. end;
  2681. 2:
  2682. { Only modify the first parameter }
  2683. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2684. begin
  2685. Result := True;
  2686. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2687. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2688. end;
  2689. 3:
  2690. { Only modify the second parameter }
  2691. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2692. begin
  2693. Result := True;
  2694. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2695. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2696. end;
  2697. else
  2698. InternalError(2020012901);
  2699. end;
  2700. end;
  2701. else
  2702. if (hp.ops > 0) and
  2703. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2704. begin
  2705. Result := True;
  2706. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2707. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2708. end;
  2709. end;
  2710. end;
  2711. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2712. var
  2713. hp2, hp_regalloc: tai;
  2714. p_SourceReg, p_TargetReg: TRegister;
  2715. begin
  2716. Result := False;
  2717. { Backward optimisation. If we have:
  2718. func. %reg1,%reg2
  2719. mov %reg2,%reg3
  2720. (dealloc %reg2)
  2721. Change to:
  2722. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2723. Perform similar optimisations with 1, 3 and 4-operand instructions
  2724. that only have one output.
  2725. }
  2726. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2727. begin
  2728. p_SourceReg := taicpu(p).oper[0]^.reg;
  2729. p_TargetReg := taicpu(p).oper[1]^.reg;
  2730. TransferUsedRegs(TmpUsedRegs);
  2731. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2732. GetLastInstruction(p, hp2) and
  2733. (hp2.typ = ait_instruction) and
  2734. { Have to make sure it's an instruction that only reads from
  2735. the first operands and only writes (not reads or modifies) to
  2736. the last one; in essence, a pure function such as BSR, POPCNT
  2737. or ANDN }
  2738. (
  2739. (
  2740. (taicpu(hp2).ops = 1) and
  2741. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2742. ) or
  2743. (
  2744. (taicpu(hp2).ops = 2) and
  2745. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2746. ) or
  2747. (
  2748. (taicpu(hp2).ops = 3) and
  2749. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2750. ) or
  2751. (
  2752. (taicpu(hp2).ops = 4) and
  2753. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2754. )
  2755. ) and
  2756. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2757. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2758. begin
  2759. case taicpu(hp2).opcode of
  2760. A_FSTSW, A_FNSTSW,
  2761. A_IN, A_INS, A_OUT, A_OUTS,
  2762. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2763. { These routines have explicit operands, but they are restricted in
  2764. what they can be (e.g. IN and OUT can only read from AL, AX or
  2765. EAX. }
  2766. ;
  2767. else
  2768. begin
  2769. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2770. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2771. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2772. if Assigned(hp_regalloc) then
  2773. begin
  2774. Asml.Remove(hp_regalloc);
  2775. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2776. begin
  2777. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2778. hp_regalloc.Free;
  2779. end
  2780. else
  2781. { If the register is not explicitly deallocated, it's
  2782. being reused, so move the allocation to after func. }
  2783. AsmL.InsertAfter(hp_regalloc, hp2);
  2784. end;
  2785. if not RegInInstruction(p_TargetReg, hp2) then
  2786. begin
  2787. TransferUsedRegs(TmpUsedRegs);
  2788. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2789. end;
  2790. { Actually make the changes }
  2791. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2792. RemoveCurrentp(p, hp1);
  2793. { If the Func was another MOV instruction, we might get
  2794. "mov %reg,%reg" that doesn't get removed in Pass 2
  2795. otherwise, so deal with it here (also do something
  2796. similar with lea (%reg),%reg}
  2797. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2798. begin
  2799. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2800. if p = hp2 then
  2801. RemoveCurrentp(p)
  2802. else
  2803. RemoveInstruction(hp2);
  2804. end;
  2805. Result := True;
  2806. Exit;
  2807. end;
  2808. end;
  2809. end;
  2810. end;
  2811. end;
  2812. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2813. begin
  2814. Result := False;
  2815. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2816. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2817. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2818. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2819. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2820. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2821. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2822. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2823. begin
  2824. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2825. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2826. Result := True;
  2827. Include(OptsToCheck, aoc_ForceNewIteration);
  2828. end;
  2829. end;
  2830. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2831. var
  2832. hp1, hp2, hp3, hp4: tai;
  2833. DoOptimisation, TempBool: Boolean;
  2834. {$ifdef x86_64}
  2835. NewConst: TCGInt;
  2836. {$endif x86_64}
  2837. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2838. begin
  2839. if taicpu(hp1).opcode = signed_movop then
  2840. begin
  2841. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2842. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2843. end
  2844. else
  2845. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2846. end;
  2847. function TryConstMerge(var p1, p2: tai): Boolean;
  2848. var
  2849. ThisRef: TReference;
  2850. begin
  2851. Result := False;
  2852. ThisRef := taicpu(p2).oper[1]^.ref^;
  2853. { Only permit writes to the stack, since we can guarantee alignment with that }
  2854. if (ThisRef.index = NR_NO) and
  2855. (
  2856. (ThisRef.base = NR_STACK_POINTER_REG) or
  2857. (ThisRef.base = current_procinfo.framepointer)
  2858. ) then
  2859. begin
  2860. case taicpu(p).opsize of
  2861. S_B:
  2862. begin
  2863. { Word writes must be on a 2-byte boundary }
  2864. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2865. begin
  2866. { Reduce offset of second reference to see if it is sequential with the first }
  2867. Dec(ThisRef.offset, 1);
  2868. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2869. begin
  2870. { Make sure the constants aren't represented as a
  2871. negative number, as these won't merge properly }
  2872. taicpu(p1).opsize := S_W;
  2873. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2874. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2875. RemoveInstruction(p2);
  2876. Result := True;
  2877. end;
  2878. end;
  2879. end;
  2880. S_W:
  2881. begin
  2882. { Longword writes must be on a 4-byte boundary }
  2883. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2884. begin
  2885. { Reduce offset of second reference to see if it is sequential with the first }
  2886. Dec(ThisRef.offset, 2);
  2887. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2888. begin
  2889. { Make sure the constants aren't represented as a
  2890. negative number, as these won't merge properly }
  2891. taicpu(p1).opsize := S_L;
  2892. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2893. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2894. RemoveInstruction(p2);
  2895. Result := True;
  2896. end;
  2897. end;
  2898. end;
  2899. {$ifdef x86_64}
  2900. S_L:
  2901. begin
  2902. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2903. see if the constants can be encoded this way. }
  2904. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2905. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2906. { Quadword writes must be on an 8-byte boundary }
  2907. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2908. begin
  2909. { Reduce offset of second reference to see if it is sequential with the first }
  2910. Dec(ThisRef.offset, 4);
  2911. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2912. begin
  2913. { Make sure the constants aren't represented as a
  2914. negative number, as these won't merge properly }
  2915. taicpu(p1).opsize := S_Q;
  2916. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2917. taicpu(p1).oper[0]^.val := NewConst;
  2918. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2919. RemoveInstruction(p2);
  2920. Result := True;
  2921. end;
  2922. end;
  2923. end;
  2924. {$endif x86_64}
  2925. else
  2926. ;
  2927. end;
  2928. end;
  2929. end;
  2930. var
  2931. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2932. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2933. NewSize: topsize; NewOffset: asizeint;
  2934. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2935. SourceRef, TargetRef: TReference;
  2936. MovAligned, MovUnaligned: TAsmOp;
  2937. ThisRef: TReference;
  2938. JumpTracking: TLinkedList;
  2939. begin
  2940. Result:=false;
  2941. { remove mov reg1,reg1? }
  2942. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2943. then
  2944. begin
  2945. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2946. { take care of the register (de)allocs following p }
  2947. RemoveCurrentP(p);
  2948. Result := True;
  2949. exit;
  2950. end;
  2951. { Prevent compiler warnings }
  2952. p_SourceReg := NR_NO;
  2953. p_TargetReg := NR_NO;
  2954. if taicpu(p).oper[1]^.typ = top_reg then
  2955. begin
  2956. { Saves on a large number of dereferences }
  2957. p_TargetReg := taicpu(p).oper[1]^.reg;
  2958. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2959. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_TargetReg)
  2960. else
  2961. GetNextInstruction_p := GetNextInstruction(p, hp1);
  2962. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  2963. while True do
  2964. begin
  2965. if (taicpu(hp1).opcode = A_AND) and
  2966. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2967. begin
  2968. { A change has occurred, just not in p }
  2969. Include(OptsToCheck, aoc_ForceNewIteration);
  2970. if MatchOperand(taicpu(hp1).oper[1]^, p_TargetReg) then
  2971. begin
  2972. case taicpu(p).opsize of
  2973. S_L:
  2974. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2975. begin
  2976. { Optimize out:
  2977. mov x, %reg
  2978. and ffffffffh, %reg
  2979. }
  2980. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2981. RemoveInstruction(hp1);
  2982. Result:=true;
  2983. exit;
  2984. end;
  2985. S_Q: { TODO: Confirm if this is even possible }
  2986. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2987. begin
  2988. { Optimize out:
  2989. mov x, %reg
  2990. and ffffffffffffffffh, %reg
  2991. }
  2992. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2993. RemoveInstruction(hp1);
  2994. Result:=true;
  2995. exit;
  2996. end;
  2997. else
  2998. ;
  2999. end;
  3000. if (
  3001. { Make sure that if a reference is used, its registers
  3002. are not modified in between }
  3003. (
  3004. (taicpu(p).oper[0]^.typ = top_reg) and
  3005. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  3006. ) or
  3007. (
  3008. (taicpu(p).oper[0]^.typ = top_ref) and
  3009. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  3010. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  3011. )
  3012. ) and
  3013. GetNextInstruction(hp1,hp2) and
  3014. MatchInstruction(hp2,A_TEST,[]) and
  3015. (
  3016. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3017. (
  3018. { If the register being tested is smaller than the one
  3019. that received a bitwise AND, permit it if the constant
  3020. fits into the smaller size }
  3021. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3022. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3023. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3024. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3025. (
  3026. (
  3027. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3028. (taicpu(hp1).oper[0]^.val <= $FF)
  3029. ) or
  3030. (
  3031. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3032. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3033. {$ifdef x86_64}
  3034. ) or
  3035. (
  3036. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3037. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3038. {$endif x86_64}
  3039. )
  3040. )
  3041. )
  3042. ) and
  3043. (
  3044. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3045. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3046. ) and
  3047. GetNextInstruction(hp2,hp3) and
  3048. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3049. (taicpu(hp3).condition in [C_E,C_NE]) then
  3050. begin
  3051. TransferUsedRegs(TmpUsedRegs);
  3052. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3053. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3054. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3055. begin
  3056. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3057. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3058. taicpu(hp1).opcode:=A_TEST;
  3059. { Shrink the TEST instruction down to the smallest possible size }
  3060. case taicpu(hp1).oper[0]^.val of
  3061. 0..255:
  3062. if (taicpu(hp1).opsize <> S_B)
  3063. {$ifndef x86_64}
  3064. and (
  3065. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3066. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3067. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3068. )
  3069. {$endif x86_64}
  3070. then
  3071. begin
  3072. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3073. { Only print debug message if the TEST instruction
  3074. is a different size before and after }
  3075. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3076. taicpu(hp1).opsize := S_B;
  3077. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3078. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3079. end;
  3080. 256..65535:
  3081. if (taicpu(hp1).opsize <> S_W) then
  3082. begin
  3083. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3084. { Only print debug message if the TEST instruction
  3085. is a different size before and after }
  3086. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3087. taicpu(hp1).opsize := S_W;
  3088. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3089. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3090. end;
  3091. {$ifdef x86_64}
  3092. 65536..$7FFFFFFF:
  3093. if (taicpu(hp1).opsize <> S_L) then
  3094. begin
  3095. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3096. { Only print debug message if the TEST instruction
  3097. is a different size before and after }
  3098. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3099. taicpu(hp1).opsize := S_L;
  3100. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3101. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3102. end;
  3103. {$endif x86_64}
  3104. else
  3105. ;
  3106. end;
  3107. RemoveInstruction(hp2);
  3108. RemoveCurrentP(p);
  3109. Result:=true;
  3110. exit;
  3111. end;
  3112. end;
  3113. end;
  3114. if IsMOVZXAcceptable and
  3115. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3116. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3117. (getsupreg(p_TargetReg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3118. then
  3119. begin
  3120. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3121. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3122. case taicpu(p).opsize of
  3123. S_B:
  3124. if (taicpu(hp1).oper[0]^.val = $ff) then
  3125. begin
  3126. { Convert:
  3127. movb x, %regl movb x, %regl
  3128. andw ffh, %regw andl ffh, %regd
  3129. To:
  3130. movzbw x, %regd movzbl x, %regd
  3131. (Identical registers, just different sizes)
  3132. }
  3133. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3134. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3135. case taicpu(hp1).opsize of
  3136. S_W: NewSize := S_BW;
  3137. S_L: NewSize := S_BL;
  3138. {$ifdef x86_64}
  3139. S_Q: NewSize := S_BQ;
  3140. {$endif x86_64}
  3141. else
  3142. InternalError(2018011510);
  3143. end;
  3144. end
  3145. else
  3146. NewSize := S_NO;
  3147. S_W:
  3148. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3149. begin
  3150. { Convert:
  3151. movw x, %regw
  3152. andl ffffh, %regd
  3153. To:
  3154. movzwl x, %regd
  3155. (Identical registers, just different sizes)
  3156. }
  3157. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3158. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3159. case taicpu(hp1).opsize of
  3160. S_L: NewSize := S_WL;
  3161. {$ifdef x86_64}
  3162. S_Q: NewSize := S_WQ;
  3163. {$endif x86_64}
  3164. else
  3165. InternalError(2018011511);
  3166. end;
  3167. end
  3168. else
  3169. NewSize := S_NO;
  3170. else
  3171. NewSize := S_NO;
  3172. end;
  3173. if NewSize <> S_NO then
  3174. begin
  3175. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3176. { The actual optimization }
  3177. taicpu(p).opcode := A_MOVZX;
  3178. taicpu(p).changeopsize(NewSize);
  3179. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3180. { Make sure we deal with any reference counts that were increased }
  3181. if taicpu(hp1).oper[1]^.typ = top_ref then
  3182. begin
  3183. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3184. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3185. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3186. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3187. end;
  3188. { Safeguard if "and" is followed by a conditional command }
  3189. TransferUsedRegs(TmpUsedRegs);
  3190. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3191. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3192. begin
  3193. { At this point, the "and" command is effectively equivalent to
  3194. "test %reg,%reg". This will be handled separately by the
  3195. Peephole Optimizer. [Kit] }
  3196. DebugMsg(SPeepholeOptimization + PreMessage +
  3197. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3198. end
  3199. else
  3200. begin
  3201. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3202. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3203. RemoveInstruction(hp1);
  3204. end;
  3205. Result := True;
  3206. Exit;
  3207. { Go through DeepMOVOpt again (jump to "while True do") }
  3208. Continue;
  3209. end;
  3210. end;
  3211. end;
  3212. if taicpu(p).oper[0]^.typ = top_reg then
  3213. begin
  3214. p_SourceReg := taicpu(p).oper[0]^.reg;
  3215. { Look for:
  3216. mov %reg1,%reg2
  3217. ??? %reg2,r/m
  3218. Change to:
  3219. mov %reg1,%reg2
  3220. ??? %reg1,r/m
  3221. }
  3222. if RegReadByInstruction(p_TargetReg, hp1) and
  3223. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3224. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3225. begin
  3226. { A change has occurred, just not in p }
  3227. Include(OptsToCheck, aoc_ForceNewIteration);
  3228. TransferUsedRegs(TmpUsedRegs);
  3229. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3230. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3231. { Just in case something didn't get modified (e.g. an
  3232. implicit register) }
  3233. not RegReadByInstruction(p_TargetReg, hp1) then
  3234. begin
  3235. { We can remove the original MOV }
  3236. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3237. RemoveCurrentP(p);
  3238. { UsedRegs got updated by RemoveCurrentp }
  3239. Result := True;
  3240. Exit;
  3241. end;
  3242. { If we know a MOV instruction has become a null operation, we might as well
  3243. get rid of it now to save time. }
  3244. if (taicpu(hp1).opcode = A_MOV) and
  3245. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3246. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3247. { Just being a register is enough to confirm it's a null operation }
  3248. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3249. begin
  3250. Result := True;
  3251. { Speed-up to reduce a pipeline stall... if we had something like...
  3252. movl %eax,%edx
  3253. movw %dx,%ax
  3254. ... the second instruction would change to movw %ax,%ax, but
  3255. given that it is now %ax that's active rather than %eax,
  3256. penalties might occur due to a partial register write, so instead,
  3257. change it to a MOVZX instruction when optimising for speed.
  3258. }
  3259. if not (cs_opt_size in current_settings.optimizerswitches) and
  3260. IsMOVZXAcceptable and
  3261. (taicpu(hp1).opsize < taicpu(p).opsize)
  3262. {$ifdef x86_64}
  3263. { operations already implicitly set the upper 64 bits to zero }
  3264. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3265. {$endif x86_64}
  3266. then
  3267. begin
  3268. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3269. case taicpu(p).opsize of
  3270. S_W:
  3271. if taicpu(hp1).opsize = S_B then
  3272. taicpu(hp1).opsize := S_BL
  3273. else
  3274. InternalError(2020012911);
  3275. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3276. case taicpu(hp1).opsize of
  3277. S_B:
  3278. taicpu(hp1).opsize := S_BL;
  3279. S_W:
  3280. taicpu(hp1).opsize := S_WL;
  3281. else
  3282. InternalError(2020012912);
  3283. end;
  3284. else
  3285. InternalError(2020012910);
  3286. end;
  3287. taicpu(hp1).opcode := A_MOVZX;
  3288. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3289. end
  3290. else
  3291. begin
  3292. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3293. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3294. RemoveInstruction(hp1);
  3295. { The instruction after what was hp1 is now the immediate next instruction,
  3296. so we can continue to make optimisations if it's present }
  3297. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3298. Exit;
  3299. hp1 := hp2;
  3300. end;
  3301. end;
  3302. end;
  3303. {$ifdef x86_64}
  3304. { Change:
  3305. movl %reg1l,%reg2l
  3306. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3307. To:
  3308. movl %reg1l,%reg2l
  3309. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3310. If %reg1 = %reg3, convert to:
  3311. movl %reg1l,%reg2l
  3312. andl %reg1l,%reg1l
  3313. }
  3314. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3315. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3316. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3317. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg) then
  3318. begin
  3319. TransferUsedRegs(TmpUsedRegs);
  3320. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3321. taicpu(hp1).opsize := S_L;
  3322. taicpu(hp1).loadreg(0, p_SourceReg);
  3323. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3324. AllocRegBetween(p_SourceReg, p, hp1, UsedRegs);
  3325. if (p_SourceReg = taicpu(hp1).oper[1]^.reg) then
  3326. begin
  3327. { %reg1 = %reg3 }
  3328. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3329. taicpu(hp1).opcode := A_AND;
  3330. end
  3331. else
  3332. begin
  3333. { %reg1 <> %reg3 }
  3334. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3335. end;
  3336. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3337. begin
  3338. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3339. RemoveCurrentP(p);
  3340. Result := True;
  3341. Exit;
  3342. end
  3343. else
  3344. begin
  3345. { Initial instruction wasn't actually changed }
  3346. Include(OptsToCheck, aoc_ForceNewIteration);
  3347. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3348. appears below since %reg1 has technically changed }
  3349. if taicpu(hp1).opcode = A_AND then
  3350. Exit;
  3351. end;
  3352. end;
  3353. {$endif x86_64}
  3354. end
  3355. else if taicpu(p).oper[0]^.typ = top_const then
  3356. begin
  3357. if (taicpu(hp1).opcode = A_OR) and
  3358. (taicpu(p).oper[1]^.typ = top_reg) and
  3359. MatchOperand(taicpu(p).oper[0]^, 0) and
  3360. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3361. begin
  3362. { mov 0, %reg
  3363. or ###,%reg
  3364. Change to (only if the flags are not used):
  3365. mov ###,%reg
  3366. }
  3367. TransferUsedRegs(TmpUsedRegs);
  3368. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3369. DoOptimisation := True;
  3370. { Even if the flags are used, we might be able to do the optimisation
  3371. if the conditions are predictable }
  3372. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3373. begin
  3374. { Only perform if ### = %reg (the same register) or equal to 0,
  3375. so %reg is guaranteed to still have a value of zero }
  3376. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3377. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3378. begin
  3379. hp2 := hp1;
  3380. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3381. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3382. GetNextInstruction(hp2, hp3) do
  3383. begin
  3384. { Don't continue modifying if the flags state is getting changed }
  3385. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3386. Break;
  3387. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3388. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3389. begin
  3390. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3391. begin
  3392. { Condition is always true }
  3393. case taicpu(hp3).opcode of
  3394. A_Jcc:
  3395. begin
  3396. { Check for jump shortcuts before we destroy the condition }
  3397. hp4 := hp3;
  3398. DoJumpOptimizations(hp3, TempBool);
  3399. { Make sure hp3 hasn't changed }
  3400. if (hp4 = hp3) then
  3401. begin
  3402. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3403. MakeUnconditional(taicpu(hp3));
  3404. end;
  3405. Result := True;
  3406. end;
  3407. A_CMOVcc:
  3408. begin
  3409. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3410. taicpu(hp3).opcode := A_MOV;
  3411. taicpu(hp3).condition := C_None;
  3412. Result := True;
  3413. end;
  3414. A_SETcc:
  3415. begin
  3416. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3417. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3418. taicpu(hp3).opcode := A_MOV;
  3419. taicpu(hp3).ops := 2;
  3420. taicpu(hp3).condition := C_None;
  3421. taicpu(hp3).opsize := S_B;
  3422. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3423. taicpu(hp3).loadconst(0, 1);
  3424. Result := True;
  3425. end;
  3426. else
  3427. InternalError(2021090701);
  3428. end;
  3429. end
  3430. 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
  3431. begin
  3432. { Condition is always false }
  3433. case taicpu(hp3).opcode of
  3434. A_Jcc:
  3435. begin
  3436. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3437. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3438. RemoveInstruction(hp3);
  3439. Result := True;
  3440. { Since hp3 was deleted, hp2 must not be updated }
  3441. Continue;
  3442. end;
  3443. A_CMOVcc:
  3444. begin
  3445. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3446. RemoveInstruction(hp3);
  3447. Result := True;
  3448. { Since hp3 was deleted, hp2 must not be updated }
  3449. Continue;
  3450. end;
  3451. A_SETcc:
  3452. begin
  3453. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3454. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3455. taicpu(hp3).opcode := A_MOV;
  3456. taicpu(hp3).ops := 2;
  3457. taicpu(hp3).condition := C_None;
  3458. taicpu(hp3).opsize := S_B;
  3459. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3460. taicpu(hp3).loadconst(0, 0);
  3461. Result := True;
  3462. end;
  3463. else
  3464. InternalError(2021090702);
  3465. end;
  3466. end
  3467. else
  3468. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3469. DoOptimisation := False;
  3470. end;
  3471. hp2 := hp3;
  3472. end;
  3473. if DoOptimisation then
  3474. begin
  3475. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3476. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3477. { Flags are still in use - don't optimise }
  3478. DoOptimisation := False;
  3479. end;
  3480. end
  3481. else
  3482. DoOptimisation := False;
  3483. end;
  3484. if DoOptimisation then
  3485. begin
  3486. {$ifdef x86_64}
  3487. { OR only supports 32-bit sign-extended constants for 64-bit
  3488. instructions, so compensate for this if the constant is
  3489. encoded as a value greater than or equal to 2^31 }
  3490. if (taicpu(hp1).opsize = S_Q) and
  3491. (taicpu(hp1).oper[0]^.typ = top_const) and
  3492. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3493. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3494. {$endif x86_64}
  3495. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3496. taicpu(hp1).opcode := A_MOV;
  3497. RemoveCurrentP(p);
  3498. Result := True;
  3499. Exit;
  3500. end;
  3501. end;
  3502. end
  3503. else if
  3504. { oper[0] is a reference }
  3505. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) then
  3506. begin
  3507. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  3508. begin
  3509. if ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3510. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3511. ) or
  3512. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3513. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3514. )
  3515. ) and
  3516. not RegModifiedBetween(Taicpu(hp1).oper[1]^.reg, p, hp1) then
  3517. { mov ref,reg1
  3518. lea (reg1,reg2),reg2
  3519. to
  3520. add ref,reg2 }
  3521. begin
  3522. TransferUsedRegs(TmpUsedRegs);
  3523. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3524. { If the flags register is in use, don't change the instruction to an
  3525. ADD otherwise this will scramble the flags. [Kit] }
  3526. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3527. { reg1 may not be used afterwards }
  3528. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3529. begin
  3530. Taicpu(hp1).opcode:=A_ADD;
  3531. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3532. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3533. RemoveCurrentp(p);
  3534. result:=true;
  3535. exit;
  3536. end;
  3537. end;
  3538. { If the LEA instruction can be converted into an arithmetic instruction,
  3539. it may be possible to then fold it in the next optimisation. }
  3540. if ConvertLEA(taicpu(hp1)) then
  3541. Include(OptsToCheck, aoc_ForceNewIteration);
  3542. end;
  3543. {
  3544. mov ref,reg0
  3545. <op> reg0,reg1
  3546. dealloc reg0
  3547. to
  3548. <op> ref,reg1
  3549. }
  3550. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3551. (taicpu(hp1).oper[0]^.reg = p_TargetReg) and
  3552. 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
  3553. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, p_TargetReg) and
  3554. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3555. begin
  3556. TransferUsedRegs(TmpUsedRegs);
  3557. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3558. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3559. begin
  3560. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  3561. { loadref increases the reference count, so decrement it again }
  3562. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3563. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3564. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3565. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3566. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3567. { See if we can remove the allocation of reg0 }
  3568. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3569. TryRemoveRegAlloc(p_TargetReg, p, hp1);
  3570. RemoveCurrentp(p);
  3571. Result:=true;
  3572. exit;
  3573. end;
  3574. end;
  3575. end;
  3576. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3577. overwrites the original destination register. e.g.
  3578. movl ###,%reg2d
  3579. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3580. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3581. }
  3582. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3583. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3584. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3585. begin
  3586. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3587. begin
  3588. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3589. case taicpu(p).oper[0]^.typ of
  3590. top_const:
  3591. { We have something like:
  3592. movb $x, %regb
  3593. movzbl %regb,%regd
  3594. Change to:
  3595. movl $x, %regd
  3596. }
  3597. begin
  3598. case taicpu(hp1).opsize of
  3599. S_BW:
  3600. begin
  3601. convert_mov_value(A_MOVSX, $FF);
  3602. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3603. taicpu(p).opsize := S_W;
  3604. end;
  3605. S_BL:
  3606. begin
  3607. convert_mov_value(A_MOVSX, $FF);
  3608. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3609. taicpu(p).opsize := S_L;
  3610. end;
  3611. S_WL:
  3612. begin
  3613. convert_mov_value(A_MOVSX, $FFFF);
  3614. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3615. taicpu(p).opsize := S_L;
  3616. end;
  3617. {$ifdef x86_64}
  3618. S_BQ:
  3619. begin
  3620. convert_mov_value(A_MOVSX, $FF);
  3621. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3622. taicpu(p).opsize := S_Q;
  3623. end;
  3624. S_WQ:
  3625. begin
  3626. convert_mov_value(A_MOVSX, $FFFF);
  3627. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3628. taicpu(p).opsize := S_Q;
  3629. end;
  3630. S_LQ:
  3631. begin
  3632. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3633. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3634. taicpu(p).opsize := S_Q;
  3635. end;
  3636. {$endif x86_64}
  3637. else
  3638. { If hp1 was a MOV instruction, it should have been
  3639. optimised already }
  3640. InternalError(2020021001);
  3641. end;
  3642. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3643. RemoveInstruction(hp1);
  3644. Result := True;
  3645. Exit;
  3646. end;
  3647. top_ref:
  3648. begin
  3649. { We have something like:
  3650. movb mem, %regb
  3651. movzbl %regb,%regd
  3652. Change to:
  3653. movzbl mem, %regd
  3654. }
  3655. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3656. begin
  3657. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3658. taicpu(p).opcode := taicpu(hp1).opcode;
  3659. taicpu(p).opsize := taicpu(hp1).opsize;
  3660. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3661. RemoveInstruction(hp1);
  3662. Result := True;
  3663. Exit;
  3664. end;
  3665. end;
  3666. else
  3667. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3668. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3669. Exit;
  3670. end;
  3671. end
  3672. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3673. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3674. optimised }
  3675. else
  3676. begin
  3677. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3678. RemoveCurrentP(p);
  3679. Result := True;
  3680. Exit;
  3681. end;
  3682. end;
  3683. if (taicpu(hp1).opcode = A_MOV) and
  3684. (
  3685. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  3686. {$ifdef x86_64}
  3687. or (
  3688. { Permit zero extension from 32- to 64-bit when writing
  3689. a constant (it will be checked to see if it fits into
  3690. a signed 32-bit integer) }
  3691. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3692. (
  3693. { Valid situations... writing an unsigned 32-bit
  3694. immediate, or the destination is a 64-bit register }
  3695. (taicpu(p).oper[0]^.typ = top_const) or
  3696. (taicpu(hp1).oper[1]^.typ = top_reg)
  3697. ) and
  3698. (taicpu(hp1).oper[0]^.typ = top_reg) and
  3699. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg)
  3700. )
  3701. {$endif x86_64}
  3702. ) then
  3703. begin
  3704. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3705. TransferUsedRegs(TmpUsedRegs);
  3706. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3707. { we have
  3708. mov x, %treg
  3709. mov %treg, y
  3710. }
  3711. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3712. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3713. begin
  3714. { we've got
  3715. mov x, %treg
  3716. mov %treg, y
  3717. with %treg is not used after }
  3718. case taicpu(p).oper[0]^.typ Of
  3719. { top_reg is covered by DeepMOVOpt }
  3720. top_const:
  3721. begin
  3722. { change
  3723. mov const, %treg
  3724. mov %treg, y
  3725. to
  3726. mov const, y
  3727. }
  3728. {$ifdef x86_64}
  3729. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3730. (
  3731. { For 32-to-64-bit zero-extension, the immediate
  3732. must be between 0 and 2^31 - 1}
  3733. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3734. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3735. ) or
  3736. (
  3737. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3738. (
  3739. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3740. )
  3741. ) then
  3742. {$endif x86_64}
  3743. begin
  3744. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3745. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3746. RemoveCurrentP(p);
  3747. Result := True;
  3748. Exit;
  3749. end;
  3750. end;
  3751. top_ref:
  3752. case taicpu(hp1).oper[1]^.typ of
  3753. top_reg:
  3754. { change
  3755. mov mem, %treg
  3756. mov %treg, %reg
  3757. to
  3758. mov mem, %reg"
  3759. }
  3760. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3761. begin
  3762. {$ifdef x86_64}
  3763. { If zero extending from 32-bit to 64-bit,
  3764. we have to make sure the replaced
  3765. register is the right size }
  3766. taicpu(p).loadreg(1, newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),getsubreg(p_TargetReg)));
  3767. {$else}
  3768. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3769. {$endif x86_64}
  3770. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3771. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3772. RemoveInstruction(hp1);
  3773. Result := True;
  3774. Exit;
  3775. end
  3776. else if
  3777. { Make sure that if a reference is used, its
  3778. registers are not modified in between }
  3779. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3780. begin
  3781. 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
  3782. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3783. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3784. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3785. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3786. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3787. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3788. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3789. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3790. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3791. RemoveCurrentP(p);
  3792. Result := True;
  3793. Exit;
  3794. end;
  3795. top_ref:
  3796. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3797. begin
  3798. {$ifdef x86_64}
  3799. { Look for the following to simplify:
  3800. mov x(mem1), %reg
  3801. mov %reg, y(mem2)
  3802. mov x+8(mem1), %reg
  3803. mov %reg, y+8(mem2)
  3804. Change to:
  3805. movdqu x(mem1), %xmmreg
  3806. movdqu %xmmreg, y(mem2)
  3807. ...but only as long as the memory blocks don't overlap
  3808. }
  3809. SourceRef := taicpu(p).oper[0]^.ref^;
  3810. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3811. if (taicpu(p).opsize = S_Q) and
  3812. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3813. GetNextInstruction(hp1, hp2) and
  3814. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3815. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3816. begin
  3817. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3818. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3819. Inc(SourceRef.offset, 8);
  3820. if UseAVX then
  3821. begin
  3822. MovAligned := A_VMOVDQA;
  3823. MovUnaligned := A_VMOVDQU;
  3824. end
  3825. else
  3826. begin
  3827. MovAligned := A_MOVDQA;
  3828. MovUnaligned := A_MOVDQU;
  3829. end;
  3830. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3831. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3832. begin
  3833. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3834. Inc(TargetRef.offset, 8);
  3835. if GetNextInstruction(hp2, hp3) and
  3836. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3837. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3838. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3839. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3840. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3841. begin
  3842. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3843. if NewMMReg <> NR_NO then
  3844. begin
  3845. { Remember that the offsets are 8 ahead }
  3846. if ((SourceRef.offset mod 16) = 8) and
  3847. (
  3848. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3849. (SourceRef.base = current_procinfo.framepointer) or
  3850. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3851. ) then
  3852. taicpu(p).opcode := MovAligned
  3853. else
  3854. taicpu(p).opcode := MovUnaligned;
  3855. taicpu(p).opsize := S_XMM;
  3856. taicpu(p).oper[1]^.reg := NewMMReg;
  3857. if ((TargetRef.offset mod 16) = 8) and
  3858. (
  3859. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3860. (TargetRef.base = current_procinfo.framepointer) or
  3861. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3862. ) then
  3863. taicpu(hp1).opcode := MovAligned
  3864. else
  3865. taicpu(hp1).opcode := MovUnaligned;
  3866. taicpu(hp1).opsize := S_XMM;
  3867. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3868. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3869. RemoveInstruction(hp2);
  3870. RemoveInstruction(hp3);
  3871. Result := True;
  3872. Exit;
  3873. end;
  3874. end;
  3875. end
  3876. else
  3877. begin
  3878. { See if the next references are 8 less rather than 8 greater }
  3879. Dec(SourceRef.offset, 16); { -8 the other way }
  3880. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3881. begin
  3882. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3883. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3884. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3885. GetNextInstruction(hp2, hp3) and
  3886. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3887. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3888. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3889. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3890. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3891. begin
  3892. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3893. if NewMMReg <> NR_NO then
  3894. begin
  3895. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3896. if ((SourceRef.offset mod 16) = 0) and
  3897. (
  3898. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3899. (SourceRef.base = current_procinfo.framepointer) or
  3900. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3901. ) then
  3902. taicpu(hp2).opcode := MovAligned
  3903. else
  3904. taicpu(hp2).opcode := MovUnaligned;
  3905. taicpu(hp2).opsize := S_XMM;
  3906. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3907. if ((TargetRef.offset mod 16) = 0) and
  3908. (
  3909. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3910. (TargetRef.base = current_procinfo.framepointer) or
  3911. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3912. ) then
  3913. taicpu(hp3).opcode := MovAligned
  3914. else
  3915. taicpu(hp3).opcode := MovUnaligned;
  3916. taicpu(hp3).opsize := S_XMM;
  3917. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3918. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3919. RemoveInstruction(hp1);
  3920. RemoveCurrentP(p);
  3921. Result := True;
  3922. Exit;
  3923. end;
  3924. end;
  3925. end;
  3926. end;
  3927. end;
  3928. {$endif x86_64}
  3929. end;
  3930. else
  3931. { The write target should be a reg or a ref }
  3932. InternalError(2021091601);
  3933. end;
  3934. else
  3935. ;
  3936. end;
  3937. end
  3938. else if (taicpu(p).oper[0]^.typ = top_const) and
  3939. { %treg is used afterwards, but all eventualities other
  3940. than the first MOV instruction being a constant are
  3941. covered by DeepMOVOpt, so only check for that }
  3942. (
  3943. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3944. not (cs_opt_size in current_settings.optimizerswitches) or
  3945. (taicpu(hp1).opsize = S_B)
  3946. ) and
  3947. (
  3948. (taicpu(hp1).oper[1]^.typ=top_reg) or
  3949. (
  3950. { For 32-to-64-bit zero-extension, the immediate
  3951. must be between 0 and 2^31 - 1}
  3952. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3953. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3954. ) or
  3955. (
  3956. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3957. (
  3958. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3959. )
  3960. )
  3961. ) then
  3962. begin
  3963. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3964. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3965. Include(OptsToCheck, aoc_ForceNewIteration);
  3966. end;
  3967. end;
  3968. Break;
  3969. end;
  3970. end;
  3971. if taicpu(p).oper[0]^.typ = top_reg then
  3972. begin
  3973. { oper[1] is a reference }
  3974. { Saves on a large number of dereferences }
  3975. p_SourceReg := taicpu(p).oper[0]^.reg;
  3976. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  3977. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_SourceReg)
  3978. else
  3979. GetNextInstruction_p := GetNextInstruction(p, hp1);
  3980. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  3981. begin
  3982. if taicpu(p).oper[1]^.typ = top_reg then
  3983. begin
  3984. p_TargetReg := taicpu(p).oper[1]^.reg;
  3985. { Change:
  3986. movl %reg1,%reg2
  3987. ...
  3988. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3989. ...
  3990. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3991. To:
  3992. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3993. ...
  3994. movl x(%reg1),%reg1
  3995. ...
  3996. movl %reg1,%regX
  3997. }
  3998. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  3999. (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4000. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  4001. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  4002. not RegModifiedBetween(p_TargetReg, p, hp1) and
  4003. GetNextInstructionUsingReg(hp1, hp2, p_TargetReg) and
  4004. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  4005. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4006. not RegModifiedBetween(p_SourceReg, hp1, hp2) then
  4007. begin
  4008. SourceRef := taicpu(hp2).oper[0]^.ref^;
  4009. if RegInRef(p_TargetReg, SourceRef) and
  4010. { If %reg1 also appears in the second reference, then it will
  4011. not refer to the same memory block as the first reference }
  4012. not RegInRef(p_SourceReg, SourceRef) then
  4013. begin
  4014. { Check to see if the references match if %reg2 is changed to %reg1 }
  4015. if SourceRef.base = p_TargetReg then
  4016. SourceRef.base := p_SourceReg;
  4017. if SourceRef.index = p_TargetReg then
  4018. SourceRef.index := p_SourceReg;
  4019. { RefsEqual also checks to ensure both references are non-volatile }
  4020. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  4021. begin
  4022. taicpu(hp2).loadreg(0, p_SourceReg);
  4023. TransferUsedRegs(TmpUsedRegs);
  4024. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  4025. { Make sure the register is allocated between these instructions
  4026. even though it doesn't change value, since it may cause
  4027. optimisations on a later pass to behave incorrectly. (Fixes #41155) }
  4028. AllocRegBetween(p_SourceReg, hp1, hp2, TmpUsedRegs);
  4029. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  4030. Result := True;
  4031. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  4032. begin
  4033. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  4034. RemoveCurrentP(p);
  4035. Exit;
  4036. end
  4037. else
  4038. begin
  4039. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  4040. begin
  4041. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  4042. RemoveCurrentP(p);
  4043. Exit;
  4044. end;
  4045. end;
  4046. { If we reach this point, p and hp1 weren't actually modified,
  4047. so we can do a bit more work on this pass }
  4048. end;
  4049. end;
  4050. end;
  4051. end;
  4052. end;
  4053. end;
  4054. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  4055. { All the next optimisations require a next instruction }
  4056. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  4057. Exit;
  4058. { Next instruction is also a MOV ? }
  4059. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  4060. begin
  4061. if MatchOpType(taicpu(p), top_const, top_ref) and
  4062. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4063. TryConstMerge(p, hp1) then
  4064. begin
  4065. Result := True;
  4066. { In case we have four byte writes in a row, check for 2 more
  4067. right now so we don't have to wait for another iteration of
  4068. pass 1
  4069. }
  4070. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  4071. case taicpu(p).opsize of
  4072. S_W:
  4073. begin
  4074. if GetNextInstruction(p, hp1) and
  4075. MatchInstruction(hp1, A_MOV, [S_B]) and
  4076. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4077. GetNextInstruction(hp1, hp2) and
  4078. MatchInstruction(hp2, A_MOV, [S_B]) and
  4079. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4080. { Try to merge the two bytes }
  4081. TryConstMerge(hp1, hp2) then
  4082. { Now try to merge the two words (hp2 will get deleted) }
  4083. TryConstMerge(p, hp1);
  4084. end;
  4085. S_L:
  4086. begin
  4087. { Though this only really benefits x86_64 and not i386, it
  4088. gets a potential optimisation done faster and hence
  4089. reduces the number of times OptPass1MOV is entered }
  4090. if GetNextInstruction(p, hp1) and
  4091. MatchInstruction(hp1, A_MOV, [S_W]) and
  4092. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4093. GetNextInstruction(hp1, hp2) and
  4094. MatchInstruction(hp2, A_MOV, [S_W]) and
  4095. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4096. { Try to merge the two words }
  4097. TryConstMerge(hp1, hp2) then
  4098. { This will always fail on i386, so don't bother
  4099. calling it unless we're doing x86_64 }
  4100. {$ifdef x86_64}
  4101. { Now try to merge the two longwords (hp2 will get deleted) }
  4102. TryConstMerge(p, hp1)
  4103. {$endif x86_64}
  4104. ;
  4105. end;
  4106. else
  4107. ;
  4108. end;
  4109. Exit;
  4110. end;
  4111. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4112. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4113. { mov reg1, mem1 or mov mem1, reg1
  4114. mov mem2, reg2 mov reg2, mem2}
  4115. begin
  4116. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4117. { mov reg1, mem1 or mov mem1, reg1
  4118. mov mem2, reg1 mov reg2, mem1}
  4119. begin
  4120. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4121. { Removes the second statement from
  4122. mov reg1, mem1/reg2
  4123. mov mem1/reg2, reg1 }
  4124. begin
  4125. if taicpu(p).oper[0]^.typ=top_reg then
  4126. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4127. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  4128. RemoveInstruction(hp1);
  4129. Result:=true;
  4130. exit;
  4131. end
  4132. else
  4133. begin
  4134. TransferUsedRegs(TmpUsedRegs);
  4135. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4136. if (taicpu(p).oper[1]^.typ = top_ref) and
  4137. { mov reg1, mem1
  4138. mov mem2, reg1 }
  4139. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4140. GetNextInstruction(hp1, hp2) and
  4141. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4142. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4143. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4144. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4145. { change to
  4146. mov reg1, mem1 mov reg1, mem1
  4147. mov mem2, reg1 cmp reg1, mem2
  4148. cmp mem1, reg1
  4149. }
  4150. begin
  4151. RemoveInstruction(hp2);
  4152. taicpu(hp1).opcode := A_CMP;
  4153. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4154. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4155. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4156. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4157. end;
  4158. end;
  4159. end
  4160. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4161. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4162. begin
  4163. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4164. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4165. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4166. end
  4167. else
  4168. begin
  4169. TransferUsedRegs(TmpUsedRegs);
  4170. if GetNextInstruction(hp1, hp2) and
  4171. MatchOpType(taicpu(p),top_ref,top_reg) and
  4172. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4173. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4174. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4175. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4176. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4177. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4178. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4179. { mov mem1, %reg1
  4180. mov %reg1, mem2
  4181. mov mem2, reg2
  4182. to:
  4183. mov mem1, reg2
  4184. mov reg2, mem2}
  4185. begin
  4186. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4187. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4188. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4189. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4190. RemoveInstruction(hp2);
  4191. Result := True;
  4192. end
  4193. {$ifdef i386}
  4194. { this is enabled for i386 only, as the rules to create the reg sets below
  4195. are too complicated for x86-64, so this makes this code too error prone
  4196. on x86-64
  4197. }
  4198. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4199. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4200. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4201. { mov mem1, reg1 mov mem1, reg1
  4202. mov reg1, mem2 mov reg1, mem2
  4203. mov mem2, reg2 mov mem2, reg1
  4204. to: to:
  4205. mov mem1, reg1 mov mem1, reg1
  4206. mov mem1, reg2 mov reg1, mem2
  4207. mov reg1, mem2
  4208. or (if mem1 depends on reg1
  4209. and/or if mem2 depends on reg2)
  4210. to:
  4211. mov mem1, reg1
  4212. mov reg1, mem2
  4213. mov reg1, reg2
  4214. }
  4215. begin
  4216. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4217. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4218. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4219. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4220. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4221. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4222. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4223. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4224. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4225. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4226. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4227. end
  4228. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4229. begin
  4230. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4231. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4232. end
  4233. else
  4234. begin
  4235. RemoveInstruction(hp2);
  4236. end
  4237. {$endif i386}
  4238. ;
  4239. end;
  4240. end
  4241. { movl [mem1],reg1
  4242. movl [mem1],reg2
  4243. to
  4244. movl [mem1],reg1
  4245. movl reg1,reg2
  4246. }
  4247. else if not CheckMovMov2MovMov2(p, hp1) and
  4248. { movl const1,[mem1]
  4249. movl [mem1],reg1
  4250. to
  4251. movl const1,reg1
  4252. movl reg1,[mem1]
  4253. }
  4254. MatchOpType(Taicpu(p),top_const,top_ref) and
  4255. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4256. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4257. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4258. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4259. begin
  4260. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4261. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4262. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4263. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4264. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4265. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4266. Result:=true;
  4267. exit;
  4268. end;
  4269. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4270. end;
  4271. { search further than the next instruction for a mov (as long as it's not a jump) }
  4272. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4273. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4274. (taicpu(p).oper[1]^.typ = top_reg) and
  4275. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4276. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4277. begin
  4278. { we work with hp2 here, so hp1 can be still used later on when
  4279. checking for GetNextInstruction_p }
  4280. hp3 := hp1;
  4281. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4282. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4283. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4284. TransferUsedRegs(TmpUsedRegs);
  4285. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4286. if NotFirstIteration then
  4287. JumpTracking := TLinkedList.Create
  4288. else
  4289. JumpTracking := nil;
  4290. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4291. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4292. (hp2.typ=ait_instruction) do
  4293. begin
  4294. case taicpu(hp2).opcode of
  4295. A_POP:
  4296. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4297. begin
  4298. if not CrossJump and
  4299. not RegUsedBetween(p_TargetReg, p, hp2) then
  4300. begin
  4301. { We can remove the original MOV since the register
  4302. wasn't used between it and its popping from the stack }
  4303. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4304. RemoveCurrentp(p, hp1);
  4305. Result := True;
  4306. JumpTracking.Free;
  4307. Exit;
  4308. end;
  4309. { Can't go any further }
  4310. Break;
  4311. end;
  4312. A_MOV:
  4313. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4314. ((taicpu(p).oper[0]^.typ=top_const) or
  4315. ((taicpu(p).oper[0]^.typ=top_reg) and
  4316. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4317. )
  4318. ) then
  4319. begin
  4320. { we have
  4321. mov x, %treg
  4322. mov %treg, y
  4323. }
  4324. { We don't need to call UpdateUsedRegs for every instruction between
  4325. p and hp2 because the register we're concerned about will not
  4326. become deallocated (otherwise GetNextInstructionUsingReg would
  4327. have stopped at an earlier instruction). [Kit] }
  4328. TempRegUsed :=
  4329. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4330. RegReadByInstruction(p_TargetReg, hp3) or
  4331. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4332. case taicpu(p).oper[0]^.typ Of
  4333. top_reg:
  4334. begin
  4335. { change
  4336. mov %reg, %treg
  4337. mov %treg, y
  4338. to
  4339. mov %reg, y
  4340. }
  4341. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4342. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4343. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4344. begin
  4345. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4346. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4347. if TempRegUsed then
  4348. begin
  4349. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4350. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4351. { Set the start of the next GetNextInstructionUsingRegCond search
  4352. to start at the entry right before hp2 (which is about to be removed) }
  4353. hp3 := tai(hp2.Previous);
  4354. RemoveInstruction(hp2);
  4355. Include(OptsToCheck, aoc_ForceNewIteration);
  4356. { See if there's more we can optimise }
  4357. Continue;
  4358. end
  4359. else
  4360. begin
  4361. RemoveInstruction(hp2);
  4362. { We can remove the original MOV too }
  4363. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4364. RemoveCurrentP(p, hp1);
  4365. Result:=true;
  4366. JumpTracking.Free;
  4367. Exit;
  4368. end;
  4369. end
  4370. else
  4371. begin
  4372. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4373. taicpu(hp2).loadReg(0, p_SourceReg);
  4374. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4375. { Check to see if the register also appears in the reference }
  4376. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4377. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4378. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4379. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4380. begin
  4381. { Don't remove the first instruction if the temporary register is in use }
  4382. if not TempRegUsed then
  4383. begin
  4384. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4385. RemoveCurrentP(p, hp1);
  4386. Result:=true;
  4387. JumpTracking.Free;
  4388. Exit;
  4389. end;
  4390. { No need to set Result to True here. If there's another instruction later
  4391. on that can be optimised, it will be detected when the main Pass 1 loop
  4392. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4393. hp3 := hp2;
  4394. Continue;
  4395. end;
  4396. end;
  4397. end;
  4398. top_const:
  4399. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4400. begin
  4401. { change
  4402. mov const, %treg
  4403. mov %treg, y
  4404. to
  4405. mov const, y
  4406. }
  4407. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4408. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4409. begin
  4410. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4411. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4412. if TempRegUsed then
  4413. begin
  4414. { Don't remove the first instruction if the temporary register is in use }
  4415. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4416. { No need to set Result to True. If there's another instruction later on
  4417. that can be optimised, it will be detected when the main Pass 1 loop
  4418. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4419. end
  4420. else
  4421. begin
  4422. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4423. RemoveCurrentP(p, hp1);
  4424. Result:=true;
  4425. Exit;
  4426. end;
  4427. end;
  4428. end;
  4429. else
  4430. Internalerror(2019103001);
  4431. end;
  4432. end
  4433. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4434. begin
  4435. if not CrossJump and
  4436. not RegUsedBetween(p_TargetReg, p, hp2) and
  4437. not RegReadByInstruction(p_TargetReg, hp2) then
  4438. begin
  4439. { Register is not used before it is overwritten }
  4440. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4441. RemoveCurrentp(p, hp1);
  4442. Result := True;
  4443. Exit;
  4444. end;
  4445. if (taicpu(p).oper[0]^.typ = top_const) and
  4446. (taicpu(hp2).oper[0]^.typ = top_const) then
  4447. begin
  4448. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4449. begin
  4450. { Same value - register hasn't changed }
  4451. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4452. RemoveInstruction(hp2);
  4453. Include(OptsToCheck, aoc_ForceNewIteration);
  4454. { See if there's more we can optimise }
  4455. Continue;
  4456. end;
  4457. end;
  4458. {$ifdef x86_64}
  4459. end
  4460. { Change:
  4461. movl %reg1l,%reg2l
  4462. ...
  4463. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4464. To:
  4465. movl %reg1l,%reg2l
  4466. ...
  4467. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4468. If %reg1 = %reg3, convert to:
  4469. movl %reg1l,%reg2l
  4470. ...
  4471. andl %reg1l,%reg1l
  4472. }
  4473. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4474. (taicpu(p).oper[0]^.typ = top_reg) and
  4475. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4476. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4477. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4478. begin
  4479. TempRegUsed :=
  4480. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4481. RegReadByInstruction(p_TargetReg, hp3) or
  4482. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4483. taicpu(hp2).opsize := S_L;
  4484. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4485. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4486. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4487. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4488. begin
  4489. { %reg1 = %reg3 }
  4490. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4491. taicpu(hp2).opcode := A_AND;
  4492. end
  4493. else
  4494. begin
  4495. { %reg1 <> %reg3 }
  4496. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4497. end;
  4498. if not TempRegUsed then
  4499. begin
  4500. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4501. RemoveCurrentP(p, hp1);
  4502. Result := True;
  4503. Exit;
  4504. end
  4505. else
  4506. begin
  4507. { Initial instruction wasn't actually changed }
  4508. Include(OptsToCheck, aoc_ForceNewIteration);
  4509. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4510. appears below since %reg1 has technically changed }
  4511. if taicpu(hp2).opcode = A_AND then
  4512. Break;
  4513. end;
  4514. {$endif x86_64}
  4515. end
  4516. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4517. GetNextInstruction(hp2, hp4) and
  4518. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4519. { Optimise the following first:
  4520. movl [mem1],reg1
  4521. movl [mem1],reg2
  4522. to
  4523. movl [mem1],reg1
  4524. movl reg1,reg2
  4525. If [mem1] contains the target register and reg1 is the
  4526. the source register, this optimisation will get missed
  4527. and produce less efficient code later on.
  4528. }
  4529. if CheckMovMov2MovMov2(hp2, hp4) then
  4530. { Initial instruction wasn't actually changed }
  4531. Include(OptsToCheck, aoc_ForceNewIteration);
  4532. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4533. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4534. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4535. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4536. begin
  4537. {
  4538. Change from:
  4539. mov ###, %reg
  4540. ...
  4541. movs/z %reg,%reg (Same register, just different sizes)
  4542. To:
  4543. movs/z ###, %reg (Longer version)
  4544. ...
  4545. (remove)
  4546. }
  4547. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4548. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4549. { Keep the first instruction as mov if ### is a constant }
  4550. if taicpu(p).oper[0]^.typ = top_const then
  4551. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4552. else
  4553. begin
  4554. taicpu(p).opcode := taicpu(hp2).opcode;
  4555. taicpu(p).opsize := taicpu(hp2).opsize;
  4556. end;
  4557. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4558. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4559. RemoveInstruction(hp2);
  4560. Result := True;
  4561. JumpTracking.Free;
  4562. Exit;
  4563. end;
  4564. else
  4565. { Move down to the if-block below };
  4566. end;
  4567. { Also catches MOV/S/Z instructions that aren't modified }
  4568. if taicpu(p).oper[0]^.typ = top_reg then
  4569. begin
  4570. p_SourceReg := taicpu(p).oper[0]^.reg;
  4571. if
  4572. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4573. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4574. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4575. begin
  4576. Result := True;
  4577. { Just in case something didn't get modified (e.g. an
  4578. implicit register). Also, if it does read from this
  4579. register, then there's no longer an advantage to
  4580. changing the register on subsequent instructions.}
  4581. if not RegReadByInstruction(p_TargetReg, hp2) then
  4582. begin
  4583. { If a conditional jump was crossed, do not delete
  4584. the original MOV no matter what }
  4585. if not CrossJump and
  4586. { RegEndOfLife returns True if the register is
  4587. deallocated before the next instruction or has
  4588. been loaded with a new value }
  4589. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4590. begin
  4591. { We can remove the original MOV }
  4592. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4593. RemoveCurrentp(p, hp1);
  4594. JumpTracking.Free;
  4595. Result := True;
  4596. Exit;
  4597. end;
  4598. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4599. begin
  4600. { See if there's more we can optimise }
  4601. hp3 := hp2;
  4602. Continue;
  4603. end;
  4604. end;
  4605. end;
  4606. end;
  4607. { Break out of the while loop under normal circumstances }
  4608. Break;
  4609. end;
  4610. JumpTracking.Free;
  4611. end;
  4612. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4613. (taicpu(p).oper[1]^.typ = top_reg) and
  4614. (taicpu(p).opsize = S_L) and
  4615. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4616. (hp2.typ = ait_instruction) and
  4617. (taicpu(hp2).opcode = A_AND) and
  4618. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4619. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4620. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4621. ) then
  4622. begin
  4623. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4624. begin
  4625. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4626. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4627. begin
  4628. { Optimize out:
  4629. mov x, %reg
  4630. and ffffffffh, %reg
  4631. }
  4632. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4633. RemoveInstruction(hp2);
  4634. Result:=true;
  4635. exit;
  4636. end;
  4637. end;
  4638. end;
  4639. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4640. x >= RetOffset) as it doesn't do anything (it writes either to a
  4641. parameter or to the temporary storage room for the function
  4642. result)
  4643. }
  4644. if IsExitCode(hp1) and
  4645. (taicpu(p).oper[1]^.typ = top_ref) and
  4646. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4647. (
  4648. (
  4649. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4650. not (
  4651. assigned(current_procinfo.procdef.funcretsym) and
  4652. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4653. )
  4654. ) or
  4655. { Also discard writes to the stack that are below the base pointer,
  4656. as this is temporary storage rather than a function result on the
  4657. stack, say. }
  4658. (
  4659. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4660. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4661. )
  4662. ) then
  4663. begin
  4664. RemoveCurrentp(p, hp1);
  4665. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4666. RemoveLastDeallocForFuncRes(p);
  4667. Result:=true;
  4668. exit;
  4669. end;
  4670. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4671. begin
  4672. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4673. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4674. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4675. begin
  4676. { change
  4677. mov reg1, mem1
  4678. test/cmp x, mem1
  4679. to
  4680. mov reg1, mem1
  4681. test/cmp x, reg1
  4682. }
  4683. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4684. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4685. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4686. Result := True;
  4687. Exit;
  4688. end;
  4689. if DoMovCmpMemOpt(p, hp1) then
  4690. begin
  4691. Result := True;
  4692. Exit;
  4693. end;
  4694. end;
  4695. if (taicpu(p).oper[1]^.typ = top_reg) and
  4696. (hp1.typ = ait_instruction) and
  4697. GetNextInstruction(hp1, hp2) and
  4698. MatchInstruction(hp2,A_MOV,[]) and
  4699. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4700. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4701. (
  4702. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4703. {$ifdef x86_64}
  4704. or
  4705. (
  4706. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4707. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4708. )
  4709. {$endif x86_64}
  4710. ) then
  4711. begin
  4712. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4713. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4714. { change movsX/movzX reg/ref, reg2
  4715. add/sub/or/... reg3/$const, reg2
  4716. mov reg2 reg/ref
  4717. dealloc reg2
  4718. to
  4719. add/sub/or/... reg3/$const, reg/ref }
  4720. begin
  4721. TransferUsedRegs(TmpUsedRegs);
  4722. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4723. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4724. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4725. begin
  4726. { by example:
  4727. movswl %si,%eax movswl %si,%eax p
  4728. decl %eax addl %edx,%eax hp1
  4729. movw %ax,%si movw %ax,%si hp2
  4730. ->
  4731. movswl %si,%eax movswl %si,%eax p
  4732. decw %eax addw %edx,%eax hp1
  4733. movw %ax,%si movw %ax,%si hp2
  4734. }
  4735. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4736. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4737. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4738. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4739. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4740. {
  4741. ->
  4742. movswl %si,%eax movswl %si,%eax p
  4743. decw %si addw %dx,%si hp1
  4744. movw %ax,%si movw %ax,%si hp2
  4745. }
  4746. case taicpu(hp1).ops of
  4747. 1:
  4748. begin
  4749. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4750. if taicpu(hp1).oper[0]^.typ=top_reg then
  4751. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4752. end;
  4753. 2:
  4754. begin
  4755. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4756. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4757. (taicpu(hp1).opcode<>A_SHL) and
  4758. (taicpu(hp1).opcode<>A_SHR) and
  4759. (taicpu(hp1).opcode<>A_SAR) then
  4760. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4761. end;
  4762. else
  4763. internalerror(2008042701);
  4764. end;
  4765. {
  4766. ->
  4767. decw %si addw %dx,%si p
  4768. }
  4769. RemoveInstruction(hp2);
  4770. RemoveCurrentP(p, hp1);
  4771. Result:=True;
  4772. Exit;
  4773. end;
  4774. end;
  4775. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4776. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4777. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4778. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4779. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4780. ) and
  4781. { if ref contains a symbol, we cannot change its size to a smaller size }
  4782. ((taicpu(p).oper[0]^.typ<>top_ref) or (taicpu(p).oper[0]^.ref^.symbol=nil) or
  4783. (topsize2memsize[taicpu(p).opsize]<=topsize2memsize[taicpu(hp2).opsize])
  4784. )
  4785. {$ifdef i386}
  4786. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4787. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4788. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4789. {$endif i386}
  4790. then
  4791. { change movsX/movzX reg/ref, reg2
  4792. add/sub/or/... regX/$const, reg2
  4793. mov reg2, reg3
  4794. dealloc reg2
  4795. to
  4796. movsX/movzX reg/ref, reg3
  4797. add/sub/or/... reg3/$const, reg3
  4798. }
  4799. begin
  4800. TransferUsedRegs(TmpUsedRegs);
  4801. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4802. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4803. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4804. begin
  4805. { by example:
  4806. movswl %si,%eax movswl %si,%eax p
  4807. decl %eax addl %edx,%eax hp1
  4808. movw %ax,%si movw %ax,%si hp2
  4809. ->
  4810. movswl %si,%eax movswl %si,%eax p
  4811. decw %eax addw %edx,%eax hp1
  4812. movw %ax,%si movw %ax,%si hp2
  4813. }
  4814. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4815. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4816. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4817. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4818. { limit size of constants as well to avoid assembler errors, but
  4819. check opsize to avoid overflow when left shifting the 1 }
  4820. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4821. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4822. {$ifdef x86_64}
  4823. { Be careful of, for example:
  4824. movl %reg1,%reg2
  4825. addl %reg3,%reg2
  4826. movq %reg2,%reg4
  4827. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4828. }
  4829. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4830. begin
  4831. taicpu(hp2).changeopsize(S_L);
  4832. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4833. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4834. end;
  4835. {$endif x86_64}
  4836. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4837. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4838. if taicpu(p).oper[0]^.typ=top_reg then
  4839. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4840. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4841. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4842. {
  4843. ->
  4844. movswl %si,%eax movswl %si,%eax p
  4845. decw %si addw %dx,%si hp1
  4846. movw %ax,%si movw %ax,%si hp2
  4847. }
  4848. case taicpu(hp1).ops of
  4849. 1:
  4850. begin
  4851. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4852. if taicpu(hp1).oper[0]^.typ=top_reg then
  4853. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4854. end;
  4855. 2:
  4856. begin
  4857. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4858. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4859. (taicpu(hp1).opcode<>A_SHL) and
  4860. (taicpu(hp1).opcode<>A_SHR) and
  4861. (taicpu(hp1).opcode<>A_SAR) then
  4862. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4863. end;
  4864. else
  4865. internalerror(2018111801);
  4866. end;
  4867. {
  4868. ->
  4869. decw %si addw %dx,%si p
  4870. }
  4871. RemoveInstruction(hp2);
  4872. end;
  4873. end;
  4874. end;
  4875. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4876. GetNextInstruction(hp1, hp2) and
  4877. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4878. MatchOperand(Taicpu(p).oper[0]^,0) and
  4879. (Taicpu(p).oper[1]^.typ = top_reg) and
  4880. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4881. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4882. { mov reg1,0
  4883. bts reg1,operand1 --> mov reg1,operand2
  4884. or reg1,operand2 bts reg1,operand1}
  4885. begin
  4886. Taicpu(hp2).opcode:=A_MOV;
  4887. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4888. asml.remove(hp1);
  4889. insertllitem(hp2,hp2.next,hp1);
  4890. RemoveCurrentp(p, hp1);
  4891. Result:=true;
  4892. exit;
  4893. end;
  4894. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4895. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4896. GetNextInstruction(hp1, hp2) and
  4897. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4898. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4899. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4900. { change
  4901. mov reg1,reg2
  4902. sub reg3,reg2
  4903. cmp reg3,reg1
  4904. into
  4905. mov reg1,reg2
  4906. sub reg3,reg2
  4907. }
  4908. begin
  4909. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4910. RemoveInstruction(hp2);
  4911. Result:=true;
  4912. exit;
  4913. end;
  4914. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4915. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4916. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4917. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4918. begin
  4919. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4920. {$ifdef x86_64}
  4921. { Convert:
  4922. movq x(ref),%reg64
  4923. shrq y,%reg64
  4924. To:
  4925. movl x+4(ref),%reg32
  4926. shrl y-32,%reg32 (Remove if y = 32)
  4927. }
  4928. if (taicpu(p).opsize = S_Q) and
  4929. (taicpu(hp1).opcode = A_SHR) and
  4930. (taicpu(hp1).oper[0]^.val >= 32) then
  4931. begin
  4932. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4933. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4934. { Convert to 32-bit }
  4935. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4936. taicpu(p).opsize := S_L;
  4937. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4938. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4939. if (taicpu(hp1).oper[0]^.val = 32) then
  4940. begin
  4941. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4942. RemoveInstruction(hp1);
  4943. end
  4944. else
  4945. begin
  4946. { This will potentially open up more arithmetic operations since
  4947. the peephole optimizer now has a big hint that only the lower
  4948. 32 bits are currently in use (and opcodes are smaller in size) }
  4949. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4950. taicpu(hp1).opsize := S_L;
  4951. Dec(taicpu(hp1).oper[0]^.val, 32);
  4952. DebugMsg(SPeepholeOptimization + PreMessage +
  4953. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4954. end;
  4955. Result := True;
  4956. Exit;
  4957. end;
  4958. {$endif x86_64}
  4959. { Convert:
  4960. movl x(ref),%reg
  4961. shrl $24,%reg
  4962. To:
  4963. movzbl x+3(ref),%reg
  4964. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4965. Also accept sar instead of shr, but convert to movsx instead of movzx
  4966. }
  4967. if taicpu(hp1).opcode = A_SHR then
  4968. MovUnaligned := A_MOVZX
  4969. else
  4970. MovUnaligned := A_MOVSX;
  4971. NewSize := S_NO;
  4972. NewOffset := 0;
  4973. case taicpu(p).opsize of
  4974. S_B:
  4975. { No valid combinations };
  4976. S_W:
  4977. if (taicpu(hp1).oper[0]^.val = 8) then
  4978. begin
  4979. NewSize := S_BW;
  4980. NewOffset := 1;
  4981. end;
  4982. S_L:
  4983. case taicpu(hp1).oper[0]^.val of
  4984. 16:
  4985. begin
  4986. NewSize := S_WL;
  4987. NewOffset := 2;
  4988. end;
  4989. 24:
  4990. begin
  4991. NewSize := S_BL;
  4992. NewOffset := 3;
  4993. end;
  4994. else
  4995. ;
  4996. end;
  4997. {$ifdef x86_64}
  4998. S_Q:
  4999. case taicpu(hp1).oper[0]^.val of
  5000. 32:
  5001. begin
  5002. if taicpu(hp1).opcode = A_SAR then
  5003. begin
  5004. { 32-bit to 64-bit is a distinct instruction }
  5005. MovUnaligned := A_MOVSXD;
  5006. NewSize := S_LQ;
  5007. NewOffset := 4;
  5008. end
  5009. else
  5010. { Should have been handled by MovShr2Mov above }
  5011. InternalError(2022081811);
  5012. end;
  5013. 48:
  5014. begin
  5015. NewSize := S_WQ;
  5016. NewOffset := 6;
  5017. end;
  5018. 56:
  5019. begin
  5020. NewSize := S_BQ;
  5021. NewOffset := 7;
  5022. end;
  5023. else
  5024. ;
  5025. end;
  5026. {$endif x86_64}
  5027. else
  5028. InternalError(2022081810);
  5029. end;
  5030. if (NewSize <> S_NO) and
  5031. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  5032. begin
  5033. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  5034. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  5035. debug_op2str(MovUnaligned);
  5036. {$ifdef x86_64}
  5037. if MovUnaligned <> A_MOVSXD then
  5038. { Don't add size suffix for MOVSXD }
  5039. {$endif x86_64}
  5040. PreMessage := PreMessage + debug_opsize2str(NewSize);
  5041. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  5042. taicpu(p).opcode := MovUnaligned;
  5043. taicpu(p).opsize := NewSize;
  5044. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  5045. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  5046. RemoveInstruction(hp1);
  5047. Result := True;
  5048. Exit;
  5049. end;
  5050. end;
  5051. { Backward optimisation shared with OptPass2MOV }
  5052. if FuncMov2Func(p, hp1) then
  5053. begin
  5054. Result := True;
  5055. Exit;
  5056. end;
  5057. end;
  5058. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  5059. var
  5060. hp1 : tai;
  5061. begin
  5062. Result:=false;
  5063. if taicpu(p).ops <> 2 then
  5064. exit;
  5065. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  5066. GetNextInstruction(p,hp1) then
  5067. begin
  5068. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5069. (taicpu(hp1).ops = 2) then
  5070. begin
  5071. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  5072. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  5073. { movXX reg1, mem1 or movXX mem1, reg1
  5074. movXX mem2, reg2 movXX reg2, mem2}
  5075. begin
  5076. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  5077. { movXX reg1, mem1 or movXX mem1, reg1
  5078. movXX mem2, reg1 movXX reg2, mem1}
  5079. begin
  5080. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5081. begin
  5082. { Removes the second statement from
  5083. movXX reg1, mem1/reg2
  5084. movXX mem1/reg2, reg1
  5085. }
  5086. if taicpu(p).oper[0]^.typ=top_reg then
  5087. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  5088. { Removes the second statement from
  5089. movXX mem1/reg1, reg2
  5090. movXX reg2, mem1/reg1
  5091. }
  5092. if (taicpu(p).oper[1]^.typ=top_reg) and
  5093. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  5094. begin
  5095. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  5096. RemoveInstruction(hp1);
  5097. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5098. Result:=true;
  5099. exit;
  5100. end
  5101. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5102. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5103. begin
  5104. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5105. RemoveInstruction(hp1);
  5106. Result:=true;
  5107. exit;
  5108. end;
  5109. end
  5110. end;
  5111. end;
  5112. end;
  5113. end;
  5114. end;
  5115. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5116. var
  5117. hp1 : tai;
  5118. begin
  5119. result:=false;
  5120. { replace
  5121. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5122. MovX %mreg2,%mreg1
  5123. dealloc %mreg2
  5124. by
  5125. <Op>X %mreg2,%mreg1
  5126. ?
  5127. }
  5128. if GetNextInstruction(p,hp1) and
  5129. { we mix single and double opperations here because we assume that the compiler
  5130. generates vmovapd only after double operations and vmovaps only after single operations }
  5131. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5132. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5133. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5134. (taicpu(p).oper[0]^.typ=top_reg) then
  5135. begin
  5136. TransferUsedRegs(TmpUsedRegs);
  5137. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5138. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5139. begin
  5140. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5141. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5142. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5143. RemoveInstruction(hp1);
  5144. result:=true;
  5145. end;
  5146. end;
  5147. end;
  5148. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5149. var
  5150. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5151. JumpLabel, JumpLabel_dist: TAsmLabel;
  5152. FirstValue, SecondValue: TCGInt;
  5153. function OptimizeJump(var InputP: tai): Boolean;
  5154. var
  5155. TempBool: Boolean;
  5156. begin
  5157. Result := False;
  5158. TempBool := True;
  5159. if DoJumpOptimizations(InputP, TempBool) or
  5160. not TempBool then
  5161. begin
  5162. Result := True;
  5163. if Assigned(InputP) then
  5164. begin
  5165. { CollapseZeroDistJump will be set to the label or an align
  5166. before it after the jump if it optimises, whether or not
  5167. the label is live or dead }
  5168. if (InputP.typ = ait_align) or
  5169. (
  5170. (InputP.typ = ait_label) and
  5171. not (tai_label(InputP).labsym.is_used)
  5172. ) then
  5173. GetNextInstruction(InputP, InputP);
  5174. end;
  5175. Exit;
  5176. end;
  5177. end;
  5178. begin
  5179. Result := False;
  5180. if (taicpu(p).oper[0]^.typ = top_const) and
  5181. (taicpu(p).oper[0]^.val <> -1) then
  5182. begin
  5183. { Convert unsigned maximum constants to -1 to aid optimisation }
  5184. case taicpu(p).opsize of
  5185. S_B:
  5186. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5187. begin
  5188. taicpu(p).oper[0]^.val := -1;
  5189. Result := True;
  5190. Exit;
  5191. end;
  5192. S_W:
  5193. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5194. begin
  5195. taicpu(p).oper[0]^.val := -1;
  5196. Result := True;
  5197. Exit;
  5198. end;
  5199. S_L:
  5200. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5201. begin
  5202. taicpu(p).oper[0]^.val := -1;
  5203. Result := True;
  5204. Exit;
  5205. end;
  5206. {$ifdef x86_64}
  5207. S_Q:
  5208. { Storing anything greater than $7FFFFFFF is not possible so do
  5209. nothing };
  5210. {$endif x86_64}
  5211. else
  5212. InternalError(2021121001);
  5213. end;
  5214. end;
  5215. if GetNextInstruction(p, hp1) and
  5216. TrySwapMovCmp(p, hp1) then
  5217. begin
  5218. Result := True;
  5219. Exit;
  5220. end;
  5221. p_label := nil;
  5222. JumpLabel := nil;
  5223. if MatchInstruction(hp1, A_Jcc, []) then
  5224. begin
  5225. if OptimizeJump(hp1) then
  5226. begin
  5227. Result := True;
  5228. if Assigned(hp1) then
  5229. begin
  5230. { CollapseZeroDistJump will be set to the label or an align
  5231. before it after the jump if it optimises, whether or not
  5232. the label is live or dead }
  5233. if (hp1.typ = ait_align) or
  5234. (
  5235. (hp1.typ = ait_label) and
  5236. not (tai_label(hp1).labsym.is_used)
  5237. ) then
  5238. GetNextInstruction(hp1, hp1);
  5239. end;
  5240. TransferUsedRegs(TmpUsedRegs);
  5241. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5242. if not Assigned(hp1) or
  5243. (
  5244. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5245. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5246. ) then
  5247. begin
  5248. { No more conditional jumps; conditional statement is no longer required }
  5249. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5250. RemoveCurrentP(p);
  5251. end;
  5252. Exit;
  5253. end;
  5254. if IsJumpToLabel(taicpu(hp1)) then
  5255. begin
  5256. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5257. if Assigned(JumpLabel) then
  5258. p_label := getlabelwithsym(JumpLabel);
  5259. end;
  5260. end;
  5261. { Search for:
  5262. test $x,(reg/ref)
  5263. jne @lbl1
  5264. test $y,(reg/ref) (same register or reference)
  5265. jne @lbl1
  5266. Change to:
  5267. test $(x or y),(reg/ref)
  5268. jne @lbl1
  5269. (Note, this doesn't work with je instead of jne)
  5270. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5271. Also search for:
  5272. test $x,(reg/ref)
  5273. je @lbl1
  5274. ...
  5275. test $y,(reg/ref)
  5276. je/jne @lbl2
  5277. If (x or y) = x, then the second jump is deterministic
  5278. }
  5279. if (
  5280. (
  5281. (taicpu(p).oper[0]^.typ = top_const) or
  5282. (
  5283. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5284. (taicpu(p).oper[0]^.typ = top_reg) and
  5285. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5286. )
  5287. ) and
  5288. MatchInstruction(hp1, A_JCC, [])
  5289. ) then
  5290. begin
  5291. if (taicpu(p).oper[0]^.typ = top_reg) and
  5292. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5293. FirstValue := -1
  5294. else
  5295. FirstValue := taicpu(p).oper[0]^.val;
  5296. { If we have several test/jne's in a row, it might be the case that
  5297. the second label doesn't go to the same location, but the one
  5298. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5299. so accommodate for this with a while loop.
  5300. }
  5301. hp1_last := hp1;
  5302. while (
  5303. (
  5304. (taicpu(p).oper[1]^.typ = top_reg) and
  5305. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5306. ) or GetNextInstruction(hp1_last, p_dist)
  5307. ) and (p_dist.typ = ait_instruction) do
  5308. begin
  5309. if (
  5310. (
  5311. (taicpu(p_dist).opcode = A_TEST) and
  5312. (
  5313. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5314. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5315. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5316. )
  5317. ) or
  5318. (
  5319. { cmp 0,%reg = test %reg,%reg }
  5320. (taicpu(p_dist).opcode = A_CMP) and
  5321. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5322. )
  5323. ) and
  5324. { Make sure the destination operands are actually the same }
  5325. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5326. GetNextInstruction(p_dist, hp1_dist) and
  5327. MatchInstruction(hp1_dist, A_JCC, []) then
  5328. begin
  5329. if OptimizeJump(hp1_dist) then
  5330. begin
  5331. Result := True;
  5332. Exit;
  5333. end;
  5334. if
  5335. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5336. (
  5337. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5338. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5339. ) then
  5340. SecondValue := -1
  5341. else
  5342. SecondValue := taicpu(p_dist).oper[0]^.val;
  5343. { If both of the TEST constants are identical, delete the
  5344. second TEST that is unnecessary (be careful though, just
  5345. in case the flags are modified in between) }
  5346. if (FirstValue = SecondValue) then
  5347. begin
  5348. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5349. begin
  5350. { Since the second jump's condition is a subset of the first, we
  5351. know it will never branch because the first jump dominates it.
  5352. Get it out of the way now rather than wait for the jump
  5353. optimisations for a speed boost. }
  5354. if IsJumpToLabel(taicpu(hp1_dist)) then
  5355. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5356. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5357. RemoveInstruction(hp1_dist);
  5358. Result := True;
  5359. end
  5360. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5361. begin
  5362. { If the inverse of the first condition is a subset of the second,
  5363. the second one will definitely branch if the first one doesn't }
  5364. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5365. { We can remove the TEST instruction too }
  5366. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5367. RemoveInstruction(p_dist);
  5368. MakeUnconditional(taicpu(hp1_dist));
  5369. RemoveDeadCodeAfterJump(hp1_dist);
  5370. { Since the jump is now unconditional, we can't
  5371. continue any further with this particular
  5372. optimisation. The original TEST is still intact
  5373. though, so there might be something else we can
  5374. do }
  5375. Include(OptsToCheck, aoc_ForceNewIteration);
  5376. Break;
  5377. end;
  5378. if Result or
  5379. { If a jump wasn't removed or made unconditional, only
  5380. remove the identical TEST instruction if the flags
  5381. weren't modified }
  5382. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5383. begin
  5384. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5385. RemoveInstruction(p_dist);
  5386. { If the jump was removed or made unconditional, we
  5387. don't need to allocate NR_DEFAULTFLAGS over the
  5388. entire range }
  5389. if not Result then
  5390. begin
  5391. { Mark the flags as 'in use' over the entire range }
  5392. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5393. { Speed gain - continue search from the Jcc instruction }
  5394. hp1_last := hp1_dist;
  5395. { Only the TEST instruction was removed, and the
  5396. original was unchanged, so we can safely do
  5397. another iteration of the while loop }
  5398. Include(OptsToCheck, aoc_ForceNewIteration);
  5399. Continue;
  5400. end;
  5401. Exit;
  5402. end;
  5403. end;
  5404. hp1_last := nil;
  5405. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5406. (
  5407. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5408. { Always adjacent under -O2 and under }
  5409. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5410. (
  5411. GetNextInstruction(hp1, hp1_last) and
  5412. (hp1_last = p_dist)
  5413. )
  5414. ) and
  5415. (
  5416. (
  5417. { Test the following variant:
  5418. test $x,(reg/ref)
  5419. jne @lbl1
  5420. test $y,(reg/ref)
  5421. je @lbl2
  5422. @lbl1:
  5423. Becomes:
  5424. test $(x or y),(reg/ref)
  5425. je @lbl2
  5426. @lbl1: (may become a dead label)
  5427. }
  5428. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5429. GetNextInstruction(hp1_dist, hp1_last) and
  5430. (hp1_last = p_label)
  5431. ) or
  5432. (
  5433. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5434. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5435. then the second jump will never branch, so it can also be
  5436. removed regardless of where it goes }
  5437. (
  5438. (FirstValue = -1) or
  5439. (SecondValue = -1) or
  5440. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5441. )
  5442. )
  5443. ) then
  5444. begin
  5445. { Same jump location... can be a register since nothing's changed }
  5446. { If any of the entries are equivalent to test %reg,%reg, then the
  5447. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5448. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5449. if (hp1_last = p_label) then
  5450. begin
  5451. { Variant }
  5452. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5453. RemoveInstruction(p_dist);
  5454. if Assigned(JumpLabel) then
  5455. JumpLabel.decrefs;
  5456. RemoveInstruction(hp1);
  5457. end
  5458. else
  5459. begin
  5460. { Only remove the second test if no jumps or other conditional instructions follow }
  5461. TransferUsedRegs(TmpUsedRegs);
  5462. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5463. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5464. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5465. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5466. begin
  5467. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5468. RemoveInstruction(p_dist);
  5469. { Remove the first jump, not the second, to keep
  5470. any register deallocations between the second
  5471. TEST/JNE pair in the same place. Aids future
  5472. optimisation. }
  5473. if Assigned(JumpLabel) then
  5474. JumpLabel.decrefs;
  5475. RemoveInstruction(hp1);
  5476. end
  5477. else
  5478. begin
  5479. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5480. if IsJumpToLabel(taicpu(hp1_dist)) then
  5481. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5482. { Remove second jump in this instance }
  5483. RemoveInstruction(hp1_dist);
  5484. end;
  5485. end;
  5486. Result := True;
  5487. Exit;
  5488. end;
  5489. end;
  5490. if { If -O2 and under, it may stop on any old instruction }
  5491. (cs_opt_level3 in current_settings.optimizerswitches) and
  5492. (taicpu(p).oper[1]^.typ = top_reg) and
  5493. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5494. begin
  5495. hp1_last := p_dist;
  5496. Continue;
  5497. end;
  5498. Break;
  5499. end;
  5500. end;
  5501. { Search for:
  5502. test %reg,%reg
  5503. j(c1) @lbl1
  5504. ...
  5505. @lbl:
  5506. test %reg,%reg (same register)
  5507. j(c2) @lbl2
  5508. If c2 is a subset of c1, change to:
  5509. test %reg,%reg
  5510. j(c1) @lbl2
  5511. (@lbl1 may become a dead label as a result)
  5512. }
  5513. if (taicpu(p).oper[1]^.typ = top_reg) and
  5514. (taicpu(p).oper[0]^.typ = top_reg) and
  5515. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5516. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5517. Assigned(p_label) and
  5518. GetNextInstruction(p_label, p_dist) and
  5519. MatchInstruction(p_dist, A_TEST, []) and
  5520. { It's fine if the second test uses smaller sub-registers }
  5521. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5522. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5523. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5524. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5525. GetNextInstruction(p_dist, hp1_dist) and
  5526. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5527. begin
  5528. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5529. if JumpLabel = JumpLabel_dist then
  5530. { This is an infinite loop }
  5531. Exit;
  5532. { Best optimisation when the first condition is a subset (or equal) of the second }
  5533. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5534. begin
  5535. { Any registers used here will already be allocated }
  5536. if Assigned(JumpLabel) then
  5537. JumpLabel.DecRefs;
  5538. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5539. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5540. Result := True;
  5541. Exit;
  5542. end;
  5543. end;
  5544. end;
  5545. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5546. var
  5547. hp1, hp2: tai;
  5548. ActiveReg: TRegister;
  5549. OldOffset: asizeint;
  5550. ThisConst: TCGInt;
  5551. function RegDeallocated: Boolean;
  5552. begin
  5553. TransferUsedRegs(TmpUsedRegs);
  5554. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5555. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5556. end;
  5557. begin
  5558. result:=false;
  5559. hp1 := nil;
  5560. { replace
  5561. addX const,%reg1
  5562. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5563. dealloc %reg1
  5564. by
  5565. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5566. }
  5567. if MatchOpType(taicpu(p),top_const,top_reg) then
  5568. begin
  5569. ActiveReg := taicpu(p).oper[1]^.reg;
  5570. { Ensures the entire register was updated }
  5571. if (taicpu(p).opsize >= S_L) and
  5572. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5573. MatchInstruction(hp1,A_LEA,[]) and
  5574. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5575. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5576. (
  5577. { Cover the case where the register in the reference is also the destination register }
  5578. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5579. (
  5580. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5581. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5582. RegDeallocated
  5583. )
  5584. ) then
  5585. begin
  5586. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5587. {$push}
  5588. {$R-}{$Q-}
  5589. { Explicitly disable overflow checking for these offset calculation
  5590. as those do not matter for the final result }
  5591. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5592. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5593. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5594. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5595. {$pop}
  5596. {$ifdef x86_64}
  5597. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5598. begin
  5599. { Overflow; abort }
  5600. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5601. end
  5602. else
  5603. {$endif x86_64}
  5604. begin
  5605. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5606. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5607. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5608. RemoveCurrentP(p, hp1)
  5609. else
  5610. RemoveCurrentP(p);
  5611. result:=true;
  5612. Exit;
  5613. end;
  5614. end;
  5615. if (
  5616. { Save calling GetNextInstructionUsingReg again }
  5617. Assigned(hp1) or
  5618. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5619. ) and
  5620. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5621. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5622. begin
  5623. { Make sure the flags aren't in use by the second operation }
  5624. TransferUsedRegs(TmpUsedRegs);
  5625. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  5626. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5627. begin
  5628. if taicpu(hp1).oper[0]^.typ = top_const then
  5629. begin
  5630. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5631. if taicpu(hp1).opcode = A_ADD then
  5632. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5633. else
  5634. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5635. Result := True;
  5636. { Handle any overflows }
  5637. case taicpu(p).opsize of
  5638. S_B:
  5639. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5640. S_W:
  5641. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5642. S_L:
  5643. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5644. {$ifdef x86_64}
  5645. S_Q:
  5646. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5647. { Overflow; abort }
  5648. Result := False
  5649. else
  5650. taicpu(p).oper[0]^.val := ThisConst;
  5651. {$endif x86_64}
  5652. else
  5653. InternalError(2021102610);
  5654. end;
  5655. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5656. if Result then
  5657. begin
  5658. if (taicpu(p).oper[0]^.val < 0) and
  5659. (
  5660. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5661. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5662. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5663. ) then
  5664. begin
  5665. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5666. taicpu(p).opcode := A_SUB;
  5667. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5668. end
  5669. else
  5670. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5671. RemoveInstruction(hp1);
  5672. end;
  5673. end
  5674. else
  5675. begin
  5676. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5677. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5678. Asml.Remove(p);
  5679. Asml.InsertAfter(p, hp1);
  5680. p := hp1;
  5681. Result := True;
  5682. Exit;
  5683. end;
  5684. end;
  5685. end;
  5686. if DoArithCombineOpt(p) then
  5687. Result:=true;
  5688. end;
  5689. end;
  5690. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5691. var
  5692. hp1, hp2: tai;
  5693. ref: Integer;
  5694. saveref: treference;
  5695. offsetcalc: Int64;
  5696. TempReg: TRegister;
  5697. Multiple: TCGInt;
  5698. Adjacent, IntermediateRegDiscarded: Boolean;
  5699. begin
  5700. Result:=false;
  5701. { play save and throw an error if LEA uses a seg register prefix,
  5702. this is most likely an error somewhere else }
  5703. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5704. internalerror(2022022001);
  5705. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5706. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5707. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5708. (
  5709. { do not mess with leas accessing the stack pointer
  5710. unless it's a null operation }
  5711. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5712. (
  5713. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5714. (taicpu(p).oper[0]^.ref^.offset = 0)
  5715. )
  5716. ) and
  5717. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5718. begin
  5719. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5720. begin
  5721. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5722. begin
  5723. taicpu(p).opcode := A_MOV;
  5724. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5725. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5726. end
  5727. else
  5728. begin
  5729. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5730. RemoveCurrentP(p);
  5731. end;
  5732. Result:=true;
  5733. exit;
  5734. end
  5735. else if (
  5736. { continue to use lea to adjust the stack pointer,
  5737. it is the recommended way, but only if not optimizing for size }
  5738. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5739. (cs_opt_size in current_settings.optimizerswitches)
  5740. ) and
  5741. { If the flags register is in use, don't change the instruction
  5742. to an ADD otherwise this will scramble the flags. [Kit] }
  5743. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5744. ConvertLEA(taicpu(p)) then
  5745. begin
  5746. Result:=true;
  5747. exit;
  5748. end;
  5749. end;
  5750. { Don't optimise if the stack or frame pointer is the destination register }
  5751. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5752. Exit;
  5753. if GetNextInstruction(p,hp1) and
  5754. (hp1.typ=ait_instruction) then
  5755. begin
  5756. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5757. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5758. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5759. begin
  5760. TransferUsedRegs(TmpUsedRegs);
  5761. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5762. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5763. begin
  5764. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5765. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5766. RemoveInstruction(hp1);
  5767. result:=true;
  5768. exit;
  5769. end;
  5770. end;
  5771. { changes
  5772. lea <ref1>, reg1
  5773. <op> ...,<ref. with reg1>,...
  5774. to
  5775. <op> ...,<ref1>,... }
  5776. { find a reference which uses reg1 }
  5777. 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
  5778. ref:=0
  5779. 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
  5780. ref:=1
  5781. else
  5782. ref:=-1;
  5783. if (ref<>-1) and
  5784. { reg1 must be either the base or the index }
  5785. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5786. begin
  5787. { reg1 can be removed from the reference }
  5788. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5789. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5790. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5791. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5792. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5793. else
  5794. Internalerror(2019111201);
  5795. { check if the can insert all data of the lea into the second instruction }
  5796. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5797. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5798. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5799. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5800. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5801. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5802. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5803. {$ifdef x86_64}
  5804. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5805. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5806. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5807. )
  5808. {$endif x86_64}
  5809. then
  5810. begin
  5811. { reg1 might not used by the second instruction after it is remove from the reference }
  5812. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5813. begin
  5814. TransferUsedRegs(TmpUsedRegs);
  5815. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5816. { reg1 is not updated so it might not be used afterwards }
  5817. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5818. begin
  5819. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5820. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5821. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5822. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5823. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5824. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5825. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5826. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5827. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5828. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5829. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5830. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5831. RemoveCurrentP(p, hp1);
  5832. result:=true;
  5833. exit;
  5834. end
  5835. end;
  5836. end;
  5837. { recover }
  5838. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5839. end;
  5840. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5841. if Adjacent or
  5842. { Check further ahead (up to 2 instructions ahead for -O2) }
  5843. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5844. begin
  5845. { Check common LEA/LEA conditions }
  5846. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5847. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5848. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5849. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5850. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5851. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5852. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5853. (
  5854. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5855. calling it (since it calls GetNextInstruction) }
  5856. Adjacent or
  5857. (
  5858. (
  5859. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5860. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5861. ) and (
  5862. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5863. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5864. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5865. )
  5866. )
  5867. ) then
  5868. begin
  5869. TransferUsedRegs(TmpUsedRegs);
  5870. hp2 := p;
  5871. repeat
  5872. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5873. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5874. IntermediateRegDiscarded :=
  5875. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5876. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5877. { changes
  5878. lea offset1(regX,scale), reg1
  5879. lea offset2(reg1,reg1), reg2
  5880. to
  5881. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5882. and
  5883. lea offset1(regX,scale1), reg1
  5884. lea offset2(reg1,scale2), reg2
  5885. to
  5886. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5887. and
  5888. lea offset1(regX,scale1), reg1
  5889. lea offset2(reg3,reg1,scale2), reg2
  5890. to
  5891. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5892. ... so long as the final scale does not exceed 8
  5893. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5894. }
  5895. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5896. (
  5897. { Don't optimise if size is a concern and the intermediate register remains in use }
  5898. IntermediateRegDiscarded or
  5899. (
  5900. not (cs_opt_size in current_settings.optimizerswitches) and
  5901. { If the intermediate register is not discarded, it must not
  5902. appear in the first LEA's reference. (Fixes #41166) }
  5903. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  5904. )
  5905. ) and
  5906. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5907. (
  5908. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5909. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5910. ) and (
  5911. (
  5912. { lea (reg1,scale2), reg2 variant }
  5913. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5914. (
  5915. Adjacent or
  5916. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5917. ) and
  5918. (
  5919. (
  5920. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5921. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5922. ) or (
  5923. { lea (regX,regX), reg1 variant }
  5924. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5925. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5926. )
  5927. )
  5928. ) or (
  5929. { lea (reg1,reg1), reg1 variant }
  5930. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5931. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5932. )
  5933. ) then
  5934. begin
  5935. { Make everything homogeneous to make calculations easier }
  5936. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5937. begin
  5938. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5939. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5940. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5941. else
  5942. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5943. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5944. end;
  5945. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5946. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5947. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5948. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5949. begin
  5950. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5951. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5952. begin
  5953. { Put the register to change in the index register }
  5954. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5955. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5956. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5957. end;
  5958. { Change lea (reg,reg) to lea(,reg,2) }
  5959. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5960. begin
  5961. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5962. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5963. end;
  5964. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5965. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5966. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5967. { Just to prevent miscalculations }
  5968. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5969. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5970. else
  5971. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5972. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5973. if IntermediateRegDiscarded then
  5974. begin
  5975. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5976. RemoveCurrentP(p);
  5977. end
  5978. else
  5979. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5980. result:=true;
  5981. exit;
  5982. end;
  5983. end;
  5984. { changes
  5985. lea offset1(regX), reg1
  5986. lea offset2(reg1), reg2
  5987. to
  5988. lea offset1+offset2(regX), reg2 }
  5989. if (
  5990. { Don't optimise if size is a concern and the intermediate register remains in use }
  5991. IntermediateRegDiscarded or
  5992. (
  5993. not (cs_opt_size in current_settings.optimizerswitches) and
  5994. { If the intermediate register is not discarded, it must not
  5995. appear in the first LEA's reference. (Fixes #41166) }
  5996. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  5997. )
  5998. ) and
  5999. (
  6000. (
  6001. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6002. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  6003. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  6004. ) or (
  6005. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6006. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  6007. (
  6008. (
  6009. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6010. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  6011. ) or (
  6012. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  6013. (
  6014. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6015. (
  6016. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6017. (
  6018. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  6019. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  6020. )
  6021. )
  6022. )
  6023. )
  6024. )
  6025. )
  6026. ) then
  6027. begin
  6028. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6029. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6030. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6031. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6032. begin
  6033. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  6034. begin
  6035. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  6036. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6037. { if the register is used as index and base, we have to increase for base as well
  6038. and adapt base }
  6039. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  6040. begin
  6041. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6042. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6043. end;
  6044. end
  6045. else
  6046. begin
  6047. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6048. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6049. end;
  6050. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  6051. begin
  6052. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  6053. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  6054. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  6055. { Catch the situation where the base = index
  6056. and treat this as *2. The scalefactor of
  6057. p will be 0 or 1 due to the conditional
  6058. checks above. Fixes i40647 }
  6059. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  6060. else
  6061. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  6062. end;
  6063. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6064. if IntermediateRegDiscarded then
  6065. begin
  6066. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  6067. RemoveCurrentP(p);
  6068. end
  6069. else
  6070. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  6071. result:=true;
  6072. exit;
  6073. end;
  6074. end;
  6075. end;
  6076. { Change:
  6077. leal/q $x(%reg1),%reg2
  6078. ...
  6079. shll/q $y,%reg2
  6080. To:
  6081. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  6082. }
  6083. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6084. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  6085. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6086. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6087. (taicpu(hp1).oper[0]^.val <= 3) then
  6088. begin
  6089. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  6090. TransferUsedRegs(TmpUsedRegs);
  6091. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6092. if
  6093. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  6094. (this works even if scalefactor is zero) }
  6095. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  6096. { Ensure offset doesn't go out of bounds }
  6097. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  6098. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  6099. (
  6100. (
  6101. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  6102. (
  6103. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6104. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6105. (
  6106. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6107. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6108. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6109. )
  6110. )
  6111. ) or (
  6112. (
  6113. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6114. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6115. ) and
  6116. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6117. )
  6118. ) then
  6119. begin
  6120. repeat
  6121. with taicpu(p).oper[0]^.ref^ do
  6122. begin
  6123. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6124. if index = base then
  6125. begin
  6126. if Multiple > 4 then
  6127. { Optimisation will no longer work because resultant
  6128. scale factor will exceed 8 }
  6129. Break;
  6130. base := NR_NO;
  6131. scalefactor := 2;
  6132. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6133. end
  6134. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6135. begin
  6136. { Scale factor only works on the index register }
  6137. index := base;
  6138. base := NR_NO;
  6139. end;
  6140. { For safety }
  6141. if scalefactor <= 1 then
  6142. begin
  6143. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6144. scalefactor := Multiple;
  6145. end
  6146. else
  6147. begin
  6148. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6149. scalefactor := scalefactor * Multiple;
  6150. end;
  6151. offset := offset * Multiple;
  6152. end;
  6153. RemoveInstruction(hp1);
  6154. Result := True;
  6155. Exit;
  6156. { This repeat..until loop exists for the benefit of Break }
  6157. until True;
  6158. end;
  6159. end;
  6160. end;
  6161. end;
  6162. end;
  6163. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6164. var
  6165. hp1 : tai;
  6166. SubInstr: Boolean;
  6167. ThisConst: TCGInt;
  6168. const
  6169. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6170. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6171. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6172. begin
  6173. Result := False;
  6174. if taicpu(p).oper[0]^.typ <> top_const then
  6175. { Should have been confirmed before calling }
  6176. InternalError(2021102601);
  6177. SubInstr := (taicpu(p).opcode = A_SUB);
  6178. if not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  6179. GetLastInstruction(p, hp1) and
  6180. (hp1.typ = ait_instruction) and
  6181. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6182. begin
  6183. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6184. { Bad size }
  6185. InternalError(2022042001);
  6186. case taicpu(hp1).opcode Of
  6187. A_INC:
  6188. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6189. begin
  6190. if SubInstr then
  6191. ThisConst := taicpu(p).oper[0]^.val - 1
  6192. else
  6193. ThisConst := taicpu(p).oper[0]^.val + 1;
  6194. end
  6195. else
  6196. Exit;
  6197. A_DEC:
  6198. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6199. begin
  6200. if SubInstr then
  6201. ThisConst := taicpu(p).oper[0]^.val + 1
  6202. else
  6203. ThisConst := taicpu(p).oper[0]^.val - 1;
  6204. end
  6205. else
  6206. Exit;
  6207. A_SUB:
  6208. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6209. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6210. begin
  6211. if SubInstr then
  6212. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6213. else
  6214. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6215. end
  6216. else
  6217. Exit;
  6218. A_ADD:
  6219. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6220. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6221. begin
  6222. if SubInstr then
  6223. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6224. else
  6225. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6226. end
  6227. else
  6228. Exit;
  6229. else
  6230. Exit;
  6231. end;
  6232. { Check that the values are in range }
  6233. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6234. { Overflow; abort }
  6235. Exit;
  6236. if (ThisConst = 0) then
  6237. begin
  6238. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6239. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6240. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6241. RemoveInstruction(hp1);
  6242. hp1 := tai(p.next);
  6243. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6244. if not GetLastInstruction(hp1, p) then
  6245. p := hp1;
  6246. end
  6247. else
  6248. begin
  6249. if taicpu(hp1).opercnt=1 then
  6250. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6251. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6252. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6253. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6254. else
  6255. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6256. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6257. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6258. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6259. RemoveInstruction(hp1);
  6260. taicpu(p).loadconst(0, ThisConst);
  6261. end;
  6262. Result := True;
  6263. end;
  6264. end;
  6265. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6266. begin
  6267. Result := False;
  6268. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6269. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6270. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6271. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6272. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6273. (
  6274. (
  6275. (taicpu(hp1).opcode = A_TEST)
  6276. ) or (
  6277. (taicpu(hp1).opcode = A_CMP) and
  6278. { A sanity check more than anything }
  6279. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6280. )
  6281. ) then
  6282. begin
  6283. { change
  6284. mov mem, %reg
  6285. ...
  6286. cmp/test x, %reg / test %reg,%reg
  6287. (reg deallocated)
  6288. to
  6289. cmp/test x, mem / cmp 0, mem
  6290. }
  6291. TransferUsedRegs(TmpUsedRegs);
  6292. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6293. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6294. begin
  6295. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6296. if (taicpu(hp1).opcode = A_TEST) and
  6297. (
  6298. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6299. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6300. ) then
  6301. begin
  6302. taicpu(hp1).opcode := A_CMP;
  6303. taicpu(hp1).loadconst(0, 0);
  6304. end;
  6305. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6306. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6307. RemoveCurrentP(p);
  6308. if (p <> hp1) then
  6309. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6310. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6311. { Make sure the flags are allocated across the CMP instruction }
  6312. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6313. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6314. Result := True;
  6315. Exit;
  6316. end;
  6317. end;
  6318. end;
  6319. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6320. var
  6321. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6322. ThisReg, SecondReg: TRegister;
  6323. JumpLoc: TAsmLabel;
  6324. NewSize: TOpSize;
  6325. begin
  6326. Result := False;
  6327. {
  6328. Convert:
  6329. j<c> .L1
  6330. .L2:
  6331. mov 1,reg
  6332. jmp .L3 (or ret, although it might not be a RET yet)
  6333. .L1:
  6334. mov 0,reg
  6335. jmp .L3 (or ret)
  6336. ( As long as .L3 <> .L1 or .L2)
  6337. To:
  6338. mov 0,reg
  6339. set<not(c)> reg
  6340. jmp .L3 (or ret)
  6341. .L2:
  6342. mov 1,reg
  6343. jmp .L3 (or ret)
  6344. .L1:
  6345. mov 0,reg
  6346. jmp .L3 (or ret)
  6347. }
  6348. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6349. Exit;
  6350. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6351. if GetNextInstruction(hp_label, hp2) and
  6352. MatchInstruction(hp2,A_MOV,[]) and
  6353. (taicpu(hp2).oper[0]^.typ = top_const) and
  6354. (
  6355. (
  6356. (taicpu(hp2).oper[1]^.typ = top_reg)
  6357. {$ifdef i386}
  6358. { Under i386, ESI, EDI, EBP and ESP
  6359. don't have an 8-bit representation }
  6360. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6361. {$endif i386}
  6362. ) or (
  6363. {$ifdef i386}
  6364. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6365. {$endif i386}
  6366. (taicpu(hp2).opsize = S_B)
  6367. )
  6368. ) and
  6369. GetNextInstruction(hp2, hp3) and
  6370. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6371. (
  6372. (taicpu(hp3).opcode=A_RET) or
  6373. (
  6374. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6375. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6376. )
  6377. ) and
  6378. GetNextInstruction(hp3, hp4) and
  6379. FindLabel(JumpLoc, hp4) and
  6380. (
  6381. not (cs_opt_size in current_settings.optimizerswitches) or
  6382. { If the initial jump is the label's only reference, then it will
  6383. become a dead label if the other conditions are met and hence
  6384. remove at least 2 instructions, including a jump }
  6385. (JumpLoc.getrefs = 1)
  6386. ) and
  6387. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6388. that will be optimised out }
  6389. GetNextInstruction(hp4, hp5) and
  6390. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6391. (taicpu(hp5).oper[0]^.typ = top_const) and
  6392. (
  6393. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6394. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6395. ) and
  6396. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6397. GetNextInstruction(hp5,hp6) and
  6398. (
  6399. not (hp6.typ in [ait_align, ait_label]) or
  6400. SkipLabels(hp6, hp6)
  6401. ) and
  6402. (hp6.typ=ait_instruction) then
  6403. begin
  6404. { First, let's look at the two jumps that are hp3 and hp6 }
  6405. if not
  6406. (
  6407. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6408. (
  6409. (taicpu(hp6).opcode=A_RET) or
  6410. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6411. )
  6412. ) then
  6413. { If condition is False, then the JMP/RET instructions matched conventionally }
  6414. begin
  6415. { See if one of the jumps can be instantly converted into a RET }
  6416. if (taicpu(hp3).opcode=A_JMP) then
  6417. begin
  6418. { Reuse hp5 }
  6419. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6420. { Make sure hp5 doesn't jump back to .L1 (zero distance jump) or .L2 (infinite loop) }
  6421. if not Assigned(hp5) or (hp5 = hp_label) or (hp5 = hp4) or not GetNextInstruction(hp5, hp5) then
  6422. Exit;
  6423. if MatchInstruction(hp5, A_RET, []) then
  6424. begin
  6425. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6426. ConvertJumpToRET(hp3, hp5);
  6427. Result := True;
  6428. end
  6429. else
  6430. Exit;
  6431. end;
  6432. if (taicpu(hp6).opcode=A_JMP) then
  6433. begin
  6434. { Reuse hp5 }
  6435. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6436. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6437. Exit;
  6438. if MatchInstruction(hp5, A_RET, []) then
  6439. begin
  6440. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6441. ConvertJumpToRET(hp6, hp5);
  6442. Result := True;
  6443. end
  6444. else
  6445. Exit;
  6446. end;
  6447. if not
  6448. (
  6449. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6450. (
  6451. (taicpu(hp6).opcode=A_RET) or
  6452. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6453. )
  6454. ) then
  6455. { Still doesn't match }
  6456. Exit;
  6457. end;
  6458. if (taicpu(hp2).oper[0]^.val = 1) then
  6459. begin
  6460. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6461. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6462. end
  6463. else
  6464. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6465. if taicpu(hp2).opsize=S_B then
  6466. begin
  6467. if taicpu(hp2).oper[1]^.typ = top_reg then
  6468. begin
  6469. SecondReg := taicpu(hp2).oper[1]^.reg;
  6470. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6471. end
  6472. else
  6473. begin
  6474. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6475. SecondReg := NR_NO;
  6476. end;
  6477. hp_pos := p;
  6478. hp_allocstart := hp4;
  6479. end
  6480. else
  6481. begin
  6482. { Will be a register because the size can't be S_B otherwise }
  6483. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6484. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6485. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6486. if (cs_opt_size in current_settings.optimizerswitches) then
  6487. begin
  6488. { Favour using MOVZX when optimising for size }
  6489. case taicpu(hp2).opsize of
  6490. S_W:
  6491. NewSize := S_BW;
  6492. S_L:
  6493. NewSize := S_BL;
  6494. {$ifdef x86_64}
  6495. S_Q:
  6496. begin
  6497. NewSize := S_BL;
  6498. { Will implicitly zero-extend to 64-bit }
  6499. setsubreg(SecondReg, R_SUBD);
  6500. end;
  6501. {$endif x86_64}
  6502. else
  6503. InternalError(2022101301);
  6504. end;
  6505. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6506. { Inserting it right before p will guarantee that the flags are also tracked }
  6507. Asml.InsertBefore(hp5, p);
  6508. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6509. hp_pos := hp5;
  6510. hp_allocstart := hp4;
  6511. end
  6512. else
  6513. begin
  6514. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6515. { Inserting it right before p will guarantee that the flags are also tracked }
  6516. Asml.InsertBefore(hp5, p);
  6517. hp_pos := p;
  6518. hp_allocstart := hp5;
  6519. end;
  6520. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6521. end;
  6522. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6523. taicpu(hp4).condition := taicpu(p).condition;
  6524. asml.InsertBefore(hp4, hp_pos);
  6525. if taicpu(hp3).is_jmp then
  6526. begin
  6527. JumpLoc.decrefs;
  6528. MakeUnconditional(taicpu(p));
  6529. { This also increases the reference count }
  6530. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6531. end
  6532. else
  6533. ConvertJumpToRET(p, hp3);
  6534. if SecondReg <> NR_NO then
  6535. { Ensure the destination register is allocated over this region }
  6536. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6537. if (JumpLoc.getrefs = 0) then
  6538. RemoveDeadCodeAfterJump(hp3);
  6539. Result:=true;
  6540. exit;
  6541. end;
  6542. end;
  6543. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6544. var
  6545. hp1, hp2: tai;
  6546. ActiveReg: TRegister;
  6547. OldOffset: asizeint;
  6548. ThisConst: TCGInt;
  6549. function RegDeallocated: Boolean;
  6550. begin
  6551. TransferUsedRegs(TmpUsedRegs);
  6552. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6553. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6554. end;
  6555. begin
  6556. Result:=false;
  6557. hp1 := nil;
  6558. { replace
  6559. subX const,%reg1
  6560. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6561. dealloc %reg1
  6562. by
  6563. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6564. }
  6565. if MatchOpType(taicpu(p),top_const,top_reg) then
  6566. begin
  6567. ActiveReg := taicpu(p).oper[1]^.reg;
  6568. { Ensures the entire register was updated }
  6569. if (taicpu(p).opsize >= S_L) and
  6570. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6571. MatchInstruction(hp1,A_LEA,[]) and
  6572. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6573. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6574. (
  6575. { Cover the case where the register in the reference is also the destination register }
  6576. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6577. (
  6578. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6579. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6580. RegDeallocated
  6581. )
  6582. ) then
  6583. begin
  6584. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6585. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.base) then
  6586. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6587. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.index) then
  6588. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6589. {$ifdef x86_64}
  6590. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6591. begin
  6592. { Overflow; abort }
  6593. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6594. end
  6595. else
  6596. {$endif x86_64}
  6597. begin
  6598. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6599. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6600. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6601. RemoveCurrentP(p, hp1)
  6602. else
  6603. RemoveCurrentP(p);
  6604. result:=true;
  6605. Exit;
  6606. end;
  6607. end;
  6608. if (
  6609. { Save calling GetNextInstructionUsingReg again }
  6610. Assigned(hp1) or
  6611. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6612. ) and
  6613. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6614. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6615. begin
  6616. { Make sure the flags aren't in use by the second operation }
  6617. TransferUsedRegs(TmpUsedRegs);
  6618. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  6619. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6620. begin
  6621. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6622. begin
  6623. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6624. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6625. Result := True;
  6626. { Handle any overflows }
  6627. case taicpu(p).opsize of
  6628. S_B:
  6629. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6630. S_W:
  6631. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6632. S_L:
  6633. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6634. {$ifdef x86_64}
  6635. S_Q:
  6636. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6637. { Overflow; abort }
  6638. Result := False
  6639. else
  6640. taicpu(p).oper[0]^.val := ThisConst;
  6641. {$endif x86_64}
  6642. else
  6643. InternalError(2021102611);
  6644. end;
  6645. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6646. if Result then
  6647. begin
  6648. if (taicpu(p).oper[0]^.val < 0) and
  6649. (
  6650. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6651. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6652. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6653. ) then
  6654. begin
  6655. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6656. taicpu(p).opcode := A_SUB;
  6657. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6658. end
  6659. else
  6660. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6661. RemoveInstruction(hp1);
  6662. end;
  6663. end
  6664. else
  6665. begin
  6666. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6667. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6668. Asml.Remove(p);
  6669. Asml.InsertAfter(p, hp1);
  6670. p := hp1;
  6671. Result := True;
  6672. Exit;
  6673. end;
  6674. end;
  6675. end;
  6676. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6677. { * change "sub/add const1, reg" or "dec reg" followed by
  6678. "sub const2, reg" to one "sub ..., reg" }
  6679. {$ifdef i386}
  6680. if (taicpu(p).oper[0]^.val = 2) and
  6681. (ActiveReg = NR_ESP) and
  6682. { Don't do the sub/push optimization if the sub }
  6683. { comes from setting up the stack frame (JM) }
  6684. (not(GetLastInstruction(p,hp1)) or
  6685. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6686. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6687. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6688. begin
  6689. hp1 := tai(p.next);
  6690. while Assigned(hp1) and
  6691. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6692. not RegReadByInstruction(NR_ESP,hp1) and
  6693. not RegModifiedByInstruction(NR_ESP,hp1) do
  6694. hp1 := tai(hp1.next);
  6695. if Assigned(hp1) and
  6696. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6697. begin
  6698. taicpu(hp1).changeopsize(S_L);
  6699. if taicpu(hp1).oper[0]^.typ=top_reg then
  6700. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6701. hp1 := tai(p.next);
  6702. RemoveCurrentp(p, hp1);
  6703. Result:=true;
  6704. exit;
  6705. end;
  6706. end;
  6707. {$endif i386}
  6708. if DoArithCombineOpt(p) then
  6709. Result:=true;
  6710. end;
  6711. end;
  6712. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6713. var
  6714. TmpBool1,TmpBool2 : Boolean;
  6715. tmpref : treference;
  6716. hp1,hp2: tai;
  6717. mask, shiftval: tcgint;
  6718. begin
  6719. Result:=false;
  6720. { All these optimisations work on "shl/sal const,%reg" }
  6721. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6722. Exit;
  6723. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6724. (taicpu(p).oper[0]^.val <= 3) then
  6725. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6726. begin
  6727. { should we check the next instruction? }
  6728. TmpBool1 := True;
  6729. { have we found an add/sub which could be
  6730. integrated in the lea? }
  6731. TmpBool2 := False;
  6732. reference_reset(tmpref,2,[]);
  6733. TmpRef.index := taicpu(p).oper[1]^.reg;
  6734. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6735. while TmpBool1 and
  6736. GetNextInstruction(p, hp1) and
  6737. (tai(hp1).typ = ait_instruction) and
  6738. ((((taicpu(hp1).opcode = A_ADD) or
  6739. (taicpu(hp1).opcode = A_SUB)) and
  6740. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6741. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6742. (((taicpu(hp1).opcode = A_INC) or
  6743. (taicpu(hp1).opcode = A_DEC)) and
  6744. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6745. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6746. ((taicpu(hp1).opcode = A_LEA) and
  6747. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6748. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6749. (not GetNextInstruction(hp1,hp2) or
  6750. not instrReadsFlags(hp2)) Do
  6751. begin
  6752. TmpBool1 := False;
  6753. if taicpu(hp1).opcode=A_LEA then
  6754. begin
  6755. if (TmpRef.base = NR_NO) and
  6756. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6757. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6758. { Segment register isn't a concern here }
  6759. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6760. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6761. begin
  6762. TmpBool1 := True;
  6763. TmpBool2 := True;
  6764. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6765. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6766. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6767. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6768. RemoveInstruction(hp1);
  6769. end
  6770. end
  6771. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6772. begin
  6773. TmpBool1 := True;
  6774. TmpBool2 := True;
  6775. case taicpu(hp1).opcode of
  6776. A_ADD:
  6777. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6778. A_SUB:
  6779. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6780. else
  6781. internalerror(2019050536);
  6782. end;
  6783. RemoveInstruction(hp1);
  6784. end
  6785. else
  6786. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6787. (((taicpu(hp1).opcode = A_ADD) and
  6788. (TmpRef.base = NR_NO)) or
  6789. (taicpu(hp1).opcode = A_INC) or
  6790. (taicpu(hp1).opcode = A_DEC)) then
  6791. begin
  6792. TmpBool1 := True;
  6793. TmpBool2 := True;
  6794. case taicpu(hp1).opcode of
  6795. A_ADD:
  6796. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6797. A_INC:
  6798. inc(TmpRef.offset);
  6799. A_DEC:
  6800. dec(TmpRef.offset);
  6801. else
  6802. internalerror(2019050535);
  6803. end;
  6804. RemoveInstruction(hp1);
  6805. end;
  6806. end;
  6807. if TmpBool2
  6808. {$ifndef x86_64}
  6809. or
  6810. ((current_settings.optimizecputype < cpu_Pentium2) and
  6811. (taicpu(p).oper[0]^.val <= 3) and
  6812. not(cs_opt_size in current_settings.optimizerswitches))
  6813. {$endif x86_64}
  6814. then
  6815. begin
  6816. if not(TmpBool2) and
  6817. (taicpu(p).oper[0]^.val=1) then
  6818. begin
  6819. taicpu(p).opcode := A_ADD;
  6820. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6821. end
  6822. else
  6823. begin
  6824. taicpu(p).opcode := A_LEA;
  6825. taicpu(p).loadref(0, TmpRef);
  6826. end;
  6827. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6828. Result := True;
  6829. end;
  6830. end
  6831. {$ifndef x86_64}
  6832. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6833. begin
  6834. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6835. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6836. (unlike shl, which is only Tairable in the U pipe) }
  6837. if taicpu(p).oper[0]^.val=1 then
  6838. begin
  6839. taicpu(p).opcode := A_ADD;
  6840. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6841. Result := True;
  6842. end
  6843. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6844. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6845. else if (taicpu(p).opsize = S_L) and
  6846. (taicpu(p).oper[0]^.val<= 3) then
  6847. begin
  6848. reference_reset(tmpref,2,[]);
  6849. TmpRef.index := taicpu(p).oper[1]^.reg;
  6850. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6851. taicpu(p).opcode := A_LEA;
  6852. taicpu(p).loadref(0, TmpRef);
  6853. Result := True;
  6854. end;
  6855. end
  6856. {$endif x86_64}
  6857. else if
  6858. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6859. (
  6860. (
  6861. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6862. SetAndTest(hp1, hp2)
  6863. {$ifdef x86_64}
  6864. ) or
  6865. (
  6866. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6867. GetNextInstruction(hp1, hp2) and
  6868. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6869. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6870. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6871. {$endif x86_64}
  6872. )
  6873. ) and
  6874. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6875. begin
  6876. { Change:
  6877. shl x, %reg1
  6878. mov -(1<<x), %reg2
  6879. and %reg2, %reg1
  6880. Or:
  6881. shl x, %reg1
  6882. and -(1<<x), %reg1
  6883. To just:
  6884. shl x, %reg1
  6885. Since the and operation only zeroes bits that are already zero from the shl operation
  6886. }
  6887. case taicpu(p).oper[0]^.val of
  6888. 8:
  6889. mask:=$FFFFFFFFFFFFFF00;
  6890. 16:
  6891. mask:=$FFFFFFFFFFFF0000;
  6892. 32:
  6893. mask:=$FFFFFFFF00000000;
  6894. 63:
  6895. { Constant pre-calculated to prevent overflow errors with Int64 }
  6896. mask:=$8000000000000000;
  6897. else
  6898. begin
  6899. if taicpu(p).oper[0]^.val >= 64 then
  6900. { Shouldn't happen realistically, since the register
  6901. is guaranteed to be set to zero at this point }
  6902. mask := 0
  6903. else
  6904. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6905. end;
  6906. end;
  6907. if taicpu(hp1).oper[0]^.val = mask then
  6908. begin
  6909. { Everything checks out, perform the optimisation, as long as
  6910. the FLAGS register isn't being used}
  6911. TransferUsedRegs(TmpUsedRegs);
  6912. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6913. {$ifdef x86_64}
  6914. if (hp1 <> hp2) then
  6915. begin
  6916. { "shl/mov/and" version }
  6917. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6918. { Don't do the optimisation if the FLAGS register is in use }
  6919. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6920. begin
  6921. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6922. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6923. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6924. begin
  6925. RemoveInstruction(hp1);
  6926. Result := True;
  6927. end;
  6928. { Only set Result to True if the 'mov' instruction was removed }
  6929. RemoveInstruction(hp2);
  6930. end;
  6931. end
  6932. else
  6933. {$endif x86_64}
  6934. begin
  6935. { "shl/and" version }
  6936. { Don't do the optimisation if the FLAGS register is in use }
  6937. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6938. begin
  6939. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6940. RemoveInstruction(hp1);
  6941. Result := True;
  6942. end;
  6943. end;
  6944. Exit;
  6945. end
  6946. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6947. begin
  6948. { Even if the mask doesn't allow for its removal, we might be
  6949. able to optimise the mask for the "shl/and" version, which
  6950. may permit other peephole optimisations }
  6951. {$ifdef DEBUG_AOPTCPU}
  6952. mask := taicpu(hp1).oper[0]^.val and mask;
  6953. if taicpu(hp1).oper[0]^.val <> mask then
  6954. begin
  6955. DebugMsg(
  6956. SPeepholeOptimization +
  6957. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6958. ' to $' + debug_tostr(mask) +
  6959. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6960. taicpu(hp1).oper[0]^.val := mask;
  6961. end;
  6962. {$else DEBUG_AOPTCPU}
  6963. { If debugging is off, just set the operand even if it's the same }
  6964. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6965. {$endif DEBUG_AOPTCPU}
  6966. end;
  6967. end;
  6968. {
  6969. change
  6970. shl/sal const,reg
  6971. <op> ...(...,reg,1),...
  6972. into
  6973. <op> ...(...,reg,1 shl const),...
  6974. if const in 1..3
  6975. }
  6976. if MatchOpType(taicpu(p), top_const, top_reg) and
  6977. (taicpu(p).oper[0]^.val in [1..3]) and
  6978. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6979. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6980. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6981. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6982. MatchOpType(taicpu(hp1),top_ref))
  6983. ) and
  6984. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6985. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6986. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6987. begin
  6988. TransferUsedRegs(TmpUsedRegs);
  6989. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6990. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6991. begin
  6992. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6993. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6994. RemoveCurrentP(p);
  6995. Result:=true;
  6996. exit;
  6997. end;
  6998. end;
  6999. if MatchOpType(taicpu(p), top_const, top_reg) and
  7000. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  7001. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  7002. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7003. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  7004. begin
  7005. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  7006. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  7007. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  7008. {$ifdef x86_64}
  7009. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  7010. {$endif x86_64}
  7011. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  7012. begin
  7013. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  7014. taicpu(hp1).opcode:=A_MOV;
  7015. taicpu(hp1).oper[0]^.val:=0;
  7016. end
  7017. else
  7018. begin
  7019. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  7020. taicpu(hp1).oper[0]^.val:=shiftval;
  7021. end;
  7022. RemoveCurrentP(p);
  7023. Result:=true;
  7024. exit;
  7025. end;
  7026. end;
  7027. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  7028. begin
  7029. case shr_size of
  7030. S_B:
  7031. { No valid combinations }
  7032. Result := False;
  7033. S_W:
  7034. Result := (Shift >= 8) and (movz_size = S_BW);
  7035. S_L:
  7036. Result :=
  7037. (Shift >= 24) { Any opsize is valid for this shift } or
  7038. ((Shift >= 16) and (movz_size = S_WL));
  7039. {$ifdef x86_64}
  7040. S_Q:
  7041. Result :=
  7042. (Shift >= 56) { Any opsize is valid for this shift } or
  7043. ((Shift >= 48) and (movz_size = S_WL));
  7044. {$endif x86_64}
  7045. else
  7046. InternalError(2022081510);
  7047. end;
  7048. end;
  7049. function TX86AsmOptimizer.HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  7050. var
  7051. hp1, hp2: tai;
  7052. IdentityMask, Shift: TCGInt;
  7053. LimitSize: Topsize;
  7054. DoNotMerge: Boolean;
  7055. begin
  7056. if not MatchInstruction(p, A_SHR, []) then
  7057. InternalError(2025040301);
  7058. Result := False;
  7059. DoNotMerge := False;
  7060. Shift := taicpu(p).oper[0]^.val;
  7061. LimitSize := taicpu(p).opsize;
  7062. hp1 := p;
  7063. repeat
  7064. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  7065. Exit;
  7066. case taicpu(hp1).opcode of
  7067. A_AND:
  7068. { Detect:
  7069. shr x, %reg
  7070. and y, %reg
  7071. If and y, %reg doesn't actually change the value of %reg (e.g. with
  7072. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  7073. (Post-peephole only)
  7074. }
  7075. if PostPeephole and
  7076. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7077. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7078. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7079. begin
  7080. { Make sure the FLAGS register isn't in use }
  7081. TransferUsedRegs(TmpUsedRegs);
  7082. hp2 := p;
  7083. repeat
  7084. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7085. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7086. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7087. begin
  7088. { Generate the identity mask }
  7089. case taicpu(p).opsize of
  7090. S_B:
  7091. IdentityMask := $FF shr Shift;
  7092. S_W:
  7093. IdentityMask := $FFFF shr Shift;
  7094. S_L:
  7095. IdentityMask := $FFFFFFFF shr Shift;
  7096. {$ifdef x86_64}
  7097. S_Q:
  7098. { We need to force the operands to be unsigned 64-bit
  7099. integers otherwise the wrong value is generated }
  7100. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  7101. {$endif x86_64}
  7102. else
  7103. InternalError(2022081501);
  7104. end;
  7105. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  7106. begin
  7107. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  7108. { All the possible 1 bits are covered, so we can remove the AND }
  7109. hp2 := tai(hp1.Previous);
  7110. RemoveInstruction(hp1);
  7111. { p wasn't actually changed, so don't set Result to True,
  7112. but a change was nonetheless made elsewhere }
  7113. Include(OptsToCheck, aoc_ForceNewIteration);
  7114. { Do another pass in case other AND or MOVZX instructions
  7115. follow }
  7116. hp1 := hp2;
  7117. Continue;
  7118. end;
  7119. end;
  7120. end;
  7121. A_TEST, A_CMP:
  7122. { Skip over relevant comparisons, but shift instructions must
  7123. now not be merged since the original value is being read }
  7124. begin
  7125. DoNotMerge := True;
  7126. Continue;
  7127. end;
  7128. A_Jcc:
  7129. { Skip over conditional jumps and relevant comparisons }
  7130. Continue;
  7131. A_MOVZX:
  7132. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  7133. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  7134. begin
  7135. { Since the original register is being read as is, subsequent
  7136. SHRs must not be merged at this point }
  7137. DoNotMerge := True;
  7138. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  7139. begin
  7140. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  7141. begin
  7142. { If the MOVZX instruction reads and writes the same register,
  7143. defer this to the post-peephole optimisation stage }
  7144. if PostPeephole then
  7145. begin
  7146. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  7147. { All the possible 1 bits are covered, so we can remove the MOVZX }
  7148. hp2 := tai(hp1.Previous);
  7149. RemoveInstruction(hp1);
  7150. hp1 := hp2;
  7151. end;
  7152. end
  7153. else { Different register target }
  7154. begin
  7155. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  7156. taicpu(hp1).opcode := A_MOV;
  7157. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  7158. case taicpu(hp1).opsize of
  7159. S_BW:
  7160. taicpu(hp1).opsize := S_W;
  7161. S_BL, S_WL:
  7162. taicpu(hp1).opsize := S_L;
  7163. else
  7164. InternalError(2022081503);
  7165. end;
  7166. { p itself hasn't changed, so no need to set Result to True }
  7167. Include(OptsToCheck, aoc_ForceNewIteration);
  7168. { See if there's anything afterwards that can be
  7169. optimised, since the input register hasn't changed }
  7170. Continue;
  7171. end;
  7172. Exit;
  7173. end
  7174. else if PostPeephole and
  7175. (Shift > 0) and
  7176. (taicpu(p).opsize = S_W) and
  7177. (taicpu(hp1).opsize = S_WL) and
  7178. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  7179. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  7180. begin
  7181. { Detect:
  7182. shr x, %ax (x > 0)
  7183. ...
  7184. movzwl %ax,%eax
  7185. -
  7186. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  7187. But first, check to see if movzwl %ax,%eax can be removed...
  7188. }
  7189. hp2 := tai(hp1.Previous);
  7190. TransferUsedRegs(TmpUsedRegs);
  7191. UpdateUsedRegsBetween(UsedRegs, p, hp1);
  7192. if PostPeepholeOptMovZX(hp1) then
  7193. hp1 := hp2
  7194. else
  7195. begin
  7196. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  7197. taicpu(hp1).opcode := A_CWDE;
  7198. taicpu(hp1).clearop(0);
  7199. taicpu(hp1).clearop(1);
  7200. taicpu(hp1).ops := 0;
  7201. end;
  7202. RestoreUsedRegs(TmpUsedRegs);
  7203. { Don't need to set aoc_ForceNewIteration if
  7204. PostPeepholeOptMovZX returned True because it's the
  7205. post-peephole stage }
  7206. end;
  7207. { Move onto the next instruction }
  7208. Continue;
  7209. end;
  7210. A_SHL, A_SAL, A_SHR:
  7211. if (taicpu(hp1).opsize <= LimitSize) and
  7212. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7213. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7214. begin
  7215. { Make sure the sizes don't exceed the register size limit
  7216. (measured by the shift value falling below the limit) }
  7217. if taicpu(hp1).opsize < LimitSize then
  7218. LimitSize := taicpu(hp1).opsize;
  7219. if taicpu(hp1).opcode = A_SHR then
  7220. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7221. else
  7222. begin
  7223. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7224. DoNotMerge := True;
  7225. end;
  7226. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7227. Exit;
  7228. { Since we've established that the combined shift is within
  7229. limits, we can actually combine the adjacent SHR
  7230. instructions even if they're different sizes }
  7231. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7232. begin
  7233. hp2 := tai(hp1.Previous);
  7234. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7235. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7236. RemoveInstruction(hp1);
  7237. hp1 := hp2;
  7238. { Though p has changed, only the constant has, and its
  7239. effects can still be detected on the next iteration of
  7240. the repeat..until loop }
  7241. Include(OptsToCheck, aoc_ForceNewIteration);
  7242. end;
  7243. { Move onto the next instruction }
  7244. Continue;
  7245. end;
  7246. else
  7247. ;
  7248. end;
  7249. { If the register isn't actually modified, move onto the next instruction,
  7250. but set DoNotMerge to True since the register is being read }
  7251. if (
  7252. { Under -O2 and below, GetNextInstructionUsingReg only returns
  7253. the next instruction, whether or not it contains the register }
  7254. (cs_opt_level3 in current_settings.optimizerswitches) or
  7255. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1)
  7256. ) and not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  7257. begin
  7258. DoNotMerge := True;
  7259. Continue;
  7260. end;
  7261. Break;
  7262. until False;
  7263. end;
  7264. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  7265. begin
  7266. Result := False;
  7267. { All these optimisations work on "shr const,%reg" }
  7268. if not MatchOpType(taicpu(p), top_const, top_reg) then
  7269. Exit;
  7270. Result := HandleSHRMerge(p, False);
  7271. end;
  7272. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7273. var
  7274. CurrentRef: TReference;
  7275. FullReg: TRegister;
  7276. hp1, hp2: tai;
  7277. begin
  7278. Result := False;
  7279. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7280. Exit;
  7281. { We assume you've checked if the operand is actually a reference by
  7282. this point. If it isn't, you'll most likely get an access violation }
  7283. CurrentRef := first_mov.oper[1]^.ref^;
  7284. { Memory must be aligned }
  7285. if (CurrentRef.offset mod 4) <> 0 then
  7286. Exit;
  7287. Inc(CurrentRef.offset);
  7288. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7289. if MatchOperand(second_mov.oper[0]^, 0) and
  7290. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7291. GetNextInstruction(second_mov, hp1) and
  7292. (hp1.typ = ait_instruction) and
  7293. (taicpu(hp1).opcode = A_MOV) and
  7294. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7295. (taicpu(hp1).oper[0]^.val = 0) then
  7296. begin
  7297. Inc(CurrentRef.offset);
  7298. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7299. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7300. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7301. begin
  7302. case taicpu(hp1).opsize of
  7303. S_B:
  7304. if GetNextInstruction(hp1, hp2) and
  7305. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7306. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7307. (taicpu(hp2).oper[0]^.val = 0) then
  7308. begin
  7309. Inc(CurrentRef.offset);
  7310. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7311. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7312. (taicpu(hp2).opsize = S_B) then
  7313. begin
  7314. RemoveInstruction(hp1);
  7315. RemoveInstruction(hp2);
  7316. first_mov.opsize := S_L;
  7317. if first_mov.oper[0]^.typ = top_reg then
  7318. begin
  7319. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7320. { Reuse second_mov as a MOVZX instruction }
  7321. second_mov.opcode := A_MOVZX;
  7322. second_mov.opsize := S_BL;
  7323. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7324. second_mov.loadreg(1, FullReg);
  7325. first_mov.oper[0]^.reg := FullReg;
  7326. asml.Remove(second_mov);
  7327. asml.InsertBefore(second_mov, first_mov);
  7328. end
  7329. else
  7330. { It's a value }
  7331. begin
  7332. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7333. RemoveInstruction(second_mov);
  7334. end;
  7335. Result := True;
  7336. Exit;
  7337. end;
  7338. end;
  7339. S_W:
  7340. begin
  7341. RemoveInstruction(hp1);
  7342. first_mov.opsize := S_L;
  7343. if first_mov.oper[0]^.typ = top_reg then
  7344. begin
  7345. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7346. { Reuse second_mov as a MOVZX instruction }
  7347. second_mov.opcode := A_MOVZX;
  7348. second_mov.opsize := S_BL;
  7349. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7350. second_mov.loadreg(1, FullReg);
  7351. first_mov.oper[0]^.reg := FullReg;
  7352. asml.Remove(second_mov);
  7353. asml.InsertBefore(second_mov, first_mov);
  7354. end
  7355. else
  7356. { It's a value }
  7357. begin
  7358. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7359. RemoveInstruction(second_mov);
  7360. end;
  7361. Result := True;
  7362. Exit;
  7363. end;
  7364. else
  7365. ;
  7366. end;
  7367. end;
  7368. end;
  7369. end;
  7370. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7371. { returns true if a "continue" should be done after this optimization }
  7372. var
  7373. hp1, hp2, hp3: tai;
  7374. begin
  7375. Result := false;
  7376. hp3 := nil;
  7377. if MatchOpType(taicpu(p),top_ref) and
  7378. GetNextInstruction(p, hp1) and
  7379. (hp1.typ = ait_instruction) and
  7380. (((taicpu(hp1).opcode = A_FLD) and
  7381. (taicpu(p).opcode = A_FSTP)) or
  7382. ((taicpu(p).opcode = A_FISTP) and
  7383. (taicpu(hp1).opcode = A_FILD))) and
  7384. MatchOpType(taicpu(hp1),top_ref) and
  7385. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7386. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7387. begin
  7388. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7389. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7390. GetNextInstruction(hp1, hp2) and
  7391. (((hp2.typ = ait_instruction) and
  7392. IsExitCode(hp2) and
  7393. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7394. not(assigned(current_procinfo.procdef.funcretsym) and
  7395. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7396. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7397. { fstp <temp>
  7398. fld <temp>
  7399. <dealloc> <temp>
  7400. }
  7401. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7402. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7403. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7404. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7405. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7406. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7407. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7408. )
  7409. )
  7410. ) then
  7411. begin
  7412. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7413. RemoveInstruction(hp1);
  7414. RemoveCurrentP(p, hp2);
  7415. { first case: exit code }
  7416. if hp2.typ = ait_instruction then
  7417. RemoveLastDeallocForFuncRes(p);
  7418. Result := true;
  7419. end
  7420. else
  7421. { we can do this only in fast math mode as fstp is rounding ...
  7422. ... still disabled as it breaks the compiler and/or rtl }
  7423. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7424. { ... or if another fstp equal to the first one follows }
  7425. GetNextInstruction(hp1,hp2) and
  7426. (hp2.typ = ait_instruction) and
  7427. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7428. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7429. begin
  7430. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7431. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7432. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7433. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7434. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7435. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7436. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7437. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7438. ) then
  7439. begin
  7440. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7441. RemoveCurrentP(p,hp2);
  7442. RemoveInstruction(hp1);
  7443. Result := true;
  7444. end
  7445. else if { fst can't store an extended/comp value }
  7446. (taicpu(p).opsize <> S_FX) and
  7447. (taicpu(p).opsize <> S_IQ) then
  7448. begin
  7449. if (taicpu(p).opcode = A_FSTP) then
  7450. taicpu(p).opcode := A_FST
  7451. else
  7452. taicpu(p).opcode := A_FIST;
  7453. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7454. RemoveInstruction(hp1);
  7455. Result := true;
  7456. end;
  7457. end;
  7458. end;
  7459. end;
  7460. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7461. var
  7462. hp1, hp2, hp3: tai;
  7463. begin
  7464. result:=false;
  7465. if MatchOpType(taicpu(p),top_reg) and
  7466. GetNextInstruction(p, hp1) and
  7467. (hp1.typ = Ait_Instruction) and
  7468. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7469. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7470. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7471. { change to
  7472. fld reg fxxx reg,st
  7473. fxxxp st, st1 (hp1)
  7474. Remark: non commutative operations must be reversed!
  7475. }
  7476. begin
  7477. case taicpu(hp1).opcode Of
  7478. A_FMULP,A_FADDP,
  7479. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7480. begin
  7481. case taicpu(hp1).opcode Of
  7482. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7483. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7484. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7485. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7486. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7487. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7488. else
  7489. internalerror(2019050534);
  7490. end;
  7491. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7492. taicpu(hp1).oper[1]^.reg := NR_ST;
  7493. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7494. RemoveCurrentP(p, hp1);
  7495. Result:=true;
  7496. exit;
  7497. end;
  7498. else
  7499. ;
  7500. end;
  7501. end
  7502. else
  7503. if MatchOpType(taicpu(p),top_ref) and
  7504. GetNextInstruction(p, hp2) and
  7505. (hp2.typ = Ait_Instruction) and
  7506. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7507. (taicpu(p).opsize in [S_FS, S_FL]) and
  7508. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7509. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7510. if GetLastInstruction(p, hp1) and
  7511. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7512. MatchOpType(taicpu(hp1),top_ref) and
  7513. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7514. if ((taicpu(hp2).opcode = A_FMULP) or
  7515. (taicpu(hp2).opcode = A_FADDP)) then
  7516. { change to
  7517. fld/fst mem1 (hp1) fld/fst mem1
  7518. fld mem1 (p) fadd/
  7519. faddp/ fmul st, st
  7520. fmulp st, st1 (hp2) }
  7521. begin
  7522. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7523. RemoveCurrentP(p, hp1);
  7524. if (taicpu(hp2).opcode = A_FADDP) then
  7525. taicpu(hp2).opcode := A_FADD
  7526. else
  7527. taicpu(hp2).opcode := A_FMUL;
  7528. taicpu(hp2).oper[1]^.reg := NR_ST;
  7529. end
  7530. else
  7531. { change to
  7532. fld/fst mem1 (hp1) fld/fst mem1
  7533. fld mem1 (p) fld st
  7534. }
  7535. begin
  7536. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7537. taicpu(p).changeopsize(S_FL);
  7538. taicpu(p).loadreg(0,NR_ST);
  7539. end
  7540. else
  7541. begin
  7542. case taicpu(hp2).opcode Of
  7543. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7544. { change to
  7545. fld/fst mem1 (hp1) fld/fst mem1
  7546. fld mem2 (p) fxxx mem2
  7547. fxxxp st, st1 (hp2) }
  7548. begin
  7549. case taicpu(hp2).opcode Of
  7550. A_FADDP: taicpu(p).opcode := A_FADD;
  7551. A_FMULP: taicpu(p).opcode := A_FMUL;
  7552. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7553. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7554. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7555. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7556. else
  7557. internalerror(2019050533);
  7558. end;
  7559. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7560. RemoveInstruction(hp2);
  7561. end
  7562. else
  7563. ;
  7564. end
  7565. end
  7566. end;
  7567. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7568. begin
  7569. Result := condition_in(cond1, cond2) or
  7570. { Not strictly subsets due to the actual flags checked, but because we're
  7571. comparing integers, E is a subset of AE and GE and their aliases }
  7572. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7573. end;
  7574. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7575. var
  7576. v: TCGInt;
  7577. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7578. FirstMatch, TempBool: Boolean;
  7579. NewReg: TRegister;
  7580. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7581. begin
  7582. Result:=false;
  7583. { All these optimisations need a next instruction }
  7584. if not GetNextInstruction(p, hp1) then
  7585. Exit;
  7586. true_hp1 := hp1;
  7587. { Search for:
  7588. cmp ###,###
  7589. j(c1) @lbl1
  7590. ...
  7591. @lbl:
  7592. cmp ###,### (same comparison as above)
  7593. j(c2) @lbl2
  7594. If c1 is a subset of c2, change to:
  7595. cmp ###,###
  7596. j(c1) @lbl2
  7597. (@lbl1 may become a dead label as a result)
  7598. }
  7599. { Also handle cases where there are multiple jumps in a row }
  7600. p_jump := hp1;
  7601. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7602. begin
  7603. Prefetch(p_jump.Next);
  7604. if IsJumpToLabel(taicpu(p_jump)) then
  7605. begin
  7606. { Do jump optimisations first in case the condition becomes
  7607. unnecessary }
  7608. TempBool := True;
  7609. if DoJumpOptimizations(p_jump, TempBool) or
  7610. not TempBool then
  7611. begin
  7612. if Assigned(p_jump) then
  7613. begin
  7614. { CollapseZeroDistJump will be set to the label or an align
  7615. before it after the jump if it optimises, whether or not
  7616. the label is live or dead }
  7617. if (p_jump.typ = ait_align) or
  7618. (
  7619. (p_jump.typ = ait_label) and
  7620. not (tai_label(p_jump).labsym.is_used)
  7621. ) then
  7622. GetNextInstruction(p_jump, p_jump);
  7623. end;
  7624. TransferUsedRegs(TmpUsedRegs);
  7625. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7626. if not Assigned(p_jump) or
  7627. (
  7628. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7629. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7630. ) then
  7631. begin
  7632. { No more conditional jumps; conditional statement is no longer required }
  7633. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7634. RemoveCurrentP(p);
  7635. Result := True;
  7636. Exit;
  7637. end;
  7638. hp1 := p_jump;
  7639. Include(OptsToCheck, aoc_ForceNewIteration);
  7640. Continue;
  7641. end;
  7642. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7643. if GetNextInstruction(p_jump, hp2) and
  7644. (
  7645. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7646. not TempBool
  7647. ) then
  7648. begin
  7649. hp1 := p_jump;
  7650. Include(OptsToCheck, aoc_ForceNewIteration);
  7651. Continue;
  7652. end;
  7653. p_label := nil;
  7654. if Assigned(JumpLabel) then
  7655. p_label := getlabelwithsym(JumpLabel);
  7656. if Assigned(p_label) and
  7657. GetNextInstruction(p_label, p_dist) and
  7658. MatchInstruction(p_dist, A_CMP, []) and
  7659. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7660. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7661. GetNextInstruction(p_dist, hp1_dist) and
  7662. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7663. begin
  7664. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7665. if JumpLabel = JumpLabel_dist then
  7666. { This is an infinite loop }
  7667. Exit;
  7668. { Best optimisation when the first condition is a subset (or equal) of the second }
  7669. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7670. begin
  7671. { Any registers used here will already be allocated }
  7672. if Assigned(JumpLabel) then
  7673. JumpLabel.DecRefs;
  7674. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7675. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7676. Include(OptsToCheck, aoc_ForceNewIteration);
  7677. { Don't exit yet. Since p and p_jump haven't actually been
  7678. removed, we can check for more on this iteration }
  7679. end
  7680. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7681. GetNextInstruction(hp1_dist, hp1_label) and
  7682. (hp1_label.typ = ait_label) then
  7683. begin
  7684. JumpLabel_far := tai_label(hp1_label).labsym;
  7685. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7686. { This is an infinite loop }
  7687. Exit;
  7688. if Assigned(JumpLabel_far) then
  7689. begin
  7690. { In this situation, if the first jump branches, the second one will never,
  7691. branch so change the destination label to after the second jump }
  7692. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7693. if Assigned(JumpLabel) then
  7694. JumpLabel.DecRefs;
  7695. JumpLabel_far.IncRefs;
  7696. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7697. Result := True;
  7698. { Don't exit yet. Since p and p_jump haven't actually been
  7699. removed, we can check for more on this iteration }
  7700. Continue;
  7701. end;
  7702. end;
  7703. end;
  7704. end;
  7705. { Search for:
  7706. cmp ###,###
  7707. j(c1) @lbl1
  7708. cmp ###,### (same as first)
  7709. Remove second cmp
  7710. }
  7711. if GetNextInstruction(p_jump, hp2) and
  7712. (
  7713. (
  7714. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7715. (
  7716. (
  7717. MatchOpType(taicpu(p), top_const, top_reg) and
  7718. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7719. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7720. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7721. ) or (
  7722. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7723. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7724. )
  7725. )
  7726. ) or (
  7727. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7728. MatchOperand(taicpu(p).oper[0]^, 0) and
  7729. (taicpu(p).oper[1]^.typ = top_reg) and
  7730. MatchInstruction(hp2, A_TEST, []) and
  7731. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7732. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7733. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7734. )
  7735. ) then
  7736. begin
  7737. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7738. TransferUsedRegs(TmpUsedRegs);
  7739. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7740. RemoveInstruction(hp2);
  7741. Result := True;
  7742. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7743. end
  7744. else
  7745. begin
  7746. { hp2 is the next instruction, so save time and just set p_jump
  7747. to it instead of calling GetNextInstruction below }
  7748. p_jump := hp2;
  7749. Continue;
  7750. end;
  7751. GetNextInstruction(p_jump, p_jump);
  7752. end;
  7753. if (
  7754. { Don't call GetNextInstruction again if we already have it }
  7755. (true_hp1 = p_jump) or
  7756. GetNextInstruction(p, hp1)
  7757. ) and
  7758. MatchInstruction(hp1, A_Jcc, []) and
  7759. IsJumpToLabel(taicpu(hp1)) and
  7760. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7761. GetNextInstruction(hp1, hp2) then
  7762. begin
  7763. {
  7764. cmp x, y (or "cmp y, x")
  7765. je @lbl
  7766. mov x, y
  7767. @lbl:
  7768. (x and y can be constants, registers or references)
  7769. Change to:
  7770. mov x, y (x and y will always be equal in the end)
  7771. @lbl: (may beceome a dead label)
  7772. Also:
  7773. cmp x, y (or "cmp y, x")
  7774. jne @lbl
  7775. mov x, y
  7776. @lbl:
  7777. (x and y can be constants, registers or references)
  7778. Change to:
  7779. Absolutely nothing! (Except @lbl if it's still live)
  7780. }
  7781. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7782. (
  7783. (
  7784. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7785. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7786. ) or (
  7787. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7788. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7789. )
  7790. ) and
  7791. GetNextInstruction(hp2, hp1_label) and
  7792. (hp1_label.typ = ait_label) and
  7793. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7794. begin
  7795. tai_label(hp1_label).labsym.DecRefs;
  7796. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7797. begin
  7798. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7799. RemoveInstruction(hp2);
  7800. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7801. end
  7802. else
  7803. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7804. RemoveInstruction(hp1);
  7805. RemoveCurrentp(p, hp2);
  7806. Result := True;
  7807. Exit;
  7808. end;
  7809. {
  7810. Try to optimise the following:
  7811. cmp $x,### ($x and $y can be registers or constants)
  7812. je @lbl1 (only reference)
  7813. cmp $y,### (### are identical)
  7814. @Lbl:
  7815. sete %reg1
  7816. Change to:
  7817. cmp $x,###
  7818. sete %reg2 (allocate new %reg2)
  7819. cmp $y,###
  7820. sete %reg1
  7821. orb %reg2,%reg1
  7822. (dealloc %reg2)
  7823. This adds an instruction (so don't perform under -Os), but it removes
  7824. a conditional branch.
  7825. }
  7826. if not (cs_opt_size in current_settings.optimizerswitches) and
  7827. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7828. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7829. { The first operand of CMP instructions can only be a register or
  7830. immediate anyway, so no need to check }
  7831. GetNextInstruction(hp2, p_label) and
  7832. (p_label.typ = ait_label) and
  7833. (tai_label(p_label).labsym.getrefs = 1) and
  7834. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7835. GetNextInstruction(p_label, p_dist) and
  7836. MatchInstruction(p_dist, A_SETcc, []) and
  7837. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7838. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7839. begin
  7840. TransferUsedRegs(TmpUsedRegs);
  7841. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7842. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7843. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7844. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7845. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7846. { Get the instruction after the SETcc instruction so we can
  7847. allocate a new register over the entire range }
  7848. GetNextInstruction(p_dist, hp1_dist) then
  7849. begin
  7850. { Register can appear in p if it's not used afterwards, so only
  7851. allocate between hp1 and hp1_dist }
  7852. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7853. if NewReg <> NR_NO then
  7854. begin
  7855. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7856. { Change the jump instruction into a SETcc instruction }
  7857. taicpu(hp1).opcode := A_SETcc;
  7858. taicpu(hp1).opsize := S_B;
  7859. taicpu(hp1).loadreg(0, NewReg);
  7860. { This is now a dead label }
  7861. tai_label(p_label).labsym.decrefs;
  7862. { Prefer adding before the next instruction so the FLAGS
  7863. register is deallicated first }
  7864. AsmL.InsertBefore(
  7865. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7866. hp1_dist
  7867. );
  7868. Result := True;
  7869. { Don't exit yet, as p wasn't changed and hp1, while
  7870. modified, is still intact and might be optimised by the
  7871. SETcc optimisation below }
  7872. end;
  7873. end;
  7874. end;
  7875. end;
  7876. if (taicpu(p).oper[0]^.typ = top_const) and
  7877. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7878. begin
  7879. if (taicpu(p).oper[0]^.val = 0) and
  7880. (taicpu(p).oper[1]^.typ = top_reg) then
  7881. begin
  7882. hp2 := p;
  7883. FirstMatch := True;
  7884. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7885. anything meaningful once it's converted to "test %reg,%reg";
  7886. additionally, some jumps will always (or never) branch, so
  7887. evaluate every jump immediately following the
  7888. comparison, optimising the conditions if possible.
  7889. Similarly with SETcc... those that are always set to 0 or 1
  7890. are changed to MOV instructions }
  7891. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7892. (
  7893. GetNextInstruction(hp2, hp1) and
  7894. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7895. ) do
  7896. begin
  7897. Prefetch(hp1.Next);
  7898. FirstMatch := False;
  7899. case taicpu(hp1).condition of
  7900. C_B, C_C, C_NAE, C_O:
  7901. { For B/NAE:
  7902. Will never branch since an unsigned integer can never be below zero
  7903. For C/O:
  7904. Result cannot overflow because 0 is being subtracted
  7905. }
  7906. begin
  7907. if taicpu(hp1).opcode = A_Jcc then
  7908. begin
  7909. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7910. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7911. RemoveInstruction(hp1);
  7912. { Since hp1 was deleted, hp2 must not be updated }
  7913. Continue;
  7914. end
  7915. else
  7916. begin
  7917. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7918. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7919. taicpu(hp1).opcode := A_MOV;
  7920. taicpu(hp1).ops := 2;
  7921. taicpu(hp1).condition := C_None;
  7922. taicpu(hp1).opsize := S_B;
  7923. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7924. taicpu(hp1).loadconst(0, 0);
  7925. end;
  7926. end;
  7927. C_BE, C_NA:
  7928. begin
  7929. { Will only branch if equal to zero }
  7930. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7931. taicpu(hp1).condition := C_E;
  7932. end;
  7933. C_A, C_NBE:
  7934. begin
  7935. { Will only branch if not equal to zero }
  7936. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7937. taicpu(hp1).condition := C_NE;
  7938. end;
  7939. C_AE, C_NB, C_NC, C_NO:
  7940. begin
  7941. { Will always branch }
  7942. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7943. if taicpu(hp1).opcode = A_Jcc then
  7944. begin
  7945. MakeUnconditional(taicpu(hp1));
  7946. { Any jumps/set that follow will now be dead code }
  7947. RemoveDeadCodeAfterJump(taicpu(hp1));
  7948. Break;
  7949. end
  7950. else
  7951. begin
  7952. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7953. taicpu(hp1).opcode := A_MOV;
  7954. taicpu(hp1).ops := 2;
  7955. taicpu(hp1).condition := C_None;
  7956. taicpu(hp1).opsize := S_B;
  7957. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7958. taicpu(hp1).loadconst(0, 1);
  7959. end;
  7960. end;
  7961. C_None:
  7962. InternalError(2020012201);
  7963. C_P, C_PE, C_NP, C_PO:
  7964. { We can't handle parity checks and they should never be generated
  7965. after a general-purpose CMP (it's used in some floating-point
  7966. comparisons that don't use CMP) }
  7967. InternalError(2020012202);
  7968. else
  7969. { Zero/Equality, Sign, their complements and all of the
  7970. signed comparisons do not need to be converted };
  7971. end;
  7972. hp2 := hp1;
  7973. end;
  7974. { Convert the instruction to a TEST }
  7975. taicpu(p).opcode := A_TEST;
  7976. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7977. Result := True;
  7978. Exit;
  7979. end
  7980. else
  7981. begin
  7982. TransferUsedRegs(TmpUsedRegs);
  7983. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7984. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7985. begin
  7986. if (taicpu(p).oper[0]^.val = 1) and
  7987. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7988. begin
  7989. { Convert; To:
  7990. cmp $1,r/m cmp $0,r/m
  7991. jl @lbl jle @lbl
  7992. (Also do inverted conditions)
  7993. }
  7994. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7995. taicpu(p).oper[0]^.val := 0;
  7996. if taicpu(hp1).condition in [C_L, C_NGE] then
  7997. taicpu(hp1).condition := C_LE
  7998. else
  7999. taicpu(hp1).condition := C_NLE;
  8000. { If the instruction is now "cmp $0,%reg", convert it to a
  8001. TEST (and effectively do the work of the "cmp $0,%reg" in
  8002. the block above)
  8003. }
  8004. if (taicpu(p).oper[1]^.typ = top_reg) then
  8005. begin
  8006. taicpu(p).opcode := A_TEST;
  8007. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8008. end;
  8009. Result := True;
  8010. Exit;
  8011. end
  8012. else if (taicpu(p).oper[1]^.typ = top_reg)
  8013. {$ifdef x86_64}
  8014. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  8015. {$endif x86_64}
  8016. then
  8017. begin
  8018. { cmp register,$8000 neg register
  8019. je target --> jo target
  8020. .... only if register is deallocated before jump.}
  8021. case Taicpu(p).opsize of
  8022. S_B: v:=$80;
  8023. S_W: v:=$8000;
  8024. S_L: v:=qword($80000000);
  8025. else
  8026. internalerror(2013112905);
  8027. end;
  8028. if (taicpu(p).oper[0]^.val=v) and
  8029. (Taicpu(hp1).condition in [C_E,C_NE]) then
  8030. begin
  8031. TransferUsedRegs(TmpUsedRegs);
  8032. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  8033. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  8034. begin
  8035. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  8036. Taicpu(p).opcode:=A_NEG;
  8037. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  8038. Taicpu(p).clearop(1);
  8039. Taicpu(p).ops:=1;
  8040. if Taicpu(hp1).condition=C_E then
  8041. Taicpu(hp1).condition:=C_O
  8042. else
  8043. Taicpu(hp1).condition:=C_NO;
  8044. Result:=true;
  8045. exit;
  8046. end;
  8047. end;
  8048. end;
  8049. end;
  8050. end;
  8051. end;
  8052. if TrySwapMovCmp(p, hp1) then
  8053. begin
  8054. Result := True;
  8055. Exit;
  8056. end;
  8057. end;
  8058. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  8059. var
  8060. hp1: tai;
  8061. begin
  8062. {
  8063. remove the second (v)pxor from
  8064. pxor reg,reg
  8065. ...
  8066. pxor reg,reg
  8067. }
  8068. Result:=false;
  8069. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8070. MatchOpType(taicpu(p),top_reg,top_reg) and
  8071. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8072. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8073. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8074. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  8075. begin
  8076. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  8077. RemoveInstruction(hp1);
  8078. Result:=true;
  8079. Exit;
  8080. end
  8081. {
  8082. replace
  8083. pxor reg1,reg1
  8084. movapd/s reg1,reg2
  8085. dealloc reg1
  8086. by
  8087. pxor reg2,reg2
  8088. }
  8089. else if GetNextInstruction(p,hp1) and
  8090. { we mix single and double opperations here because we assume that the compiler
  8091. generates vmovapd only after double operations and vmovaps only after single operations }
  8092. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  8093. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8094. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  8095. (taicpu(p).oper[0]^.typ=top_reg) then
  8096. begin
  8097. TransferUsedRegs(TmpUsedRegs);
  8098. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8099. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8100. begin
  8101. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  8102. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  8103. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  8104. RemoveInstruction(hp1);
  8105. result:=true;
  8106. end;
  8107. end;
  8108. end;
  8109. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  8110. var
  8111. hp1: tai;
  8112. begin
  8113. {
  8114. remove the second (v)pxor from
  8115. (v)pxor reg,reg
  8116. ...
  8117. (v)pxor reg,reg
  8118. }
  8119. Result:=false;
  8120. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  8121. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8122. begin
  8123. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8124. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8125. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8126. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  8127. begin
  8128. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  8129. RemoveInstruction(hp1);
  8130. Result:=true;
  8131. Exit;
  8132. end;
  8133. {$ifdef x86_64}
  8134. {
  8135. replace
  8136. vpxor reg1,reg1,reg1
  8137. vmov reg,mem
  8138. by
  8139. movq $0,mem
  8140. }
  8141. if GetNextInstruction(p,hp1) and
  8142. MatchInstruction(hp1,A_VMOVSD,[]) and
  8143. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8144. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  8145. begin
  8146. TransferUsedRegs(TmpUsedRegs);
  8147. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8148. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8149. begin
  8150. taicpu(hp1).loadconst(0,0);
  8151. taicpu(hp1).opcode:=A_MOV;
  8152. taicpu(hp1).opsize:=S_Q;
  8153. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  8154. RemoveCurrentP(p);
  8155. result:=true;
  8156. Exit;
  8157. end;
  8158. end;
  8159. {$endif x86_64}
  8160. end
  8161. {
  8162. replace
  8163. vpxor reg1,reg1,reg2
  8164. by
  8165. vpxor reg2,reg2,reg2
  8166. to avoid unncessary data dependencies
  8167. }
  8168. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8169. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8170. begin
  8171. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  8172. { avoid unncessary data dependency }
  8173. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  8174. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  8175. result:=true;
  8176. exit;
  8177. end;
  8178. Result:=OptPass1VOP(p);
  8179. end;
  8180. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  8181. var
  8182. hp1 : tai;
  8183. begin
  8184. result:=false;
  8185. { replace
  8186. IMul const,%mreg1,%mreg2
  8187. Mov %reg2,%mreg3
  8188. dealloc %mreg3
  8189. by
  8190. Imul const,%mreg1,%mreg23
  8191. }
  8192. if (taicpu(p).ops=3) and
  8193. GetNextInstruction(p,hp1) and
  8194. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8195. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8196. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8197. begin
  8198. TransferUsedRegs(TmpUsedRegs);
  8199. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8200. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8201. begin
  8202. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8203. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  8204. RemoveInstruction(hp1);
  8205. result:=true;
  8206. end;
  8207. end;
  8208. end;
  8209. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  8210. var
  8211. hp1 : tai;
  8212. begin
  8213. result:=false;
  8214. { replace
  8215. IMul %reg0,%reg1,%reg2
  8216. Mov %reg2,%reg3
  8217. dealloc %reg2
  8218. by
  8219. Imul %reg0,%reg1,%reg3
  8220. }
  8221. if GetNextInstruction(p,hp1) and
  8222. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8223. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8224. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8225. begin
  8226. TransferUsedRegs(TmpUsedRegs);
  8227. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8228. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8229. begin
  8230. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8231. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8232. RemoveInstruction(hp1);
  8233. result:=true;
  8234. end;
  8235. end;
  8236. end;
  8237. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8238. var
  8239. hp1: tai;
  8240. begin
  8241. Result:=false;
  8242. { get rid of
  8243. (v)cvtss2sd reg0,<reg1,>reg2
  8244. (v)cvtss2sd reg2,<reg2,>reg0
  8245. }
  8246. if GetNextInstruction(p,hp1) and
  8247. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8248. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8249. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8250. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8251. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8252. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8253. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8254. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8255. )
  8256. ) then
  8257. begin
  8258. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8259. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8260. begin
  8261. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8262. RemoveCurrentP(p);
  8263. RemoveInstruction(hp1);
  8264. end
  8265. else
  8266. begin
  8267. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8268. if taicpu(hp1).opcode=A_CVTSD2SS then
  8269. begin
  8270. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8271. taicpu(p).opcode:=A_MOVAPS;
  8272. end
  8273. else
  8274. begin
  8275. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8276. taicpu(p).opcode:=A_VMOVAPS;
  8277. end;
  8278. taicpu(p).ops:=2;
  8279. RemoveInstruction(hp1);
  8280. end;
  8281. Result:=true;
  8282. Exit;
  8283. end;
  8284. end;
  8285. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8286. var
  8287. hp1, hp2, hp3, hp4, hp5: tai;
  8288. ThisReg: TRegister;
  8289. begin
  8290. Result := False;
  8291. if not GetNextInstruction(p,hp1) then
  8292. Exit;
  8293. {
  8294. convert
  8295. j<c> .L1
  8296. mov 1,reg
  8297. jmp .L2
  8298. .L1
  8299. mov 0,reg
  8300. .L2
  8301. into
  8302. mov 0,reg
  8303. set<not(c)> reg
  8304. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8305. would destroy the flag contents
  8306. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8307. executed at the same time as a previous comparison.
  8308. set<not(c)> reg
  8309. movzx reg, reg
  8310. }
  8311. if MatchInstruction(hp1,A_MOV,[]) and
  8312. (taicpu(hp1).oper[0]^.typ = top_const) and
  8313. (
  8314. (
  8315. (taicpu(hp1).oper[1]^.typ = top_reg)
  8316. {$ifdef i386}
  8317. { Under i386, ESI, EDI, EBP and ESP
  8318. don't have an 8-bit representation }
  8319. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8320. {$endif i386}
  8321. ) or (
  8322. {$ifdef i386}
  8323. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8324. {$endif i386}
  8325. (taicpu(hp1).opsize = S_B)
  8326. )
  8327. ) and
  8328. GetNextInstruction(hp1,hp2) and
  8329. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8330. GetNextInstruction(hp2,hp3) and
  8331. FindLabel(tasmlabel(taicpu(p).oper[0]^.ref^.symbol), hp3) and
  8332. GetNextInstruction(hp3,hp4) and
  8333. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8334. (taicpu(hp4).oper[0]^.typ = top_const) and
  8335. (
  8336. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8337. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8338. ) and
  8339. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8340. GetNextInstruction(hp4,hp5) and
  8341. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol), hp5) then
  8342. begin
  8343. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8344. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8345. tai_label(hp3).labsym.DecRefs;
  8346. { If this isn't the only reference to the middle label, we can
  8347. still make a saving - only that the first jump and everything
  8348. that follows will remain. }
  8349. if (tai_label(hp3).labsym.getrefs = 0) then
  8350. begin
  8351. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8352. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8353. else
  8354. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8355. { remove jump, first label and second MOV (also catching any aligns) }
  8356. repeat
  8357. if not GetNextInstruction(hp2, hp3) then
  8358. InternalError(2021040810);
  8359. RemoveInstruction(hp2);
  8360. hp2 := hp3;
  8361. until hp2 = hp5;
  8362. { Don't decrement reference count before the removal loop
  8363. above, otherwise GetNextInstruction won't stop on the
  8364. the label }
  8365. tai_label(hp5).labsym.DecRefs;
  8366. end
  8367. else
  8368. begin
  8369. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8370. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8371. else
  8372. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8373. end;
  8374. taicpu(p).opcode:=A_SETcc;
  8375. taicpu(p).opsize:=S_B;
  8376. taicpu(p).is_jmp:=False;
  8377. if taicpu(hp1).opsize=S_B then
  8378. begin
  8379. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8380. if taicpu(hp1).oper[1]^.typ = top_reg then
  8381. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8382. RemoveInstruction(hp1);
  8383. end
  8384. else
  8385. begin
  8386. { Will be a register because the size can't be S_B otherwise }
  8387. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8388. taicpu(p).loadreg(0, ThisReg);
  8389. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8390. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8391. begin
  8392. case taicpu(hp1).opsize of
  8393. S_W:
  8394. taicpu(hp1).opsize := S_BW;
  8395. S_L:
  8396. taicpu(hp1).opsize := S_BL;
  8397. {$ifdef x86_64}
  8398. S_Q:
  8399. begin
  8400. taicpu(hp1).opsize := S_BL;
  8401. { Change the destination register to 32-bit }
  8402. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8403. end;
  8404. {$endif x86_64}
  8405. else
  8406. InternalError(2021040820);
  8407. end;
  8408. taicpu(hp1).opcode := A_MOVZX;
  8409. taicpu(hp1).loadreg(0, ThisReg);
  8410. end
  8411. else
  8412. begin
  8413. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8414. { hp1 is already a MOV instruction with the correct register }
  8415. taicpu(hp1).loadconst(0, 0);
  8416. { Inserting it right before p will guarantee that the flags are also tracked }
  8417. asml.Remove(hp1);
  8418. asml.InsertBefore(hp1, p);
  8419. end;
  8420. end;
  8421. Result:=true;
  8422. exit;
  8423. end
  8424. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8425. Result := TryJccStcClcOpt(p, hp1)
  8426. else if (hp1.typ = ait_label) then
  8427. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8428. end;
  8429. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8430. var
  8431. hp1, hp2, hp3: tai;
  8432. SourceRef, TargetRef: TReference;
  8433. CurrentReg: TRegister;
  8434. begin
  8435. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8436. if not UseAVX then
  8437. InternalError(2021100501);
  8438. Result := False;
  8439. { Look for the following to simplify:
  8440. vmovdqa/u x(mem1), %xmmreg
  8441. vmovdqa/u %xmmreg, y(mem2)
  8442. vmovdqa/u x+16(mem1), %xmmreg
  8443. vmovdqa/u %xmmreg, y+16(mem2)
  8444. Change to:
  8445. vmovdqa/u x(mem1), %ymmreg
  8446. vmovdqa/u %ymmreg, y(mem2)
  8447. vpxor %ymmreg, %ymmreg, %ymmreg
  8448. ( The VPXOR instruction is to zero the upper half, thus removing the
  8449. need to call the potentially expensive VZEROUPPER instruction. Other
  8450. peephole optimisations can remove VPXOR if it's unnecessary )
  8451. }
  8452. TransferUsedRegs(TmpUsedRegs);
  8453. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8454. { NOTE: In the optimisations below, if the references dictate that an
  8455. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8456. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8457. if (taicpu(p).opsize = S_XMM) and
  8458. MatchOpType(taicpu(p), top_ref, top_reg) and
  8459. GetNextInstruction(p, hp1) and
  8460. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8461. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8462. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8463. begin
  8464. SourceRef := taicpu(p).oper[0]^.ref^;
  8465. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8466. if GetNextInstruction(hp1, hp2) and
  8467. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8468. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8469. begin
  8470. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8471. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8472. Inc(SourceRef.offset, 16);
  8473. { Reuse the register in the first block move }
  8474. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8475. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8476. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8477. begin
  8478. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8479. Inc(TargetRef.offset, 16);
  8480. if GetNextInstruction(hp2, hp3) and
  8481. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8482. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8483. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8484. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8485. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8486. begin
  8487. { Update the register tracking to the new size }
  8488. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8489. { Remember that the offsets are 16 ahead }
  8490. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8491. if not (
  8492. ((SourceRef.offset mod 32) = 16) and
  8493. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8494. ) then
  8495. taicpu(p).opcode := A_VMOVDQU;
  8496. taicpu(p).opsize := S_YMM;
  8497. taicpu(p).oper[1]^.reg := CurrentReg;
  8498. if not (
  8499. ((TargetRef.offset mod 32) = 16) and
  8500. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8501. ) then
  8502. taicpu(hp1).opcode := A_VMOVDQU;
  8503. taicpu(hp1).opsize := S_YMM;
  8504. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8505. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8506. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8507. if (pi_uses_ymm in current_procinfo.flags) then
  8508. RemoveInstruction(hp2)
  8509. else
  8510. begin
  8511. taicpu(hp2).opcode := A_VPXOR;
  8512. taicpu(hp2).opsize := S_YMM;
  8513. taicpu(hp2).loadreg(0, CurrentReg);
  8514. taicpu(hp2).loadreg(1, CurrentReg);
  8515. taicpu(hp2).loadreg(2, CurrentReg);
  8516. taicpu(hp2).ops := 3;
  8517. end;
  8518. RemoveInstruction(hp3);
  8519. Result := True;
  8520. Exit;
  8521. end;
  8522. end
  8523. else
  8524. begin
  8525. { See if the next references are 16 less rather than 16 greater }
  8526. Dec(SourceRef.offset, 32); { -16 the other way }
  8527. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8528. begin
  8529. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8530. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8531. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8532. GetNextInstruction(hp2, hp3) and
  8533. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8534. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8535. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8536. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8537. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8538. begin
  8539. { Update the register tracking to the new size }
  8540. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8541. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8542. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8543. if not(
  8544. ((SourceRef.offset mod 32) = 0) and
  8545. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8546. ) then
  8547. taicpu(hp2).opcode := A_VMOVDQU;
  8548. taicpu(hp2).opsize := S_YMM;
  8549. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8550. if not (
  8551. ((TargetRef.offset mod 32) = 0) and
  8552. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8553. ) then
  8554. taicpu(hp3).opcode := A_VMOVDQU;
  8555. taicpu(hp3).opsize := S_YMM;
  8556. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8557. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8558. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8559. if (pi_uses_ymm in current_procinfo.flags) then
  8560. RemoveInstruction(hp1)
  8561. else
  8562. begin
  8563. taicpu(hp1).opcode := A_VPXOR;
  8564. taicpu(hp1).opsize := S_YMM;
  8565. taicpu(hp1).loadreg(0, CurrentReg);
  8566. taicpu(hp1).loadreg(1, CurrentReg);
  8567. taicpu(hp1).loadreg(2, CurrentReg);
  8568. taicpu(hp1).ops := 3;
  8569. Asml.Remove(hp1);
  8570. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8571. end;
  8572. RemoveCurrentP(p, hp2);
  8573. Result := True;
  8574. Exit;
  8575. end;
  8576. end;
  8577. end;
  8578. end;
  8579. end;
  8580. end;
  8581. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8582. var
  8583. hp2, hp3, first_assignment: tai;
  8584. IncCount, OperIdx: Integer;
  8585. OrigLabel: TAsmLabel;
  8586. begin
  8587. Count := 0;
  8588. Result := False;
  8589. first_assignment := nil;
  8590. if (LoopCount >= 20) then
  8591. begin
  8592. { Guard against infinite loops }
  8593. Exit;
  8594. end;
  8595. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8596. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8597. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8598. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8599. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8600. Exit;
  8601. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8602. {
  8603. change
  8604. jmp .L1
  8605. ...
  8606. .L1:
  8607. mov ##, ## ( multiple movs possible )
  8608. jmp/ret
  8609. into
  8610. mov ##, ##
  8611. jmp/ret
  8612. }
  8613. if not Assigned(hp1) then
  8614. begin
  8615. hp1 := GetLabelWithSym(OrigLabel);
  8616. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8617. Exit;
  8618. end;
  8619. hp2 := hp1;
  8620. while Assigned(hp2) do
  8621. begin
  8622. if Assigned(hp2) and (hp2.typ = ait_label) then
  8623. SkipLabels(hp2,hp2);
  8624. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8625. Break;
  8626. case taicpu(hp2).opcode of
  8627. A_MOVSD:
  8628. begin
  8629. if taicpu(hp2).ops = 0 then
  8630. { Wrong MOVSD }
  8631. Break;
  8632. Inc(Count);
  8633. if Count >= 5 then
  8634. { Too many to be worthwhile }
  8635. Break;
  8636. GetNextInstruction(hp2, hp2);
  8637. Continue;
  8638. end;
  8639. A_MOV,
  8640. A_MOVD,
  8641. A_MOVQ,
  8642. A_MOVSX,
  8643. {$ifdef x86_64}
  8644. A_MOVSXD,
  8645. {$endif x86_64}
  8646. A_MOVZX,
  8647. A_MOVAPS,
  8648. A_MOVUPS,
  8649. A_MOVSS,
  8650. A_MOVAPD,
  8651. A_MOVUPD,
  8652. A_MOVDQA,
  8653. A_MOVDQU,
  8654. A_VMOVSS,
  8655. A_VMOVAPS,
  8656. A_VMOVUPS,
  8657. A_VMOVSD,
  8658. A_VMOVAPD,
  8659. A_VMOVUPD,
  8660. A_VMOVDQA,
  8661. A_VMOVDQU:
  8662. begin
  8663. Inc(Count);
  8664. if Count >= 5 then
  8665. { Too many to be worthwhile }
  8666. Break;
  8667. GetNextInstruction(hp2, hp2);
  8668. Continue;
  8669. end;
  8670. A_JMP:
  8671. begin
  8672. { Guard against infinite loops }
  8673. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8674. Exit;
  8675. { Analyse this jump first in case it also duplicates assignments }
  8676. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8677. begin
  8678. { Something did change! }
  8679. Result := True;
  8680. Inc(Count, IncCount);
  8681. if Count >= 5 then
  8682. begin
  8683. { Too many to be worthwhile }
  8684. Exit;
  8685. end;
  8686. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8687. Break;
  8688. end;
  8689. Result := True;
  8690. Break;
  8691. end;
  8692. A_RET:
  8693. begin
  8694. Result := True;
  8695. Break;
  8696. end;
  8697. else
  8698. Break;
  8699. end;
  8700. end;
  8701. if Result then
  8702. begin
  8703. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8704. if Count = 0 then
  8705. begin
  8706. Result := False;
  8707. Exit;
  8708. end;
  8709. TransferUsedRegs(TmpUsedRegs);
  8710. hp3 := p;
  8711. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8712. while True do
  8713. begin
  8714. if Assigned(hp1) and (hp1.typ = ait_label) then
  8715. SkipLabels(hp1,hp1);
  8716. case hp1.typ of
  8717. ait_regalloc:
  8718. if tai_regalloc(hp1).ratype = ra_dealloc then
  8719. begin
  8720. { Duplicate the register deallocation... }
  8721. hp3:=tai(hp1.getcopy);
  8722. if first_assignment = nil then
  8723. first_assignment := hp3;
  8724. asml.InsertBefore(hp3, p);
  8725. { ... but also reallocate it after the jump }
  8726. hp3:=tai(hp1.getcopy);
  8727. tai_regalloc(hp3).ratype := ra_alloc;
  8728. asml.InsertAfter(hp3, p);
  8729. end;
  8730. ait_instruction:
  8731. case taicpu(hp1).opcode of
  8732. A_JMP:
  8733. begin
  8734. { Change the original jump to the new destination }
  8735. OrigLabel.decrefs;
  8736. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8737. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8738. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8739. if not Assigned(first_assignment) then
  8740. InternalError(2021040810)
  8741. else
  8742. p := first_assignment;
  8743. Exit;
  8744. end;
  8745. A_RET:
  8746. begin
  8747. { Now change the jump into a RET instruction }
  8748. ConvertJumpToRET(p, hp1);
  8749. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8750. if not Assigned(first_assignment) then
  8751. InternalError(2021040811)
  8752. else
  8753. p := first_assignment;
  8754. Exit;
  8755. end;
  8756. else
  8757. begin
  8758. { Duplicate the MOV instruction }
  8759. hp3:=tai(hp1.getcopy);
  8760. if first_assignment = nil then
  8761. first_assignment := hp3;
  8762. asml.InsertBefore(hp3, p);
  8763. { Make sure the compiler knows about any final registers written here }
  8764. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8765. with taicpu(hp3).oper[OperIdx]^ do
  8766. begin
  8767. case typ of
  8768. top_ref:
  8769. begin
  8770. if (ref^.base <> NR_NO) and
  8771. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8772. (
  8773. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8774. (
  8775. { Allow the frame pointer if it's not being used by the procedure as such }
  8776. Assigned(current_procinfo) and
  8777. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8778. )
  8779. )
  8780. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8781. then
  8782. begin
  8783. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8784. if not Assigned(first_assignment) then
  8785. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8786. end;
  8787. if (ref^.index <> NR_NO) and
  8788. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8789. (
  8790. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8791. (
  8792. { Allow the frame pointer if it's not being used by the procedure as such }
  8793. Assigned(current_procinfo) and
  8794. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8795. )
  8796. )
  8797. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8798. (ref^.index <> ref^.base) then
  8799. begin
  8800. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8801. if not Assigned(first_assignment) then
  8802. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8803. end;
  8804. end;
  8805. top_reg:
  8806. begin
  8807. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8808. if not Assigned(first_assignment) then
  8809. IncludeRegInUsedRegs(reg, UsedRegs);
  8810. end;
  8811. else
  8812. ;
  8813. end;
  8814. end;
  8815. end;
  8816. end;
  8817. else
  8818. InternalError(2021040720);
  8819. end;
  8820. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8821. { Should have dropped out earlier }
  8822. InternalError(2021040710);
  8823. end;
  8824. end;
  8825. end;
  8826. const
  8827. WriteOp: array[0..3] of set of TInsChange = (
  8828. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8829. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8830. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8831. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8832. RegWriteFlags: array[0..7] of set of TInsChange = (
  8833. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8834. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8835. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8836. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8837. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8838. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8839. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8840. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8841. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8842. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8843. var
  8844. hp2: tai;
  8845. X: Integer;
  8846. begin
  8847. { If we have something like:
  8848. op ###,###
  8849. mov ###,###
  8850. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8851. interfere in regards to what they write to.
  8852. NOTE: p must be a 2-operand instruction
  8853. }
  8854. Result := False;
  8855. if (hp1.typ <> ait_instruction) or
  8856. taicpu(hp1).is_jmp or
  8857. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8858. Exit;
  8859. { NOP is a pipeline fence, likely marking the beginning of the function
  8860. epilogue, so drop out. Similarly, drop out if POP or RET are
  8861. encountered }
  8862. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8863. Exit;
  8864. if (taicpu(hp1).opcode = A_MOVSD) and
  8865. (taicpu(hp1).ops = 0) then
  8866. { Wrong MOVSD }
  8867. Exit;
  8868. { Check for writes to specific registers first }
  8869. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8870. for X := 0 to 7 do
  8871. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8872. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8873. Exit;
  8874. for X := 0 to taicpu(hp1).ops - 1 do
  8875. begin
  8876. { Check to see if this operand writes to something }
  8877. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8878. { And matches something in the CMP/TEST instruction }
  8879. (
  8880. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8881. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8882. (
  8883. { If it's a register, make sure the register written to doesn't
  8884. appear in the cmp instruction as part of a reference }
  8885. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8886. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8887. )
  8888. ) then
  8889. Exit;
  8890. end;
  8891. { Check p to make sure it doesn't write to something that affects hp1 }
  8892. { Check for writes to specific registers first }
  8893. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8894. for X := 0 to 7 do
  8895. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8896. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8897. Exit;
  8898. for X := 0 to taicpu(p).ops - 1 do
  8899. begin
  8900. { Check to see if this operand writes to something }
  8901. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8902. { And matches something in hp1 }
  8903. (taicpu(p).oper[X]^.typ = top_reg) and
  8904. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8905. Exit;
  8906. end;
  8907. { The instruction can be safely moved }
  8908. asml.Remove(hp1);
  8909. { Try to insert after the last instructions where the FLAGS register is not
  8910. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8911. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8912. asml.InsertBefore(hp1, hp2)
  8913. { Failing that, try to insert after the last instructions where the
  8914. FLAGS register is not yet in use }
  8915. else if GetLastInstruction(p, hp2) and
  8916. (
  8917. (hp2.typ <> ait_instruction) or
  8918. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8919. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8920. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8921. ) then
  8922. asml.InsertAfter(hp1, hp2)
  8923. else
  8924. { Note, if p.Previous is nil (even if it should logically never be the
  8925. case), FindRegAllocBackward immediately exits with False and so we
  8926. safely land here (we can't just pass p because FindRegAllocBackward
  8927. immediately exits on an instruction). [Kit] }
  8928. asml.InsertBefore(hp1, p);
  8929. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8930. { We can't trust UsedRegs because we're looking backwards, although we
  8931. know the registers are allocated after p at the very least, so manually
  8932. create tai_regalloc objects if needed }
  8933. for X := 0 to taicpu(hp1).ops - 1 do
  8934. case taicpu(hp1).oper[X]^.typ of
  8935. top_reg:
  8936. begin
  8937. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8938. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8939. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8940. end;
  8941. top_ref:
  8942. begin
  8943. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8944. begin
  8945. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8946. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8947. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8948. end;
  8949. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8950. begin
  8951. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8952. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8953. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8954. end;
  8955. end;
  8956. else
  8957. ;
  8958. end;
  8959. Result := True;
  8960. end;
  8961. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8962. var
  8963. hp2: tai;
  8964. X: Integer;
  8965. begin
  8966. { If we have something like:
  8967. cmp ###,%reg1
  8968. mov 0,%reg2
  8969. And no modified registers are shared, move the instruction to before
  8970. the comparison as this means it can be optimised without worrying
  8971. about the FLAGS register. (CMP/MOV is generated by
  8972. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8973. As long as the second instruction doesn't use the flags or one of the
  8974. registers used by CMP or TEST (also check any references that use the
  8975. registers), then it can be moved prior to the comparison.
  8976. }
  8977. Result := False;
  8978. if not TrySwapMovOp(p, hp1) then
  8979. Exit;
  8980. if taicpu(hp1).opcode = A_LEA then
  8981. { The flags will be overwritten by the CMP/TEST instruction }
  8982. ConvertLEA(taicpu(hp1));
  8983. Result := True;
  8984. { Can we move it one further back? }
  8985. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8986. { Check to see if CMP/TEST is a comparison against zero }
  8987. (
  8988. (
  8989. (taicpu(p).opcode = A_CMP) and
  8990. MatchOperand(taicpu(p).oper[0]^, 0)
  8991. ) or
  8992. (
  8993. (taicpu(p).opcode = A_TEST) and
  8994. (
  8995. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8996. MatchOperand(taicpu(p).oper[0]^, -1)
  8997. )
  8998. )
  8999. ) and
  9000. { These instructions set the zero flag if the result is zero }
  9001. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  9002. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  9003. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  9004. TrySwapMovOp(hp2, hp1);
  9005. end;
  9006. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  9007. var
  9008. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  9009. JumpLabel: TAsmLabel;
  9010. TmpBool: Boolean;
  9011. begin
  9012. Result := False;
  9013. { Look for:
  9014. stc/clc
  9015. j(c) .L1
  9016. ...
  9017. .L1:
  9018. set(n)cb %reg
  9019. (flags deallocated)
  9020. j(c) .L2
  9021. Change to:
  9022. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  9023. j(c) .L2
  9024. }
  9025. p_last := p;
  9026. while GetNextInstruction(p_last, hp1) and
  9027. (hp1.typ = ait_instruction) and
  9028. IsJumpToLabel(taicpu(hp1)) do
  9029. begin
  9030. if DoJumpOptimizations(hp1, TmpBool) then
  9031. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9032. Continue;
  9033. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  9034. if not Assigned(JumpLabel) then
  9035. InternalError(2024012801);
  9036. { Optimise the J(c); stc/clc optimisation first since this will
  9037. get missed if the main optimisation takes place }
  9038. if (taicpu(hp1).opcode = A_JCC) then
  9039. begin
  9040. if GetNextInstruction(hp1, hp2) and
  9041. MatchInstruction(hp2, A_CLC, A_STC, []) and
  9042. TryJccStcClcOpt(hp1, hp2) then
  9043. begin
  9044. Result := True;
  9045. Exit;
  9046. end;
  9047. hp2 := nil; { Suppress compiler warning }
  9048. if (taicpu(hp1).condition in [C_C, C_NC]) and
  9049. { Make sure the flags aren't used again }
  9050. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  9051. begin
  9052. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9053. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  9054. begin
  9055. if (taicpu(p).opcode = A_STC) then
  9056. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  9057. else
  9058. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  9059. MakeUnconditional(taicpu(hp1));
  9060. { Move the jump to after the flag deallocations }
  9061. Asml.Remove(hp1);
  9062. Asml.InsertAfter(hp1, hp2);
  9063. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9064. Result := True;
  9065. Exit;
  9066. end
  9067. else
  9068. begin
  9069. if (taicpu(p).opcode = A_STC) then
  9070. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  9071. else
  9072. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  9073. { In this case, the jump is deterministic in that it will never be taken }
  9074. JumpLabel.DecRefs;
  9075. RemoveInstruction(hp1);
  9076. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  9077. Result := True;
  9078. Exit;
  9079. end;
  9080. end;
  9081. end;
  9082. hp2 := nil; { Suppress compiler warning }
  9083. if
  9084. { Make sure the carry flag doesn't appear in the jump conditions }
  9085. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9086. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  9087. GetNextInstruction(hp2, p_dist) and
  9088. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  9089. (taicpu(p_dist).condition in [C_C, C_NC]) then
  9090. begin
  9091. case taicpu(p_dist).opcode of
  9092. A_Jcc:
  9093. begin
  9094. if DoJumpOptimizations(p_dist, TmpBool) then
  9095. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9096. Continue;
  9097. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9098. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  9099. begin
  9100. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  9101. JumpLabel.decrefs;
  9102. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  9103. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9104. Result := True;
  9105. Exit;
  9106. end
  9107. else if GetNextInstruction(p_dist, hp1_dist) and
  9108. (hp1_dist.typ = ait_label) then
  9109. begin
  9110. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  9111. JumpLabel.decrefs;
  9112. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  9113. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9114. Result := True;
  9115. Exit;
  9116. end;
  9117. end;
  9118. A_SETcc:
  9119. if { Make sure the flags aren't used again }
  9120. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  9121. GetNextInstruction(hp2, hp1_dist) and
  9122. (hp1_dist.typ = ait_instruction) and
  9123. IsJumpToLabel(taicpu(hp1_dist)) and
  9124. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9125. { This works if hp1_dist or both are regular JMP instructions }
  9126. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  9127. (
  9128. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  9129. { Make sure the register isn't still in use, otherwise it
  9130. may get corrupted (fixes #40659) }
  9131. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  9132. ) then
  9133. begin
  9134. taicpu(p).allocate_oper(2);
  9135. taicpu(p).ops := 2;
  9136. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  9137. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  9138. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  9139. taicpu(p).opcode := A_MOV;
  9140. taicpu(p).opsize := S_B;
  9141. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  9142. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  9143. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  9144. JumpLabel.decrefs;
  9145. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  9146. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  9147. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  9148. (tai_regalloc(hp2).ratype = ra_alloc) then
  9149. begin
  9150. Asml.Remove(hp2);
  9151. Asml.InsertAfter(hp2, p);
  9152. end;
  9153. Result := True;
  9154. Exit;
  9155. end;
  9156. else
  9157. ;
  9158. end;
  9159. end;
  9160. p_last := hp1;
  9161. end;
  9162. end;
  9163. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  9164. var
  9165. hp2, hp3: tai;
  9166. TempBool: Boolean;
  9167. begin
  9168. Result := False;
  9169. {
  9170. j(c) .L1
  9171. stc/clc
  9172. .L1:
  9173. jc/jnc .L2
  9174. (Flags deallocated)
  9175. Change to:
  9176. j)c) .L1
  9177. jmp .L2
  9178. .L1:
  9179. jc/jnc .L2
  9180. Then call DoJumpOptimizations to convert to:
  9181. j(nc) .L2
  9182. .L1: (may become a dead label)
  9183. jc/jnc .L2
  9184. }
  9185. if GetNextInstruction(hp1, hp2) and
  9186. (hp2.typ = ait_label) and
  9187. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  9188. GetNextInstruction(hp2, hp3) and
  9189. MatchInstruction(hp3, A_Jcc, []) and
  9190. (
  9191. (
  9192. (taicpu(hp3).condition = C_C) and
  9193. (taicpu(hp1).opcode = A_STC)
  9194. ) or (
  9195. (taicpu(hp3).condition = C_NC) and
  9196. (taicpu(hp1).opcode = A_CLC)
  9197. )
  9198. ) and
  9199. { Make sure the flags aren't used again }
  9200. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  9201. begin
  9202. taicpu(hp1).allocate_oper(1);
  9203. taicpu(hp1).ops := 1;
  9204. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  9205. taicpu(hp1).opcode := A_JMP;
  9206. taicpu(hp1).is_jmp := True;
  9207. TempBool := True; { Prevent compiler warnings }
  9208. if DoJumpOptimizations(p, TempBool) then
  9209. Result := True
  9210. else
  9211. Include(OptsToCheck, aoc_ForceNewIteration);
  9212. end;
  9213. end;
  9214. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  9215. begin
  9216. { This generally only executes under -O3 and above }
  9217. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  9218. end;
  9219. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  9220. var
  9221. hp1, hp2: tai;
  9222. FoundComparison: Boolean;
  9223. begin
  9224. { Run the pass 1 optimisations as well, since they may have some effect
  9225. after the CMOV blocks are created in OptPass2Jcc }
  9226. Result := False;
  9227. { Result := OptPass1CMOVcc(p);
  9228. if Result then
  9229. Exit;}
  9230. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9231. and make a slightly inefficent result on branching-type blocks, notably
  9232. when setting a function result then jumping to the function epilogue.
  9233. In this case, change:
  9234. cmov(c) %reg1,%reg2
  9235. j(c) @lbl
  9236. (%reg2 deallocated)
  9237. To:
  9238. mov %reg11,%reg2
  9239. j(c) @lbl
  9240. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9241. jump because if it's not present, we may end up with a jump that's
  9242. completely unrelated.
  9243. }
  9244. hp1 := p;
  9245. while GetNextInstruction(hp1, hp1) and
  9246. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9247. if (hp1.typ = ait_instruction) and
  9248. (taicpu(hp1).opcode = A_Jcc) and
  9249. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9250. begin
  9251. TransferUsedRegs(TmpUsedRegs);
  9252. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9253. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9254. (
  9255. { See if we can find a more distant instruction that overwrites
  9256. the destination register }
  9257. (cs_opt_level3 in current_settings.optimizerswitches) and
  9258. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9259. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9260. ) then
  9261. begin
  9262. if (taicpu(p).oper[0]^.typ = top_reg) then
  9263. begin
  9264. { Search backwards to see if the source register is set to a
  9265. constant }
  9266. FoundComparison := False;
  9267. hp1 := p;
  9268. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9269. begin
  9270. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9271. begin
  9272. FoundComparison := True;
  9273. Continue;
  9274. end;
  9275. { Once we find the CMP, TEST or similar instruction, we
  9276. have to stop if we find anything other than a MOV }
  9277. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9278. Break;
  9279. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9280. { Destination register was modified }
  9281. Break;
  9282. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9283. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9284. begin
  9285. { Found a constant! }
  9286. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9287. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9288. { The source register is no longer in use }
  9289. RemoveInstruction(hp1);
  9290. Break;
  9291. end;
  9292. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9293. { Some other instruction has modified the source register }
  9294. Break;
  9295. end;
  9296. end;
  9297. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9298. taicpu(p).opcode := A_MOV;
  9299. taicpu(p).condition := C_None;
  9300. { Rely on the post peephole stage to put the MOV before the
  9301. CMP/TEST instruction that appears prior }
  9302. Result := True;
  9303. Exit;
  9304. end;
  9305. end;
  9306. end;
  9307. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9308. function IsXCHGAcceptable: Boolean; inline;
  9309. begin
  9310. { Always accept if optimising for size }
  9311. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9312. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9313. than 3, so it becomes a saving compared to three MOVs with two of
  9314. them able to execute simultaneously. [Kit] }
  9315. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9316. end;
  9317. var
  9318. NewRef: TReference;
  9319. hp1, hp2, hp3, hp4: Tai;
  9320. {$ifndef x86_64}
  9321. OperIdx: Integer;
  9322. {$endif x86_64}
  9323. NewInstr : Taicpu;
  9324. NewAligh : Tai_align;
  9325. DestLabel: TAsmLabel;
  9326. TempTracking: TAllUsedRegs;
  9327. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9328. var
  9329. NextInstr: tai;
  9330. begin
  9331. Result := False;
  9332. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9333. if not GetNextInstruction(InputInstr, NextInstr) or
  9334. (
  9335. { The FLAGS register isn't always tracked properly, so do not
  9336. perform this optimisation if a conditional statement follows }
  9337. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9338. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9339. ) then
  9340. begin
  9341. reference_reset(NewRef, 1, []);
  9342. NewRef.base := taicpu(p).oper[0]^.reg;
  9343. NewRef.scalefactor := 1;
  9344. if taicpu(InputInstr).opcode = A_ADD then
  9345. begin
  9346. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9347. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9348. end
  9349. else
  9350. begin
  9351. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9352. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9353. end;
  9354. taicpu(p).opcode := A_LEA;
  9355. taicpu(p).loadref(0, NewRef);
  9356. { For the sake of debugging, have the line info match the
  9357. arithmetic instruction rather than the MOV instruction }
  9358. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9359. RemoveInstruction(InputInstr);
  9360. Result := True;
  9361. end;
  9362. end;
  9363. begin
  9364. Result:=false;
  9365. { This optimisation adds an instruction, so only do it for speed }
  9366. if not (cs_opt_size in current_settings.optimizerswitches) and
  9367. MatchOpType(taicpu(p), top_const, top_reg) and
  9368. (taicpu(p).oper[0]^.val = 0) then
  9369. begin
  9370. { To avoid compiler warning }
  9371. DestLabel := nil;
  9372. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9373. InternalError(2021040750);
  9374. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9375. Exit;
  9376. case hp1.typ of
  9377. ait_label:
  9378. begin
  9379. { Change:
  9380. mov $0,%reg mov $0,%reg
  9381. @Lbl1: @Lbl1:
  9382. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9383. je @Lbl2 jne @Lbl2
  9384. To: To:
  9385. mov $0,%reg mov $0,%reg
  9386. jmp @Lbl2 jmp @Lbl3
  9387. (align) (align)
  9388. @Lbl1: @Lbl1:
  9389. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9390. je @Lbl2 je @Lbl2
  9391. @Lbl3: <-- Only if label exists
  9392. (Not if it's optimised for size)
  9393. }
  9394. if not GetNextInstruction(hp1, hp2) then
  9395. Exit;
  9396. if (hp2.typ = ait_instruction) and
  9397. (
  9398. { Register sizes must exactly match }
  9399. (
  9400. (taicpu(hp2).opcode = A_CMP) and
  9401. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9402. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9403. ) or (
  9404. (taicpu(hp2).opcode = A_TEST) and
  9405. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9406. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9407. )
  9408. ) and GetNextInstruction(hp2, hp3) and
  9409. (hp3.typ = ait_instruction) and
  9410. (taicpu(hp3).opcode = A_JCC) and
  9411. (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
  9412. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9413. begin
  9414. { Check condition of jump }
  9415. { Always true? }
  9416. if condition_in(C_E, taicpu(hp3).condition) then
  9417. begin
  9418. { Copy label symbol and obtain matching label entry for the
  9419. conditional jump, as this will be our destination}
  9420. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9421. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9422. Result := True;
  9423. end
  9424. { Always false? }
  9425. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9426. begin
  9427. { This is only worth it if there's a jump to take }
  9428. case hp2.typ of
  9429. ait_instruction:
  9430. begin
  9431. if taicpu(hp2).opcode = A_JMP then
  9432. begin
  9433. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9434. { An unconditional jump follows the conditional jump which will always be false,
  9435. so use this jump's destination for the new jump }
  9436. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9437. Result := True;
  9438. end
  9439. else if taicpu(hp2).opcode = A_JCC then
  9440. begin
  9441. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9442. if condition_in(C_E, taicpu(hp2).condition) then
  9443. begin
  9444. { A second conditional jump follows the conditional jump which will always be false,
  9445. while the second jump is always True, so use this jump's destination for the new jump }
  9446. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9447. Result := True;
  9448. end;
  9449. { Don't risk it if the jump isn't always true (Result remains False) }
  9450. end;
  9451. end;
  9452. else
  9453. { If anything else don't optimise };
  9454. end;
  9455. end;
  9456. if Result then
  9457. begin
  9458. { Just so we have something to insert as a paremeter}
  9459. reference_reset(NewRef, 1, []);
  9460. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9461. { Now actually load the correct parameter (this also
  9462. increases the reference count) }
  9463. NewInstr.loadsymbol(0, DestLabel, 0);
  9464. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9465. begin
  9466. { Get instruction before original label (may not be p under -O3) }
  9467. if not GetLastInstruction(hp1, hp2) then
  9468. { Shouldn't fail here }
  9469. InternalError(2021040701);
  9470. end
  9471. else
  9472. hp2 := p;
  9473. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9474. AsmL.InsertAfter(NewInstr, hp2);
  9475. { Add new alignment field }
  9476. (* AsmL.InsertAfter(
  9477. cai_align.create_max(
  9478. current_settings.alignment.jumpalign,
  9479. current_settings.alignment.jumpalignskipmax
  9480. ),
  9481. NewInstr
  9482. ); *)
  9483. end;
  9484. Exit;
  9485. end;
  9486. end;
  9487. else
  9488. ;
  9489. end;
  9490. end;
  9491. if not GetNextInstruction(p, hp1) then
  9492. Exit;
  9493. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9494. begin
  9495. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9496. begin
  9497. Result := True;
  9498. Exit;
  9499. end;
  9500. { This optimisation is only effective on a second run of Pass 2,
  9501. hence -O3 or above.
  9502. Change:
  9503. mov %reg1,%reg2
  9504. cmp/test (contains %reg1)
  9505. mov x, %reg1
  9506. (another mov or a j(c))
  9507. To:
  9508. mov %reg1,%reg2
  9509. mov x, %reg1
  9510. cmp (%reg1 replaced with %reg2)
  9511. (another mov or a j(c))
  9512. The requirement of an additional MOV or a jump ensures there
  9513. isn't performance loss, since a j(c) will permit macro-fusion
  9514. with the cmp instruction, while another MOV likely means it's
  9515. not all being executed in a single cycle due to parallelisation.
  9516. }
  9517. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9518. MatchOpType(taicpu(p), top_reg, top_reg) and
  9519. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9520. GetNextInstruction(hp1, hp2) and
  9521. MatchInstruction(hp2, A_MOV, []) and
  9522. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9523. { Registers don't have to be the same size in this case }
  9524. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9525. GetNextInstruction(hp2, hp3) and
  9526. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9527. { Make sure the operands in the camparison can be safely replaced }
  9528. (
  9529. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9530. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9531. ) and
  9532. (
  9533. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9534. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9535. ) then
  9536. begin
  9537. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9538. AsmL.Remove(hp2);
  9539. AsmL.InsertAfter(hp2, p);
  9540. Result := True;
  9541. Exit;
  9542. end;
  9543. end;
  9544. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9545. begin
  9546. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9547. further, but we can't just put this jump optimisation in pass 1
  9548. because it tends to perform worse when conditional jumps are
  9549. nearby (e.g. when converting CMOV instructions). [Kit] }
  9550. CopyUsedRegs(TempTracking);
  9551. UpdateUsedRegs(tai(p.Next));
  9552. if OptPass2JMP(hp1) then
  9553. begin
  9554. { Restore register state }
  9555. RestoreUsedRegs(TempTracking);
  9556. ReleaseUsedRegs(TempTracking);
  9557. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9558. OptPass1MOV(p);
  9559. Result := True;
  9560. Exit;
  9561. end;
  9562. { If OptPass2JMP returned False, no optimisations were done to
  9563. the jump and there are no further optimisations that can be done
  9564. to the MOV instruction on this pass other than FuncMov2Func }
  9565. { Restore register state }
  9566. RestoreUsedRegs(TempTracking);
  9567. ReleaseUsedRegs(TempTracking);
  9568. Result := FuncMov2Func(p, hp1);
  9569. Exit;
  9570. end;
  9571. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9572. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9573. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9574. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9575. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9576. begin
  9577. { Change:
  9578. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9579. addl/q $x,%reg2 subl/q $x,%reg2
  9580. To:
  9581. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9582. }
  9583. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9584. { be lazy, checking separately for sub would be slightly better }
  9585. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9586. begin
  9587. TransferUsedRegs(TmpUsedRegs);
  9588. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9589. if TryMovArith2Lea(hp1) then
  9590. begin
  9591. Result := True;
  9592. Exit;
  9593. end
  9594. end
  9595. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9596. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9597. { Same as above, but also adds or subtracts to %reg2 in between.
  9598. It's still valid as long as the flags aren't in use }
  9599. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9600. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9601. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9602. { be lazy, checking separately for sub would be slightly better }
  9603. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9604. begin
  9605. TransferUsedRegs(TmpUsedRegs);
  9606. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9607. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9608. if TryMovArith2Lea(hp2) then
  9609. begin
  9610. Result := True;
  9611. Exit;
  9612. end;
  9613. end;
  9614. end;
  9615. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9616. {$ifdef x86_64}
  9617. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9618. {$else x86_64}
  9619. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9620. {$endif x86_64}
  9621. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9622. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9623. { mov reg1, reg2 mov reg1, reg2
  9624. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9625. begin
  9626. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9627. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9628. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9629. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9630. TransferUsedRegs(TmpUsedRegs);
  9631. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9632. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9633. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9634. then
  9635. begin
  9636. RemoveCurrentP(p, hp1);
  9637. Result:=true;
  9638. end;
  9639. Exit;
  9640. end;
  9641. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9642. IsXCHGAcceptable and
  9643. { XCHG doesn't support 8-bit registers }
  9644. (taicpu(p).opsize <> S_B) and
  9645. MatchInstruction(hp1, A_MOV, []) and
  9646. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9647. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9648. GetNextInstruction(hp1, hp2) and
  9649. MatchInstruction(hp2, A_MOV, []) and
  9650. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9651. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9652. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9653. begin
  9654. { mov %reg1,%reg2
  9655. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9656. mov %reg2,%reg3
  9657. (%reg2 not used afterwards)
  9658. Note that xchg takes 3 cycles to execute, and generally mov's take
  9659. only one cycle apiece, but the first two mov's can be executed in
  9660. parallel, only taking 2 cycles overall. Older processors should
  9661. therefore only optimise for size. [Kit]
  9662. }
  9663. TransferUsedRegs(TmpUsedRegs);
  9664. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9665. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9666. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9667. begin
  9668. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9669. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9670. taicpu(hp1).opcode := A_XCHG;
  9671. RemoveCurrentP(p, hp1);
  9672. RemoveInstruction(hp2);
  9673. Result := True;
  9674. Exit;
  9675. end;
  9676. end;
  9677. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9678. MatchInstruction(hp1, A_SAR, []) then
  9679. begin
  9680. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9681. begin
  9682. { the use of %edx also covers the opsize being S_L }
  9683. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9684. begin
  9685. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9686. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9687. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9688. begin
  9689. { Change:
  9690. movl %eax,%edx
  9691. sarl $31,%edx
  9692. To:
  9693. cltd
  9694. }
  9695. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9696. RemoveInstruction(hp1);
  9697. taicpu(p).opcode := A_CDQ;
  9698. taicpu(p).opsize := S_NO;
  9699. taicpu(p).clearop(1);
  9700. taicpu(p).clearop(0);
  9701. taicpu(p).ops:=0;
  9702. Result := True;
  9703. Exit;
  9704. end
  9705. else if (cs_opt_size in current_settings.optimizerswitches) and
  9706. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9707. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9708. begin
  9709. { Change:
  9710. movl %edx,%eax
  9711. sarl $31,%edx
  9712. To:
  9713. movl %edx,%eax
  9714. cltd
  9715. Note that this creates a dependency between the two instructions,
  9716. so only perform if optimising for size.
  9717. }
  9718. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9719. taicpu(hp1).opcode := A_CDQ;
  9720. taicpu(hp1).opsize := S_NO;
  9721. taicpu(hp1).clearop(1);
  9722. taicpu(hp1).clearop(0);
  9723. taicpu(hp1).ops:=0;
  9724. Include(OptsToCheck, aoc_ForceNewIteration);
  9725. Exit;
  9726. end;
  9727. {$ifndef x86_64}
  9728. end
  9729. { Don't bother if CMOV is supported, because a more optimal
  9730. sequence would have been generated for the Abs() intrinsic }
  9731. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9732. { the use of %eax also covers the opsize being S_L }
  9733. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9734. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9735. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9736. GetNextInstruction(hp1, hp2) and
  9737. MatchInstruction(hp2, A_XOR, [S_L]) and
  9738. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9739. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9740. GetNextInstruction(hp2, hp3) and
  9741. MatchInstruction(hp3, A_SUB, [S_L]) and
  9742. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9743. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9744. begin
  9745. { Change:
  9746. movl %eax,%edx
  9747. sarl $31,%eax
  9748. xorl %eax,%edx
  9749. subl %eax,%edx
  9750. (Instruction that uses %edx)
  9751. (%eax deallocated)
  9752. (%edx deallocated)
  9753. To:
  9754. cltd
  9755. xorl %edx,%eax <-- Note the registers have swapped
  9756. subl %edx,%eax
  9757. (Instruction that uses %eax) <-- %eax rather than %edx
  9758. }
  9759. TransferUsedRegs(TmpUsedRegs);
  9760. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9761. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9762. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9763. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9764. begin
  9765. if GetNextInstruction(hp3, hp4) and
  9766. not RegModifiedByInstruction(NR_EDX, hp4) and
  9767. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9768. begin
  9769. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9770. taicpu(p).opcode := A_CDQ;
  9771. taicpu(p).clearop(1);
  9772. taicpu(p).clearop(0);
  9773. taicpu(p).ops:=0;
  9774. RemoveInstruction(hp1);
  9775. taicpu(hp2).loadreg(0, NR_EDX);
  9776. taicpu(hp2).loadreg(1, NR_EAX);
  9777. taicpu(hp3).loadreg(0, NR_EDX);
  9778. taicpu(hp3).loadreg(1, NR_EAX);
  9779. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9780. { Convert references in the following instruction (hp4) from %edx to %eax }
  9781. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9782. with taicpu(hp4).oper[OperIdx]^ do
  9783. case typ of
  9784. top_reg:
  9785. if getsupreg(reg) = RS_EDX then
  9786. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9787. top_ref:
  9788. begin
  9789. if getsupreg(reg) = RS_EDX then
  9790. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9791. if getsupreg(reg) = RS_EDX then
  9792. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9793. end;
  9794. else
  9795. ;
  9796. end;
  9797. Result := True;
  9798. Exit;
  9799. end;
  9800. end;
  9801. {$else x86_64}
  9802. end;
  9803. end
  9804. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9805. { the use of %rdx also covers the opsize being S_Q }
  9806. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9807. begin
  9808. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9809. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9810. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9811. begin
  9812. { Change:
  9813. movq %rax,%rdx
  9814. sarq $63,%rdx
  9815. To:
  9816. cqto
  9817. }
  9818. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9819. RemoveInstruction(hp1);
  9820. taicpu(p).opcode := A_CQO;
  9821. taicpu(p).opsize := S_NO;
  9822. taicpu(p).clearop(1);
  9823. taicpu(p).clearop(0);
  9824. taicpu(p).ops:=0;
  9825. Result := True;
  9826. Exit;
  9827. end
  9828. else if (cs_opt_size in current_settings.optimizerswitches) and
  9829. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9830. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9831. begin
  9832. { Change:
  9833. movq %rdx,%rax
  9834. sarq $63,%rdx
  9835. To:
  9836. movq %rdx,%rax
  9837. cqto
  9838. Note that this creates a dependency between the two instructions,
  9839. so only perform if optimising for size.
  9840. }
  9841. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9842. taicpu(hp1).opcode := A_CQO;
  9843. taicpu(hp1).opsize := S_NO;
  9844. taicpu(hp1).clearop(1);
  9845. taicpu(hp1).clearop(0);
  9846. taicpu(hp1).ops:=0;
  9847. Include(OptsToCheck, aoc_ForceNewIteration);
  9848. Exit;
  9849. {$endif x86_64}
  9850. end;
  9851. end;
  9852. end;
  9853. if MatchInstruction(hp1, A_MOV, []) and
  9854. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9855. { Though "GetNextInstruction" could be factored out, along with
  9856. the instructions that depend on hp2, it is an expensive call that
  9857. should be delayed for as long as possible, hence we do cheaper
  9858. checks first that are likely to be False. [Kit] }
  9859. begin
  9860. if (
  9861. (
  9862. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9863. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9864. (
  9865. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9866. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9867. )
  9868. ) or
  9869. (
  9870. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9871. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9872. (
  9873. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9874. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9875. )
  9876. )
  9877. ) and
  9878. GetNextInstruction(hp1, hp2) and
  9879. MatchInstruction(hp2, A_SAR, []) and
  9880. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9881. begin
  9882. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9883. begin
  9884. { Change:
  9885. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9886. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9887. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9888. To:
  9889. movl r/m,%eax <- Note the change in register
  9890. cltd
  9891. }
  9892. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9893. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9894. taicpu(p).loadreg(1, NR_EAX);
  9895. taicpu(hp1).opcode := A_CDQ;
  9896. taicpu(hp1).clearop(1);
  9897. taicpu(hp1).clearop(0);
  9898. taicpu(hp1).ops:=0;
  9899. RemoveInstruction(hp2);
  9900. Include(OptsToCheck, aoc_ForceNewIteration);
  9901. (*
  9902. {$ifdef x86_64}
  9903. end
  9904. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9905. { This code sequence does not get generated - however it might become useful
  9906. if and when 128-bit signed integer types make an appearance, so the code
  9907. is kept here for when it is eventually needed. [Kit] }
  9908. (
  9909. (
  9910. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9911. (
  9912. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9913. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9914. )
  9915. ) or
  9916. (
  9917. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9918. (
  9919. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9920. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9921. )
  9922. )
  9923. ) and
  9924. GetNextInstruction(hp1, hp2) and
  9925. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9926. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9927. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9928. begin
  9929. { Change:
  9930. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9931. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9932. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9933. To:
  9934. movq r/m,%rax <- Note the change in register
  9935. cqto
  9936. }
  9937. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9938. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9939. taicpu(p).loadreg(1, NR_RAX);
  9940. taicpu(hp1).opcode := A_CQO;
  9941. taicpu(hp1).clearop(1);
  9942. taicpu(hp1).clearop(0);
  9943. taicpu(hp1).ops:=0;
  9944. RemoveInstruction(hp2);
  9945. Include(OptsToCheck, aoc_ForceNewIteration);
  9946. {$endif x86_64}
  9947. *)
  9948. end;
  9949. end;
  9950. {$ifdef x86_64}
  9951. end;
  9952. if (taicpu(p).opsize = S_L) and
  9953. (taicpu(p).oper[1]^.typ = top_reg) and
  9954. (
  9955. MatchInstruction(hp1, A_MOV,[]) and
  9956. (taicpu(hp1).opsize = S_L) and
  9957. (taicpu(hp1).oper[1]^.typ = top_reg)
  9958. ) and (
  9959. GetNextInstruction(hp1, hp2) and
  9960. (tai(hp2).typ=ait_instruction) and
  9961. (taicpu(hp2).opsize = S_Q) and
  9962. (
  9963. (
  9964. MatchInstruction(hp2, A_ADD,[]) and
  9965. (taicpu(hp2).opsize = S_Q) and
  9966. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9967. (
  9968. (
  9969. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9970. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9971. ) or (
  9972. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9973. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9974. )
  9975. )
  9976. ) or (
  9977. MatchInstruction(hp2, A_LEA,[]) and
  9978. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9979. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9980. (
  9981. (
  9982. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9983. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9984. ) or (
  9985. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9986. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9987. )
  9988. ) and (
  9989. (
  9990. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9991. ) or (
  9992. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9993. )
  9994. )
  9995. )
  9996. )
  9997. ) and (
  9998. GetNextInstruction(hp2, hp3) and
  9999. MatchInstruction(hp3, A_SHR,[]) and
  10000. (taicpu(hp3).opsize = S_Q) and
  10001. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  10002. (taicpu(hp3).oper[0]^.val = 1) and
  10003. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  10004. ) then
  10005. begin
  10006. { Change movl x, reg1d movl x, reg1d
  10007. movl y, reg2d movl y, reg2d
  10008. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  10009. shrq $1, reg1q shrq $1, reg1q
  10010. ( reg1d and reg2d can be switched around in the first two instructions )
  10011. To movl x, reg1d
  10012. addl y, reg1d
  10013. rcrl $1, reg1d
  10014. This corresponds to the common expression (x + y) shr 1, where
  10015. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  10016. smaller code, but won't account for x + y causing an overflow). [Kit]
  10017. }
  10018. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  10019. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10020. begin
  10021. { Change first MOV command to have the same register as the final output }
  10022. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10023. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  10024. Result := True;
  10025. end
  10026. else
  10027. begin
  10028. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  10029. Include(OptsToCheck, aoc_ForceNewIteration);
  10030. end;
  10031. { Change second MOV command to an ADD command. This is easier than
  10032. converting the existing command because it means we don't have to
  10033. touch 'y', which might be a complicated reference, and also the
  10034. fact that the third command might either be ADD or LEA. [Kit] }
  10035. taicpu(hp1).opcode := A_ADD;
  10036. { Delete old ADD/LEA instruction }
  10037. RemoveInstruction(hp2);
  10038. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  10039. taicpu(hp3).opcode := A_RCR;
  10040. taicpu(hp3).changeopsize(S_L);
  10041. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  10042. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  10043. called, so FuncMov2Func below is safe to call }
  10044. {$endif x86_64}
  10045. end;
  10046. if FuncMov2Func(p, hp1) then
  10047. begin
  10048. Result := True;
  10049. Exit;
  10050. end;
  10051. end;
  10052. {$push}
  10053. {$q-}{$r-}
  10054. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  10055. var
  10056. ThisReg: TRegister;
  10057. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  10058. TargetSubReg: TSubRegister;
  10059. hp1, hp2: tai;
  10060. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  10061. { Store list of found instructions so we don't have to call
  10062. GetNextInstructionUsingReg multiple times }
  10063. InstrList: array of taicpu;
  10064. InstrMax, Index: Integer;
  10065. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  10066. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  10067. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  10068. WorkingValue: TCgInt;
  10069. PreMessage: string;
  10070. { Data flow analysis }
  10071. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  10072. BitwiseOnly, OrXorUsed,
  10073. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  10074. function CheckOverflowConditions: Boolean;
  10075. begin
  10076. Result := True;
  10077. if (TestValSignedMax > SignedUpperLimit) then
  10078. UpperSignedOverflow := True;
  10079. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  10080. LowerSignedOverflow := True;
  10081. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  10082. LowerUnsignedOverflow := True;
  10083. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  10084. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  10085. begin
  10086. { Absolute overflow }
  10087. Result := False;
  10088. Exit;
  10089. end;
  10090. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  10091. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  10092. ShiftDownOverflow := True;
  10093. if (TestValMin < 0) or (TestValMax < 0) then
  10094. begin
  10095. LowerUnsignedOverflow := True;
  10096. UpperUnsignedOverflow := True;
  10097. end;
  10098. end;
  10099. function AdjustInitialLoadAndSize: Boolean;
  10100. begin
  10101. Result := False;
  10102. if not p_removed then
  10103. begin
  10104. if TargetSize = MinSize then
  10105. begin
  10106. { Convert the input MOVZX to a MOV }
  10107. if (taicpu(p).oper[0]^.typ = top_reg) and
  10108. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10109. begin
  10110. { Or remove it completely! }
  10111. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  10112. RemoveCurrentP(p);
  10113. p_removed := True;
  10114. end
  10115. else
  10116. begin
  10117. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  10118. taicpu(p).opcode := A_MOV;
  10119. taicpu(p).oper[1]^.reg := ThisReg;
  10120. taicpu(p).opsize := TargetSize;
  10121. end;
  10122. Result := True;
  10123. end
  10124. else if TargetSize <> MaxSize then
  10125. begin
  10126. case MaxSize of
  10127. S_L:
  10128. if TargetSize = S_W then
  10129. begin
  10130. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  10131. taicpu(p).opsize := S_BW;
  10132. taicpu(p).oper[1]^.reg := ThisReg;
  10133. Result := True;
  10134. end
  10135. else
  10136. InternalError(2020112341);
  10137. S_W:
  10138. if TargetSize = S_L then
  10139. begin
  10140. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  10141. taicpu(p).opsize := S_BL;
  10142. taicpu(p).oper[1]^.reg := ThisReg;
  10143. Result := True;
  10144. end
  10145. else
  10146. InternalError(2020112342);
  10147. else
  10148. ;
  10149. end;
  10150. end
  10151. else if not hp1_removed and not RegInUse then
  10152. begin
  10153. { If we have something like:
  10154. movzbl (oper),%regd
  10155. add x, %regd
  10156. movzbl %regb, %regd
  10157. We can reduce the register size to the input of the final
  10158. movzbl instruction. Overflows won't have any effect.
  10159. }
  10160. if (taicpu(p).opsize in [S_BW, S_BL]) and
  10161. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10162. begin
  10163. TargetSize := S_B;
  10164. setsubreg(ThisReg, R_SUBL);
  10165. Result := True;
  10166. end
  10167. else if (taicpu(p).opsize = S_WL) and
  10168. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10169. begin
  10170. TargetSize := S_W;
  10171. setsubreg(ThisReg, R_SUBW);
  10172. Result := True;
  10173. end;
  10174. if Result then
  10175. begin
  10176. { Convert the input MOVZX to a MOV }
  10177. if (taicpu(p).oper[0]^.typ = top_reg) and
  10178. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10179. begin
  10180. { Or remove it completely! }
  10181. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  10182. RemoveCurrentP(p);
  10183. p_removed := True;
  10184. end
  10185. else
  10186. begin
  10187. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  10188. taicpu(p).opcode := A_MOV;
  10189. taicpu(p).oper[1]^.reg := ThisReg;
  10190. taicpu(p).opsize := TargetSize;
  10191. end;
  10192. end;
  10193. end;
  10194. end;
  10195. end;
  10196. procedure AdjustFinalLoad;
  10197. begin
  10198. if not LowerUnsignedOverflow then
  10199. begin
  10200. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  10201. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  10202. begin
  10203. { Convert the output MOVZX to a MOV }
  10204. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10205. begin
  10206. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  10207. if (MinSize = S_B) or
  10208. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  10209. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  10210. begin
  10211. { Remove it completely! }
  10212. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  10213. { Be careful; if p = hp1 and p was also removed, p
  10214. will become a dangling pointer }
  10215. if p = hp1 then
  10216. begin
  10217. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10218. p_removed := True;
  10219. end
  10220. else
  10221. RemoveInstruction(hp1);
  10222. hp1_removed := True;
  10223. end;
  10224. end
  10225. else
  10226. begin
  10227. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10228. taicpu(hp1).opcode := A_MOV;
  10229. taicpu(hp1).oper[0]^.reg := ThisReg;
  10230. taicpu(hp1).opsize := TargetSize;
  10231. end;
  10232. end
  10233. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10234. begin
  10235. { Need to change the size of the output }
  10236. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10237. taicpu(hp1).oper[0]^.reg := ThisReg;
  10238. taicpu(hp1).opsize := S_BL;
  10239. end;
  10240. end;
  10241. end;
  10242. function CompressInstructions: Boolean;
  10243. var
  10244. LocalIndex: Integer;
  10245. begin
  10246. Result := False;
  10247. { The objective here is to try to find a combination that
  10248. removes one of the MOV/Z instructions. }
  10249. if (
  10250. (taicpu(p).oper[0]^.typ <> top_reg) or
  10251. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10252. ) and
  10253. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10254. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10255. begin
  10256. { Make a preference to remove the second MOVZX instruction }
  10257. case taicpu(hp1).opsize of
  10258. S_BL, S_WL:
  10259. begin
  10260. TargetSize := S_L;
  10261. TargetSubReg := R_SUBD;
  10262. end;
  10263. S_BW:
  10264. begin
  10265. TargetSize := S_W;
  10266. TargetSubReg := R_SUBW;
  10267. end;
  10268. else
  10269. InternalError(2020112302);
  10270. end;
  10271. end
  10272. else
  10273. begin
  10274. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10275. begin
  10276. { Exceeded lower bound but not upper bound }
  10277. TargetSize := MaxSize;
  10278. end
  10279. else if not LowerUnsignedOverflow then
  10280. begin
  10281. { Size didn't exceed lower bound }
  10282. TargetSize := MinSize;
  10283. end
  10284. else
  10285. Exit;
  10286. end;
  10287. case TargetSize of
  10288. S_B:
  10289. TargetSubReg := R_SUBL;
  10290. S_W:
  10291. TargetSubReg := R_SUBW;
  10292. S_L:
  10293. TargetSubReg := R_SUBD;
  10294. else
  10295. InternalError(2020112350);
  10296. end;
  10297. { Update the register to its new size }
  10298. setsubreg(ThisReg, TargetSubReg);
  10299. RegInUse := False;
  10300. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10301. begin
  10302. { Check to see if the active register is used afterwards;
  10303. if not, we can change it and make a saving. }
  10304. TransferUsedRegs(TmpUsedRegs);
  10305. { The target register may be marked as in use to cross
  10306. a jump to a distant label, so exclude it }
  10307. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10308. hp2 := p;
  10309. repeat
  10310. { Explicitly check for the excluded register (don't include the first
  10311. instruction as it may be reading from here }
  10312. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10313. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10314. begin
  10315. RegInUse := True;
  10316. Break;
  10317. end;
  10318. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10319. if not GetNextInstruction(hp2, hp2) then
  10320. InternalError(2020112340);
  10321. until (hp2 = hp1);
  10322. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10323. { We might still be able to get away with this }
  10324. RegInUse := not
  10325. (
  10326. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10327. (hp2.typ = ait_instruction) and
  10328. (
  10329. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10330. instruction that doesn't actually contain ThisReg }
  10331. (cs_opt_level3 in current_settings.optimizerswitches) or
  10332. RegInInstruction(ThisReg, hp2)
  10333. ) and
  10334. RegLoadedWithNewValue(ThisReg, hp2)
  10335. );
  10336. if not RegInUse then
  10337. begin
  10338. { Force the register size to the same as this instruction so it can be removed}
  10339. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10340. begin
  10341. TargetSize := S_L;
  10342. TargetSubReg := R_SUBD;
  10343. end
  10344. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10345. begin
  10346. TargetSize := S_W;
  10347. TargetSubReg := R_SUBW;
  10348. end;
  10349. ThisReg := taicpu(hp1).oper[1]^.reg;
  10350. setsubreg(ThisReg, TargetSubReg);
  10351. RegChanged := True;
  10352. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10353. TransferUsedRegs(TmpUsedRegs);
  10354. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10355. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10356. if p = hp1 then
  10357. begin
  10358. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10359. p_removed := True;
  10360. end
  10361. else
  10362. RemoveInstruction(hp1);
  10363. hp1_removed := True;
  10364. { Instruction will become "mov %reg,%reg" }
  10365. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10366. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10367. begin
  10368. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10369. RemoveCurrentP(p);
  10370. p_removed := True;
  10371. end
  10372. else
  10373. taicpu(p).oper[1]^.reg := ThisReg;
  10374. Result := True;
  10375. end
  10376. else
  10377. begin
  10378. if TargetSize <> MaxSize then
  10379. begin
  10380. { Since the register is in use, we have to force it to
  10381. MaxSize otherwise part of it may become undefined later on }
  10382. TargetSize := MaxSize;
  10383. case TargetSize of
  10384. S_B:
  10385. TargetSubReg := R_SUBL;
  10386. S_W:
  10387. TargetSubReg := R_SUBW;
  10388. S_L:
  10389. TargetSubReg := R_SUBD;
  10390. else
  10391. InternalError(2020112351);
  10392. end;
  10393. setsubreg(ThisReg, TargetSubReg);
  10394. end;
  10395. AdjustFinalLoad;
  10396. end;
  10397. end
  10398. else
  10399. AdjustFinalLoad;
  10400. Result := AdjustInitialLoadAndSize or Result;
  10401. { Now go through every instruction we found and change the
  10402. size. If TargetSize = MaxSize, then almost no changes are
  10403. needed and Result can remain False if it hasn't been set
  10404. yet.
  10405. If RegChanged is True, then the register requires changing
  10406. and so the point about TargetSize = MaxSize doesn't apply. }
  10407. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10408. begin
  10409. for LocalIndex := 0 to InstrMax do
  10410. begin
  10411. { If p_removed is true, then the original MOV/Z was removed
  10412. and removing the AND instruction may not be safe if it
  10413. appears first }
  10414. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10415. InternalError(2020112310);
  10416. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10417. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10418. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10419. InstrList[LocalIndex].opsize := TargetSize;
  10420. end;
  10421. Result := True;
  10422. end;
  10423. end;
  10424. begin
  10425. Result := False;
  10426. p_removed := False;
  10427. hp1_removed := False;
  10428. ThisReg := taicpu(p).oper[1]^.reg;
  10429. { Check for:
  10430. movs/z ###,%ecx (or %cx or %rcx)
  10431. ...
  10432. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10433. (dealloc %ecx)
  10434. Change to:
  10435. mov ###,%cl (if ### = %cl, then remove completely)
  10436. ...
  10437. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10438. }
  10439. if (getsupreg(ThisReg) = RS_ECX) and
  10440. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10441. (hp1.typ = ait_instruction) and
  10442. (
  10443. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10444. instruction that doesn't actually contain ECX }
  10445. (cs_opt_level3 in current_settings.optimizerswitches) or
  10446. RegInInstruction(NR_ECX, hp1) or
  10447. (
  10448. { It's common for the shift/rotate's read/write register to be
  10449. initialised in between, so under -O2 and under, search ahead
  10450. one more instruction
  10451. }
  10452. GetNextInstruction(hp1, hp1) and
  10453. (hp1.typ = ait_instruction) and
  10454. RegInInstruction(NR_ECX, hp1)
  10455. )
  10456. ) and
  10457. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10458. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10459. begin
  10460. TransferUsedRegs(TmpUsedRegs);
  10461. hp2 := p;
  10462. repeat
  10463. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10464. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10465. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10466. begin
  10467. case taicpu(p).opsize of
  10468. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10469. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10470. begin
  10471. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10472. RemoveCurrentP(p);
  10473. end
  10474. else
  10475. begin
  10476. taicpu(p).opcode := A_MOV;
  10477. taicpu(p).opsize := S_B;
  10478. taicpu(p).oper[1]^.reg := NR_CL;
  10479. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10480. end;
  10481. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10482. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10483. begin
  10484. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10485. RemoveCurrentP(p);
  10486. end
  10487. else
  10488. begin
  10489. taicpu(p).opcode := A_MOV;
  10490. taicpu(p).opsize := S_W;
  10491. taicpu(p).oper[1]^.reg := NR_CX;
  10492. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10493. end;
  10494. {$ifdef x86_64}
  10495. S_LQ:
  10496. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10497. begin
  10498. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10499. RemoveCurrentP(p);
  10500. end
  10501. else
  10502. begin
  10503. taicpu(p).opcode := A_MOV;
  10504. taicpu(p).opsize := S_L;
  10505. taicpu(p).oper[1]^.reg := NR_ECX;
  10506. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10507. end;
  10508. {$endif x86_64}
  10509. else
  10510. InternalError(2021120401);
  10511. end;
  10512. Result := True;
  10513. Exit;
  10514. end;
  10515. end;
  10516. { This is anything but quick! }
  10517. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10518. Exit;
  10519. SetLength(InstrList, 0);
  10520. InstrMax := -1;
  10521. case taicpu(p).opsize of
  10522. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10523. begin
  10524. {$if defined(i386) or defined(i8086)}
  10525. { If the target size is 8-bit, make sure we can actually encode it }
  10526. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10527. Exit;
  10528. {$endif i386 or i8086}
  10529. LowerLimit := $FF;
  10530. SignedLowerLimit := $7F;
  10531. SignedLowerLimitBottom := -128;
  10532. MinSize := S_B;
  10533. if taicpu(p).opsize = S_BW then
  10534. begin
  10535. MaxSize := S_W;
  10536. UpperLimit := $FFFF;
  10537. SignedUpperLimit := $7FFF;
  10538. SignedUpperLimitBottom := -32768;
  10539. end
  10540. else
  10541. begin
  10542. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10543. MaxSize := S_L;
  10544. UpperLimit := $FFFFFFFF;
  10545. SignedUpperLimit := $7FFFFFFF;
  10546. SignedUpperLimitBottom := -2147483648;
  10547. end;
  10548. end;
  10549. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10550. begin
  10551. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10552. LowerLimit := $FFFF;
  10553. SignedLowerLimit := $7FFF;
  10554. SignedLowerLimitBottom := -32768;
  10555. UpperLimit := $FFFFFFFF;
  10556. SignedUpperLimit := $7FFFFFFF;
  10557. SignedUpperLimitBottom := -2147483648;
  10558. MinSize := S_W;
  10559. MaxSize := S_L;
  10560. end;
  10561. {$ifdef x86_64}
  10562. S_LQ:
  10563. begin
  10564. { Both the lower and upper limits are set to 32-bit. If a limit
  10565. is breached, then optimisation is impossible }
  10566. LowerLimit := $FFFFFFFF;
  10567. SignedLowerLimit := $7FFFFFFF;
  10568. SignedLowerLimitBottom := -2147483648;
  10569. UpperLimit := $FFFFFFFF;
  10570. SignedUpperLimit := $7FFFFFFF;
  10571. SignedUpperLimitBottom := -2147483648;
  10572. MinSize := S_L;
  10573. MaxSize := S_L;
  10574. end;
  10575. {$endif x86_64}
  10576. else
  10577. InternalError(2020112301);
  10578. end;
  10579. TestValMin := 0;
  10580. TestValMax := LowerLimit;
  10581. TestValSignedMax := SignedLowerLimit;
  10582. TryShiftDownLimit := LowerLimit;
  10583. TryShiftDown := S_NO;
  10584. ShiftDownOverflow := False;
  10585. RegChanged := False;
  10586. BitwiseOnly := True;
  10587. OrXorUsed := False;
  10588. UpperSignedOverflow := False;
  10589. LowerSignedOverflow := False;
  10590. UpperUnsignedOverflow := False;
  10591. LowerUnsignedOverflow := False;
  10592. hp1 := p;
  10593. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10594. (hp1.typ = ait_instruction) and
  10595. (
  10596. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10597. instruction that doesn't actually contain ThisReg }
  10598. (cs_opt_level3 in current_settings.optimizerswitches) or
  10599. { This allows this Movx optimisation to work through the SETcc instructions
  10600. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10601. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10602. skip over these SETcc instructions). }
  10603. (taicpu(hp1).opcode = A_SETcc) or
  10604. RegInInstruction(ThisReg, hp1)
  10605. ) do
  10606. begin
  10607. case taicpu(hp1).opcode of
  10608. A_INC,A_DEC:
  10609. begin
  10610. { Has to be an exact match on the register }
  10611. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10612. Break;
  10613. if taicpu(hp1).opcode = A_INC then
  10614. begin
  10615. Inc(TestValMin);
  10616. Inc(TestValMax);
  10617. Inc(TestValSignedMax);
  10618. end
  10619. else
  10620. begin
  10621. Dec(TestValMin);
  10622. Dec(TestValMax);
  10623. Dec(TestValSignedMax);
  10624. end;
  10625. end;
  10626. A_TEST, A_CMP:
  10627. begin
  10628. if (
  10629. { Too high a risk of non-linear behaviour that breaks DFA
  10630. here, unless it's cmp $0,%reg, which is equivalent to
  10631. test %reg,%reg }
  10632. OrXorUsed and
  10633. (taicpu(hp1).opcode = A_CMP) and
  10634. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10635. ) or
  10636. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10637. { Has to be an exact match on the register }
  10638. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10639. (
  10640. { Permit "test %reg,%reg" }
  10641. (taicpu(hp1).opcode = A_TEST) and
  10642. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10643. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10644. ) or
  10645. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10646. { Make sure the comparison value is not smaller than the
  10647. smallest allowed signed value for the minimum size (e.g.
  10648. -128 for 8-bit) }
  10649. not (
  10650. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10651. { Is it in the negative range? }
  10652. (
  10653. (taicpu(hp1).oper[0]^.val < 0) and
  10654. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10655. )
  10656. ) then
  10657. Break;
  10658. { Check to see if the active register is used afterwards }
  10659. TransferUsedRegs(TmpUsedRegs);
  10660. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10661. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10662. begin
  10663. { Make sure the comparison or any previous instructions
  10664. hasn't pushed the test values outside of the range of
  10665. MinSize }
  10666. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10667. begin
  10668. { Exceeded lower bound but not upper bound }
  10669. Exit;
  10670. end
  10671. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10672. begin
  10673. { Size didn't exceed lower bound }
  10674. TargetSize := MinSize;
  10675. end
  10676. else
  10677. Break;
  10678. case TargetSize of
  10679. S_B:
  10680. TargetSubReg := R_SUBL;
  10681. S_W:
  10682. TargetSubReg := R_SUBW;
  10683. S_L:
  10684. TargetSubReg := R_SUBD;
  10685. else
  10686. InternalError(2021051002);
  10687. end;
  10688. if TargetSize <> MaxSize then
  10689. begin
  10690. { Update the register to its new size }
  10691. setsubreg(ThisReg, TargetSubReg);
  10692. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10693. taicpu(hp1).oper[1]^.reg := ThisReg;
  10694. taicpu(hp1).opsize := TargetSize;
  10695. { Convert the input MOVZX to a MOV if necessary }
  10696. AdjustInitialLoadAndSize;
  10697. if (InstrMax >= 0) then
  10698. begin
  10699. for Index := 0 to InstrMax do
  10700. begin
  10701. { If p_removed is true, then the original MOV/Z was removed
  10702. and removing the AND instruction may not be safe if it
  10703. appears first }
  10704. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10705. InternalError(2020112311);
  10706. if InstrList[Index].oper[0]^.typ = top_reg then
  10707. InstrList[Index].oper[0]^.reg := ThisReg;
  10708. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10709. InstrList[Index].opsize := MinSize;
  10710. end;
  10711. end;
  10712. Result := True;
  10713. end;
  10714. Exit;
  10715. end;
  10716. end;
  10717. A_SETcc:
  10718. begin
  10719. { This allows this Movx optimisation to work through the SETcc instructions
  10720. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10721. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10722. skip over these SETcc instructions). }
  10723. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10724. { Of course, break out if the current register is used }
  10725. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10726. Break
  10727. else
  10728. { We must use Continue so the instruction doesn't get added
  10729. to InstrList }
  10730. Continue;
  10731. end;
  10732. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10733. begin
  10734. if
  10735. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10736. { Has to be an exact match on the register }
  10737. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10738. (
  10739. (
  10740. (taicpu(hp1).oper[0]^.typ = top_const) and
  10741. (
  10742. (
  10743. (taicpu(hp1).opcode = A_SHL) and
  10744. (
  10745. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10746. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10747. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10748. )
  10749. ) or (
  10750. (taicpu(hp1).opcode <> A_SHL) and
  10751. (
  10752. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10753. { Is it in the negative range? }
  10754. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10755. )
  10756. )
  10757. )
  10758. ) or (
  10759. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10760. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10761. )
  10762. ) then
  10763. Break;
  10764. { Only process OR and XOR if there are only bitwise operations,
  10765. since otherwise they can too easily fool the data flow
  10766. analysis (they can cause non-linear behaviour) }
  10767. case taicpu(hp1).opcode of
  10768. A_ADD:
  10769. begin
  10770. if OrXorUsed then
  10771. { Too high a risk of non-linear behaviour that breaks DFA here }
  10772. Break
  10773. else
  10774. BitwiseOnly := False;
  10775. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10776. begin
  10777. TestValMin := TestValMin * 2;
  10778. TestValMax := TestValMax * 2;
  10779. TestValSignedMax := TestValSignedMax * 2;
  10780. end
  10781. else
  10782. begin
  10783. WorkingValue := taicpu(hp1).oper[0]^.val;
  10784. TestValMin := TestValMin + WorkingValue;
  10785. TestValMax := TestValMax + WorkingValue;
  10786. TestValSignedMax := TestValSignedMax + WorkingValue;
  10787. end;
  10788. end;
  10789. A_SUB:
  10790. begin
  10791. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10792. begin
  10793. TestValMin := 0;
  10794. TestValMax := 0;
  10795. TestValSignedMax := 0;
  10796. end
  10797. else
  10798. begin
  10799. if OrXorUsed then
  10800. { Too high a risk of non-linear behaviour that breaks DFA here }
  10801. Break
  10802. else
  10803. BitwiseOnly := False;
  10804. WorkingValue := taicpu(hp1).oper[0]^.val;
  10805. TestValMin := TestValMin - WorkingValue;
  10806. TestValMax := TestValMax - WorkingValue;
  10807. TestValSignedMax := TestValSignedMax - WorkingValue;
  10808. end;
  10809. end;
  10810. A_AND:
  10811. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10812. begin
  10813. { we might be able to go smaller if AND appears first }
  10814. if InstrMax = -1 then
  10815. case MinSize of
  10816. S_B:
  10817. ;
  10818. S_W:
  10819. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10820. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10821. begin
  10822. TryShiftDown := S_B;
  10823. TryShiftDownLimit := $FF;
  10824. end;
  10825. S_L:
  10826. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10827. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10828. begin
  10829. TryShiftDown := S_B;
  10830. TryShiftDownLimit := $FF;
  10831. end
  10832. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10833. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10834. begin
  10835. TryShiftDown := S_W;
  10836. TryShiftDownLimit := $FFFF;
  10837. end;
  10838. else
  10839. InternalError(2020112320);
  10840. end;
  10841. WorkingValue := taicpu(hp1).oper[0]^.val;
  10842. TestValMin := TestValMin and WorkingValue;
  10843. TestValMax := TestValMax and WorkingValue;
  10844. TestValSignedMax := TestValSignedMax and WorkingValue;
  10845. end;
  10846. A_OR:
  10847. begin
  10848. if not BitwiseOnly then
  10849. Break;
  10850. OrXorUsed := True;
  10851. WorkingValue := taicpu(hp1).oper[0]^.val;
  10852. TestValMin := TestValMin or WorkingValue;
  10853. TestValMax := TestValMax or WorkingValue;
  10854. TestValSignedMax := TestValSignedMax or WorkingValue;
  10855. end;
  10856. A_XOR:
  10857. begin
  10858. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10859. begin
  10860. TestValMin := 0;
  10861. TestValMax := 0;
  10862. TestValSignedMax := 0;
  10863. end
  10864. else
  10865. begin
  10866. if not BitwiseOnly then
  10867. Break;
  10868. OrXorUsed := True;
  10869. WorkingValue := taicpu(hp1).oper[0]^.val;
  10870. TestValMin := TestValMin xor WorkingValue;
  10871. TestValMax := TestValMax xor WorkingValue;
  10872. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10873. end;
  10874. end;
  10875. A_SHL:
  10876. begin
  10877. BitwiseOnly := False;
  10878. WorkingValue := taicpu(hp1).oper[0]^.val;
  10879. TestValMin := TestValMin shl WorkingValue;
  10880. TestValMax := TestValMax shl WorkingValue;
  10881. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10882. end;
  10883. A_SHR,
  10884. { The first instruction was MOVZX, so the value won't be negative }
  10885. A_SAR:
  10886. begin
  10887. if InstrMax <> -1 then
  10888. BitwiseOnly := False
  10889. else
  10890. { we might be able to go smaller if SHR appears first }
  10891. case MinSize of
  10892. S_B:
  10893. ;
  10894. S_W:
  10895. if (taicpu(hp1).oper[0]^.val >= 8) then
  10896. begin
  10897. TryShiftDown := S_B;
  10898. TryShiftDownLimit := $FF;
  10899. TryShiftDownSignedLimit := $7F;
  10900. TryShiftDownSignedLimitLower := -128;
  10901. end;
  10902. S_L:
  10903. if (taicpu(hp1).oper[0]^.val >= 24) then
  10904. begin
  10905. TryShiftDown := S_B;
  10906. TryShiftDownLimit := $FF;
  10907. TryShiftDownSignedLimit := $7F;
  10908. TryShiftDownSignedLimitLower := -128;
  10909. end
  10910. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10911. begin
  10912. TryShiftDown := S_W;
  10913. TryShiftDownLimit := $FFFF;
  10914. TryShiftDownSignedLimit := $7FFF;
  10915. TryShiftDownSignedLimitLower := -32768;
  10916. end;
  10917. else
  10918. InternalError(2020112321);
  10919. end;
  10920. WorkingValue := taicpu(hp1).oper[0]^.val;
  10921. if taicpu(hp1).opcode = A_SAR then
  10922. begin
  10923. TestValMin := SarInt64(TestValMin, WorkingValue);
  10924. TestValMax := SarInt64(TestValMax, WorkingValue);
  10925. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10926. end
  10927. else
  10928. begin
  10929. TestValMin := TestValMin shr WorkingValue;
  10930. TestValMax := TestValMax shr WorkingValue;
  10931. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10932. end;
  10933. end;
  10934. else
  10935. InternalError(2020112303);
  10936. end;
  10937. end;
  10938. (*
  10939. A_IMUL:
  10940. case taicpu(hp1).ops of
  10941. 2:
  10942. begin
  10943. if not MatchOpType(hp1, top_reg, top_reg) or
  10944. { Has to be an exact match on the register }
  10945. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10946. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10947. Break;
  10948. TestValMin := TestValMin * TestValMin;
  10949. TestValMax := TestValMax * TestValMax;
  10950. TestValSignedMax := TestValSignedMax * TestValMax;
  10951. end;
  10952. 3:
  10953. begin
  10954. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10955. { Has to be an exact match on the register }
  10956. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10957. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10958. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10959. { Is it in the negative range? }
  10960. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10961. Break;
  10962. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10963. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10964. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10965. end;
  10966. else
  10967. Break;
  10968. end;
  10969. A_IDIV:
  10970. case taicpu(hp1).ops of
  10971. 3:
  10972. begin
  10973. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10974. { Has to be an exact match on the register }
  10975. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10976. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10977. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10978. { Is it in the negative range? }
  10979. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10980. Break;
  10981. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10982. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10983. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10984. end;
  10985. else
  10986. Break;
  10987. end;
  10988. *)
  10989. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10990. begin
  10991. { If there are no instructions in between, then we might be able to make a saving }
  10992. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10993. Break;
  10994. { We have something like:
  10995. movzbw %dl,%dx
  10996. ...
  10997. movswl %dx,%edx
  10998. Change the latter to a zero-extension then enter the
  10999. A_MOVZX case branch.
  11000. }
  11001. {$ifdef x86_64}
  11002. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11003. begin
  11004. { this becomes a zero extension from 32-bit to 64-bit, but
  11005. the upper 32 bits are already zero, so just delete the
  11006. instruction }
  11007. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  11008. RemoveInstruction(hp1);
  11009. Result := True;
  11010. Exit;
  11011. end
  11012. else
  11013. {$endif x86_64}
  11014. begin
  11015. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  11016. taicpu(hp1).opcode := A_MOVZX;
  11017. {$ifdef x86_64}
  11018. case taicpu(hp1).opsize of
  11019. S_BQ:
  11020. begin
  11021. taicpu(hp1).opsize := S_BL;
  11022. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11023. end;
  11024. S_WQ:
  11025. begin
  11026. taicpu(hp1).opsize := S_WL;
  11027. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11028. end;
  11029. S_LQ:
  11030. begin
  11031. taicpu(hp1).opcode := A_MOV;
  11032. taicpu(hp1).opsize := S_L;
  11033. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11034. { In this instance, we need to break out because the
  11035. instruction is no longer MOVZX or MOVSXD }
  11036. Result := True;
  11037. Exit;
  11038. end;
  11039. else
  11040. ;
  11041. end;
  11042. {$endif x86_64}
  11043. Result := CompressInstructions;
  11044. Exit;
  11045. end;
  11046. end;
  11047. A_MOVZX:
  11048. begin
  11049. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  11050. Break;
  11051. if (InstrMax = -1) then
  11052. begin
  11053. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  11054. begin
  11055. { Optimise around i40003 }
  11056. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  11057. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  11058. {$ifndef x86_64}
  11059. and (
  11060. (taicpu(p).oper[0]^.typ <> top_reg) or
  11061. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  11062. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  11063. )
  11064. {$endif not x86_64}
  11065. then
  11066. begin
  11067. if (taicpu(p).oper[0]^.typ = top_reg) then
  11068. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  11069. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  11070. taicpu(p).opsize := S_BL;
  11071. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  11072. RemoveInstruction(hp1);
  11073. Result := True;
  11074. Exit;
  11075. end;
  11076. end
  11077. else
  11078. begin
  11079. { Will return false if the second parameter isn't ThisReg
  11080. (can happen on -O2 and under) }
  11081. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11082. begin
  11083. { The two MOVZX instructions are adjacent, so remove the first one }
  11084. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  11085. RemoveCurrentP(p);
  11086. Result := True;
  11087. Exit;
  11088. end;
  11089. Break;
  11090. end;
  11091. end;
  11092. Result := CompressInstructions;
  11093. Exit;
  11094. end;
  11095. else
  11096. { This includes ADC, SBB and IDIV }
  11097. Break;
  11098. end;
  11099. if not CheckOverflowConditions then
  11100. Break;
  11101. { Contains highest index (so instruction count - 1) }
  11102. Inc(InstrMax);
  11103. if InstrMax > High(InstrList) then
  11104. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11105. InstrList[InstrMax] := taicpu(hp1);
  11106. end;
  11107. end;
  11108. {$pop}
  11109. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  11110. var
  11111. hp1 : tai;
  11112. begin
  11113. Result:=false;
  11114. if (taicpu(p).ops >= 2) and
  11115. ((taicpu(p).oper[0]^.typ = top_const) or
  11116. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  11117. (taicpu(p).oper[1]^.typ = top_reg) and
  11118. ((taicpu(p).ops = 2) or
  11119. ((taicpu(p).oper[2]^.typ = top_reg) and
  11120. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  11121. GetLastInstruction(p,hp1) and
  11122. MatchInstruction(hp1,A_MOV,[]) and
  11123. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11124. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11125. begin
  11126. TransferUsedRegs(TmpUsedRegs);
  11127. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  11128. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  11129. { change
  11130. mov reg1,reg2
  11131. imul y,reg2 to imul y,reg1,reg2 }
  11132. begin
  11133. taicpu(p).ops := 3;
  11134. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  11135. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  11136. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  11137. RemoveInstruction(hp1);
  11138. result:=true;
  11139. end;
  11140. end;
  11141. end;
  11142. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  11143. var
  11144. ThisLabel: TAsmLabel;
  11145. begin
  11146. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  11147. ThisLabel.decrefs;
  11148. taicpu(p).condition := C_None;
  11149. taicpu(p).opcode := A_RET;
  11150. taicpu(p).is_jmp := false;
  11151. taicpu(p).ops := taicpu(ret_p).ops;
  11152. case taicpu(ret_p).ops of
  11153. 0:
  11154. taicpu(p).clearop(0);
  11155. 1:
  11156. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  11157. else
  11158. internalerror(2016041301);
  11159. end;
  11160. { If the original label is now dead, it might turn out that the label
  11161. immediately follows p. As a result, everything beyond it, which will
  11162. be just some final register configuration and a RET instruction, is
  11163. now dead code. [Kit] }
  11164. { NOTE: This is much faster than introducing a OptPass2RET routine and
  11165. running RemoveDeadCodeAfterJump for each RET instruction, because
  11166. this optimisation rarely happens and most RETs appear at the end of
  11167. routines where there is nothing that can be stripped. [Kit] }
  11168. if not ThisLabel.is_used then
  11169. RemoveDeadCodeAfterJump(p);
  11170. end;
  11171. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  11172. var
  11173. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  11174. Unconditional, PotentialModified: Boolean;
  11175. OperPtr: POper;
  11176. NewRef: TReference;
  11177. InstrList: array of taicpu;
  11178. InstrMax, Index: Integer;
  11179. const
  11180. {$ifdef DEBUG_AOPTCPU}
  11181. SNoFlags: shortstring = ' so the flags aren''t modified';
  11182. {$else DEBUG_AOPTCPU}
  11183. SNoFlags = '';
  11184. {$endif DEBUG_AOPTCPU}
  11185. begin
  11186. Result:=false;
  11187. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  11188. begin
  11189. if MatchInstruction(hp1, A_TEST, [S_B]) and
  11190. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11191. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11192. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11193. GetNextInstruction(hp1, hp2) and
  11194. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  11195. { Change from: To:
  11196. set(C) %reg j(~C) label
  11197. test %reg,%reg/cmp $0,%reg
  11198. je label
  11199. set(C) %reg j(C) label
  11200. test %reg,%reg/cmp $0,%reg
  11201. jne label
  11202. (Also do something similar with sete/setne instead of je/jne)
  11203. }
  11204. begin
  11205. { Before we do anything else, we need to check the instructions
  11206. in between SETcc and TEST to make sure they don't modify the
  11207. FLAGS register - if -O2 or under, there won't be any
  11208. instructions between SET and TEST }
  11209. TransferUsedRegs(TmpUsedRegs);
  11210. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11211. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11212. begin
  11213. next := p;
  11214. SetLength(InstrList, 0);
  11215. InstrMax := -1;
  11216. PotentialModified := False;
  11217. { Make a note of every instruction that modifies the FLAGS
  11218. register }
  11219. while GetNextInstruction(next, next) and (next <> hp1) do
  11220. begin
  11221. if next.typ <> ait_instruction then
  11222. { GetNextInstructionUsingReg should have returned False }
  11223. InternalError(2021051701);
  11224. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11225. begin
  11226. case taicpu(next).opcode of
  11227. A_SETcc,
  11228. A_CMOVcc,
  11229. A_Jcc:
  11230. begin
  11231. if PotentialModified then
  11232. { Not safe because the flags were modified earlier }
  11233. Exit
  11234. else
  11235. { Condition is the same as the initial SETcc, so this is safe
  11236. (don't add to instruction list though) }
  11237. Continue;
  11238. end;
  11239. A_ADD:
  11240. begin
  11241. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11242. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11243. (taicpu(next).oper[1]^.typ <> top_reg) or
  11244. { Must write to a register }
  11245. (taicpu(next).oper[0]^.typ = top_ref) then
  11246. { Require a constant or a register }
  11247. Exit;
  11248. PotentialModified := True;
  11249. end;
  11250. A_SUB:
  11251. begin
  11252. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11253. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11254. (taicpu(next).oper[1]^.typ <> top_reg) or
  11255. { Must write to a register }
  11256. (taicpu(next).oper[0]^.typ <> top_const) or
  11257. (taicpu(next).oper[0]^.val = $80000000) then
  11258. { Can't subtract a register with LEA - also
  11259. check that the value isn't -2^31, as this
  11260. can't be negated }
  11261. Exit;
  11262. PotentialModified := True;
  11263. end;
  11264. A_SAL,
  11265. A_SHL:
  11266. begin
  11267. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11268. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11269. (taicpu(next).oper[1]^.typ <> top_reg) or
  11270. { Must write to a register }
  11271. (taicpu(next).oper[0]^.typ <> top_const) or
  11272. (taicpu(next).oper[0]^.val < 0) or
  11273. (taicpu(next).oper[0]^.val > 3) then
  11274. Exit;
  11275. PotentialModified := True;
  11276. end;
  11277. A_IMUL:
  11278. begin
  11279. if (taicpu(next).ops <> 3) or
  11280. (taicpu(next).oper[1]^.typ <> top_reg) or
  11281. { Must write to a register }
  11282. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11283. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11284. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11285. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11286. Exit
  11287. else
  11288. PotentialModified := True;
  11289. end;
  11290. else
  11291. { Don't know how to change this, so abort }
  11292. Exit;
  11293. end;
  11294. { Contains highest index (so instruction count - 1) }
  11295. Inc(InstrMax);
  11296. if InstrMax > High(InstrList) then
  11297. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11298. InstrList[InstrMax] := taicpu(next);
  11299. end;
  11300. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11301. end;
  11302. if not Assigned(next) or (next <> hp1) then
  11303. { It should be equal to hp1 }
  11304. InternalError(2021051702);
  11305. { Cycle through each instruction and check to see if we can
  11306. change them to versions that don't modify the flags }
  11307. if (InstrMax >= 0) then
  11308. begin
  11309. for Index := 0 to InstrMax do
  11310. case InstrList[Index].opcode of
  11311. A_ADD:
  11312. begin
  11313. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11314. InstrList[Index].opcode := A_LEA;
  11315. reference_reset(NewRef, 1, []);
  11316. NewRef.base := InstrList[Index].oper[1]^.reg;
  11317. if InstrList[Index].oper[0]^.typ = top_reg then
  11318. begin
  11319. NewRef.index := InstrList[Index].oper[0]^.reg;
  11320. NewRef.scalefactor := 1;
  11321. end
  11322. else
  11323. NewRef.offset := InstrList[Index].oper[0]^.val;
  11324. InstrList[Index].loadref(0, NewRef);
  11325. end;
  11326. A_SUB:
  11327. begin
  11328. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11329. InstrList[Index].opcode := A_LEA;
  11330. reference_reset(NewRef, 1, []);
  11331. NewRef.base := InstrList[Index].oper[1]^.reg;
  11332. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11333. InstrList[Index].loadref(0, NewRef);
  11334. end;
  11335. A_SHL,
  11336. A_SAL:
  11337. begin
  11338. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11339. InstrList[Index].opcode := A_LEA;
  11340. reference_reset(NewRef, 1, []);
  11341. NewRef.index := InstrList[Index].oper[1]^.reg;
  11342. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11343. InstrList[Index].loadref(0, NewRef);
  11344. end;
  11345. A_IMUL:
  11346. begin
  11347. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11348. InstrList[Index].opcode := A_LEA;
  11349. reference_reset(NewRef, 1, []);
  11350. NewRef.index := InstrList[Index].oper[1]^.reg;
  11351. case InstrList[Index].oper[0]^.val of
  11352. 2, 4, 8:
  11353. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11354. else {3, 5 and 9}
  11355. begin
  11356. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11357. NewRef.base := InstrList[Index].oper[1]^.reg;
  11358. end;
  11359. end;
  11360. InstrList[Index].loadref(0, NewRef);
  11361. end;
  11362. else
  11363. InternalError(2021051710);
  11364. end;
  11365. end;
  11366. { Mark the FLAGS register as used across this whole block }
  11367. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11368. end;
  11369. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11370. JumpC := taicpu(hp2).condition;
  11371. Unconditional := False;
  11372. if conditions_equal(JumpC, C_E) then
  11373. SetC := inverse_cond(taicpu(p).condition)
  11374. else if conditions_equal(JumpC, C_NE) then
  11375. SetC := taicpu(p).condition
  11376. else
  11377. { We've got something weird here (and inefficent) }
  11378. begin
  11379. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11380. SetC := C_NONE;
  11381. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11382. if condition_in(C_AE, JumpC) then
  11383. Unconditional := True
  11384. else
  11385. { Not sure what to do with this jump - drop out }
  11386. Exit;
  11387. end;
  11388. RemoveInstruction(hp1);
  11389. if Unconditional then
  11390. MakeUnconditional(taicpu(hp2))
  11391. else
  11392. begin
  11393. if SetC = C_NONE then
  11394. InternalError(2018061402);
  11395. taicpu(hp2).SetCondition(SetC);
  11396. end;
  11397. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11398. TmpUsedRegs }
  11399. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11400. begin
  11401. RemoveCurrentp(p, hp2);
  11402. if taicpu(hp2).opcode = A_SETcc then
  11403. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11404. else
  11405. begin
  11406. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11407. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11408. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11409. end;
  11410. end
  11411. else
  11412. if taicpu(hp2).opcode = A_SETcc then
  11413. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11414. else
  11415. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11416. Result := True;
  11417. end
  11418. else if
  11419. { Make sure the instructions are adjacent }
  11420. (
  11421. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11422. GetNextInstruction(p, hp1)
  11423. ) and
  11424. MatchInstruction(hp1, A_MOV, [S_B]) and
  11425. { Writing to memory is allowed }
  11426. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11427. begin
  11428. {
  11429. Watch out for sequences such as:
  11430. set(c)b %regb
  11431. movb %regb,(ref)
  11432. movb $0,1(ref)
  11433. movb $0,2(ref)
  11434. movb $0,3(ref)
  11435. Much more efficient to turn it into:
  11436. movl $0,%regl
  11437. set(c)b %regb
  11438. movl %regl,(ref)
  11439. Or:
  11440. set(c)b %regb
  11441. movzbl %regb,%regl
  11442. movl %regl,(ref)
  11443. }
  11444. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11445. GetNextInstruction(hp1, hp2) and
  11446. MatchInstruction(hp2, A_MOV, [S_B]) and
  11447. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11448. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11449. begin
  11450. { Don't do anything else except set Result to True }
  11451. end
  11452. else
  11453. begin
  11454. if taicpu(p).oper[0]^.typ = top_reg then
  11455. begin
  11456. TransferUsedRegs(TmpUsedRegs);
  11457. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11458. end;
  11459. { If it's not a register, it's a memory address }
  11460. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11461. begin
  11462. { Even if the register is still in use, we can minimise the
  11463. pipeline stall by changing the MOV into another SETcc. }
  11464. taicpu(hp1).opcode := A_SETcc;
  11465. taicpu(hp1).condition := taicpu(p).condition;
  11466. if taicpu(hp1).oper[1]^.typ = top_ref then
  11467. begin
  11468. { Swapping the operand pointers like this is probably a
  11469. bit naughty, but it is far faster than using loadoper
  11470. to transfer the reference from oper[1] to oper[0] if
  11471. you take into account the extra procedure calls and
  11472. the memory allocation and deallocation required }
  11473. OperPtr := taicpu(hp1).oper[1];
  11474. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11475. taicpu(hp1).oper[0] := OperPtr;
  11476. end
  11477. else
  11478. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11479. taicpu(hp1).clearop(1);
  11480. taicpu(hp1).ops := 1;
  11481. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11482. end
  11483. else
  11484. begin
  11485. if taicpu(hp1).oper[1]^.typ = top_reg then
  11486. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11487. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11488. RemoveInstruction(hp1);
  11489. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11490. end
  11491. end;
  11492. Result := True;
  11493. end;
  11494. end;
  11495. end;
  11496. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11497. var
  11498. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11499. TargetReg: TRegister;
  11500. condition, inverted_condition: TAsmCond;
  11501. FoundMOV: Boolean;
  11502. begin
  11503. Result := False;
  11504. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11505. create the most optimial instructions possible due to limited
  11506. register availability, and there are situations where two
  11507. complementary "simple" CMOV blocks are created which, after the fact
  11508. can be merged into a "double" block. For example:
  11509. movw $257,%ax
  11510. movw $2,%r8w
  11511. xorl r9d,%r9d
  11512. testw $16,18(%rcx)
  11513. cmovew %ax,%dx
  11514. cmovew %r8w,%bx
  11515. cmovel %r9d,%r14d
  11516. movw $1283,%ax
  11517. movw $4,%r8w
  11518. movl $9,%r9d
  11519. cmovnew %ax,%dx
  11520. cmovnew %r8w,%bx
  11521. cmovnel %r9d,%r14d
  11522. The CMOVNE instructions at the end can be removed, and the
  11523. destination registers copied into the MOV instructions directly
  11524. above them, before finally being moved to before the first CMOVE
  11525. instructions, to produce:
  11526. movw $257,%ax
  11527. movw $2,%r8w
  11528. xorl r9d,%r9d
  11529. testw $16,18(%rcx)
  11530. movw $1283,%dx
  11531. movw $4,%bx
  11532. movl $9,%r14d
  11533. cmovew %ax,%dx
  11534. cmovew %r8w,%bx
  11535. cmovel %r9d,%r14d
  11536. Which can then be later optimised to:
  11537. movw $257,%ax
  11538. movw $2,%r8w
  11539. xorl r9d,%r9d
  11540. movw $1283,%dx
  11541. movw $4,%bx
  11542. movl $9,%r14d
  11543. testw $16,18(%rcx)
  11544. cmovew %ax,%dx
  11545. cmovew %r8w,%bx
  11546. cmovel %r9d,%r14d
  11547. }
  11548. TargetReg := taicpu(hp1).oper[1]^.reg;
  11549. condition := taicpu(hp1).condition;
  11550. inverted_condition := inverse_cond(condition);
  11551. pFirstMov := nil;
  11552. pLastMov := nil;
  11553. pCMOV := nil;
  11554. if (p.typ = ait_instruction) then
  11555. pCond := p
  11556. else if not GetNextInstruction(p, pCond) then
  11557. InternalError(2024012501);
  11558. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11559. { We should get the CMP or TEST instructeion }
  11560. InternalError(2024012502);
  11561. if (
  11562. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11563. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11564. ) then
  11565. begin
  11566. { We have to tread carefully here, hence why we're not using
  11567. GetNextInstructionUsingReg... we can only accept MOV and other
  11568. CMOV instructions. Anything else and we must drop out}
  11569. hp2 := hp1;
  11570. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11571. begin
  11572. if (hp2.typ <> ait_instruction) then
  11573. Exit;
  11574. case taicpu(hp2).opcode of
  11575. A_MOV:
  11576. begin
  11577. if not Assigned(pFirstMov) then
  11578. pFirstMov := hp2;
  11579. pLastMOV := hp2;
  11580. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11581. { Something different - drop out }
  11582. Exit;
  11583. { Otherwise, leave it for now }
  11584. end;
  11585. A_CMOVcc:
  11586. begin
  11587. if taicpu(hp2).condition = inverted_condition then
  11588. begin
  11589. { We found what we're looking for }
  11590. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11591. begin
  11592. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11593. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11594. begin
  11595. pCMOV := hp2;
  11596. Break;
  11597. end
  11598. else
  11599. { Unsafe reference - drop out }
  11600. Exit;
  11601. end;
  11602. end
  11603. else if taicpu(hp2).condition <> condition then
  11604. { Something weird - drop out }
  11605. Exit;
  11606. end;
  11607. else
  11608. { Invalid }
  11609. Exit;
  11610. end;
  11611. end;
  11612. if not Assigned(pCMOV) then
  11613. { No complementary CMOV found }
  11614. Exit;
  11615. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11616. begin
  11617. { Don't need to do anything special or search for a matching MOV }
  11618. Asml.Remove(pCMOV);
  11619. if RegInInstruction(TargetReg, pCond) then
  11620. { Make sure we don't overwrite the register if it's being used in the condition }
  11621. Asml.InsertAfter(pCMOV, pCond)
  11622. else
  11623. Asml.InsertBefore(pCMOV, pCond);
  11624. taicpu(pCMOV).opcode := A_MOV;
  11625. taicpu(pCMOV).condition := C_None;
  11626. { Don't need to worry about allocating new registers in these cases }
  11627. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11628. Result := True;
  11629. Exit;
  11630. end
  11631. else
  11632. begin
  11633. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11634. FoundMOV := False;
  11635. { Search for the MOV that sets the target register }
  11636. hp2 := pFirstMov;
  11637. repeat
  11638. if (taicpu(hp2).opcode = A_MOV) and
  11639. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11640. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11641. begin
  11642. { Change the destination }
  11643. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11644. if not FoundMOV then
  11645. begin
  11646. FoundMOV := True;
  11647. { Make sure the register is allocated }
  11648. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11649. end;
  11650. hp1 := tai(hp2.Previous);
  11651. Asml.Remove(hp2);
  11652. if RegInInstruction(TargetReg, pCond) then
  11653. { Make sure we don't overwrite the register if it's being used in the condition }
  11654. Asml.InsertAfter(hp2, pCond)
  11655. else
  11656. Asml.InsertBefore(hp2, pCond);
  11657. if (hp2 = pLastMov) then
  11658. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11659. Break;
  11660. hp2 := hp1;
  11661. end;
  11662. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11663. if FoundMOV then
  11664. { Delete the CMOV }
  11665. RemoveInstruction(pCMOV)
  11666. else
  11667. begin
  11668. { If no MOV was found, we have to actually move and transmute the CMOV }
  11669. Asml.Remove(pCMOV);
  11670. if RegInInstruction(TargetReg, pCond) then
  11671. { Make sure we don't overwrite the register if it's being used in the condition }
  11672. Asml.InsertAfter(pCMOV, pCond)
  11673. else
  11674. Asml.InsertBefore(pCMOV, pCond);
  11675. taicpu(pCMOV).opcode := A_MOV;
  11676. taicpu(pCMOV).condition := C_None;
  11677. end;
  11678. Result := True;
  11679. Exit;
  11680. end;
  11681. end;
  11682. end;
  11683. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11684. var
  11685. hp1, hp2, pCond: tai;
  11686. begin
  11687. Result := False;
  11688. { Search ahead for CMOV instructions }
  11689. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11690. begin
  11691. hp1 := p;
  11692. hp2 := p;
  11693. pCond := nil; { To prevent compiler warnings }
  11694. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11695. DEFAULTFLAGS }
  11696. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11697. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11698. pCond := p;
  11699. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11700. begin
  11701. if (hp1.typ <> ait_instruction) then
  11702. { Break out on markers and labels etc. }
  11703. Break;
  11704. case taicpu(hp1).opcode of
  11705. A_MOV:
  11706. { Ignore regular MOVs unless they are obviously not related
  11707. to a CMOV block }
  11708. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11709. Break;
  11710. A_CMOVcc:
  11711. if TryCmpCMovOpts(pCond, hp1) then
  11712. begin
  11713. hp1 := hp2;
  11714. { p itself isn't changed, and we're still inside a
  11715. while loop to catch subsequent CMOVs, so just flag
  11716. a new iteration }
  11717. Include(OptsToCheck, aoc_ForceNewIteration);
  11718. Continue;
  11719. end;
  11720. else
  11721. { Drop out if we find anything else }
  11722. Break;
  11723. end;
  11724. hp2 := hp1;
  11725. end;
  11726. end;
  11727. end;
  11728. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11729. var
  11730. hp1, hp2, pCond: tai;
  11731. SourceReg, TargetReg: TRegister;
  11732. begin
  11733. Result := False;
  11734. { In some situations, we end up with an inefficient arrangement of
  11735. instructions in the form of:
  11736. or %reg1,%reg2
  11737. (%reg1 deallocated)
  11738. test %reg2,%reg2
  11739. mov x,%reg2
  11740. we may be able to swap and rearrange the registers to produce:
  11741. or %reg2,%reg1
  11742. mov x,%reg2
  11743. test %reg1,%reg1
  11744. (%reg1 deallocated)
  11745. }
  11746. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11747. (taicpu(p).oper[1]^.typ = top_reg) and
  11748. (
  11749. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11750. MatchOperand(taicpu(p).oper[0]^, -1)
  11751. ) and
  11752. GetNextInstruction(p, hp1) and
  11753. MatchInstruction(hp1, A_MOV, []) and
  11754. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11755. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11756. begin
  11757. TargetReg := taicpu(p).oper[1]^.reg;
  11758. { Now look backwards to find a simple commutative operation: ADD,
  11759. IMUL (2-register version), OR, AND or XOR - whose destination
  11760. register is the same as TEST }
  11761. hp2 := p;
  11762. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11763. if RegInInstruction(TargetReg, hp2) then
  11764. begin
  11765. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11766. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11767. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11768. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11769. begin
  11770. SourceReg := taicpu(hp2).oper[0]^.reg;
  11771. if
  11772. { Make sure the MOV doesn't use the other register }
  11773. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11774. { And make sure the source register is not used afterwards }
  11775. not RegInUsedRegs(SourceReg, UsedRegs) then
  11776. begin
  11777. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11778. taicpu(hp2).oper[0]^.reg := TargetReg;
  11779. taicpu(hp2).oper[1]^.reg := SourceReg;
  11780. if taicpu(p).oper[0]^.typ = top_reg then
  11781. taicpu(p).oper[0]^.reg := SourceReg;
  11782. taicpu(p).oper[1]^.reg := SourceReg;
  11783. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11784. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11785. Include(OptsToCheck, aoc_ForceNewIteration);
  11786. { We can still check the following optimisations since
  11787. the instruction is still a TEST }
  11788. end;
  11789. end;
  11790. Break;
  11791. end;
  11792. end;
  11793. { Search ahead3 for CMOV instructions }
  11794. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11795. begin
  11796. hp1 := p;
  11797. hp2 := p;
  11798. pCond := nil; { To prevent compiler warnings }
  11799. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11800. DEFAULTFLAGS }
  11801. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11802. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11803. pCond := p;
  11804. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11805. begin
  11806. if (hp1.typ <> ait_instruction) then
  11807. { Break out on markers and labels etc. }
  11808. Break;
  11809. case taicpu(hp1).opcode of
  11810. A_MOV:
  11811. { Ignore regular MOVs unless they are obviously not related
  11812. to a CMOV block }
  11813. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11814. Break;
  11815. A_CMOVcc:
  11816. if TryCmpCMovOpts(pCond, hp1) then
  11817. begin
  11818. hp1 := hp2;
  11819. { p itself isn't changed, and we're still inside a
  11820. while loop to catch subsequent CMOVs, so just flag
  11821. a new iteration }
  11822. Include(OptsToCheck, aoc_ForceNewIteration);
  11823. Continue;
  11824. end;
  11825. else
  11826. { Drop out if we find anything else }
  11827. Break;
  11828. end;
  11829. hp2 := hp1;
  11830. end;
  11831. end;
  11832. end;
  11833. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11834. var
  11835. hp1: tai;
  11836. Count: Integer;
  11837. OrigLabel: TAsmLabel;
  11838. begin
  11839. result := False;
  11840. { Sometimes, the optimisations below can permit this }
  11841. RemoveDeadCodeAfterJump(p);
  11842. 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
  11843. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11844. begin
  11845. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11846. { Also a side-effect of optimisations }
  11847. if CollapseZeroDistJump(p, OrigLabel) then
  11848. begin
  11849. Result := True;
  11850. Exit;
  11851. end;
  11852. hp1 := GetLabelWithSym(OrigLabel);
  11853. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11854. begin
  11855. if taicpu(hp1).opcode = A_RET then
  11856. begin
  11857. {
  11858. change
  11859. jmp .L1
  11860. ...
  11861. .L1:
  11862. ret
  11863. into
  11864. ret
  11865. }
  11866. begin
  11867. ConvertJumpToRET(p, hp1);
  11868. result:=true;
  11869. end;
  11870. end
  11871. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11872. not (cs_opt_size in current_settings.optimizerswitches) and
  11873. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11874. begin
  11875. Result := True;
  11876. Exit;
  11877. end;
  11878. end;
  11879. end;
  11880. end;
  11881. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11882. begin
  11883. Result := assigned(p) and
  11884. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11885. (taicpu(p).oper[1]^.typ = top_reg) and
  11886. (
  11887. (taicpu(p).oper[0]^.typ = top_reg) or
  11888. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11889. it is not expected that this can cause a seg. violation }
  11890. (
  11891. (taicpu(p).oper[0]^.typ = top_ref) and
  11892. { TODO: Can we detect which references become constants at this
  11893. stage so we don't have to do a blanket ban? }
  11894. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11895. (
  11896. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11897. (
  11898. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11899. not RefModified and
  11900. { If the reference also appears in the condition, then we know it's safe, otherwise
  11901. any kind of access violation would have occurred already }
  11902. Assigned(cond_p) and
  11903. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11904. (cond_p.typ = ait_instruction) and
  11905. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11906. { Just consider 2-operand comparison instructions for now to be safe }
  11907. (taicpu(cond_p).ops = 2) and
  11908. (
  11909. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11910. (
  11911. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11912. { Don't risk identical registers but different offsets, as we may have constructs
  11913. such as buffer streams with things like length fields that indicate whether
  11914. any more data follows. And there are probably some contrived examples where
  11915. writing to offsets behind the one being read also lead to access violations }
  11916. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11917. (
  11918. { Check that we're not modifying a register that appears in the reference }
  11919. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11920. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11921. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11922. )
  11923. )
  11924. )
  11925. )
  11926. )
  11927. )
  11928. );
  11929. end;
  11930. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11931. begin
  11932. { Update integer registers, ignoring deallocations }
  11933. repeat
  11934. while assigned(p) and
  11935. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11936. (p.typ = ait_label) or
  11937. ((p.typ = ait_marker) and
  11938. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11939. p := tai(p.next);
  11940. while assigned(p) and
  11941. (p.typ=ait_RegAlloc) Do
  11942. begin
  11943. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11944. begin
  11945. case tai_regalloc(p).ratype of
  11946. ra_alloc :
  11947. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11948. else
  11949. ;
  11950. end;
  11951. end;
  11952. p := tai(p.next);
  11953. end;
  11954. until not(assigned(p)) or
  11955. (not(p.typ in SkipInstr) and
  11956. not((p.typ = ait_label) and
  11957. labelCanBeSkipped(tai_label(p))));
  11958. end;
  11959. {$ifndef 8086}
  11960. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11961. begin
  11962. Result := False;
  11963. EndJump := nil;
  11964. BlockStop := nil;
  11965. while (BlockStart <> fOptimizer.BlockEnd) and
  11966. { stop on labels }
  11967. (BlockStart.typ <> ait_label) do
  11968. begin
  11969. { Keep track of all integer registers that are used }
  11970. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11971. if BlockStart.typ = ait_instruction then
  11972. begin
  11973. if (taicpu(BlockStart).opcode = A_JMP) then
  11974. begin
  11975. if not IsJumpToLabel(taicpu(BlockStart)) or
  11976. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11977. Exit;
  11978. EndJump := BlockStart;
  11979. Break;
  11980. end
  11981. { Check to see if we have a valid MOV instruction instead }
  11982. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11983. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11984. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11985. begin
  11986. Exit;
  11987. end
  11988. else
  11989. { This will be a valid MOV }
  11990. fAllocationRange := BlockStart;
  11991. end;
  11992. OneBeforeBlock := BlockStart;
  11993. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11994. end;
  11995. if (BlockStart = fOptimizer.BlockEnd) then
  11996. Exit;
  11997. BlockStop := BlockStart;
  11998. Result := True;
  11999. end;
  12000. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  12001. var
  12002. hp1: tai;
  12003. RefModified: Boolean;
  12004. begin
  12005. Result := 0;
  12006. hp1 := BlockStart;
  12007. RefModified := False; { As long as the condition is inverted, this can be reset }
  12008. while assigned(hp1) and
  12009. (hp1 <> BlockStop) do
  12010. begin
  12011. case hp1.typ of
  12012. ait_instruction:
  12013. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12014. begin
  12015. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  12016. begin
  12017. Inc(Result);
  12018. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  12019. Assigned(fCondition) and
  12020. { Will have 2 operands }
  12021. (
  12022. (
  12023. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  12024. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  12025. ) or
  12026. (
  12027. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  12028. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  12029. )
  12030. ) then
  12031. { It is no longer safe to use the reference in the condition.
  12032. this prevents problems such as:
  12033. mov (%reg),%reg
  12034. mov (%reg),...
  12035. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  12036. (fixes #40165)
  12037. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  12038. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  12039. }
  12040. RefModified := True;
  12041. end
  12042. else if not (cs_opt_size in current_settings.optimizerswitches) and
  12043. { CMOV with constants grows the code size }
  12044. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  12045. begin
  12046. { Register was reserved by TryCMOVConst and
  12047. stored on ConstRegs }
  12048. end
  12049. else
  12050. begin
  12051. Result := -1;
  12052. Exit;
  12053. end;
  12054. end
  12055. else
  12056. begin
  12057. Result := -1;
  12058. Exit;
  12059. end;
  12060. else
  12061. { Most likely an align };
  12062. end;
  12063. fOptimizer.GetNextInstruction(hp1, hp1);
  12064. end;
  12065. end;
  12066. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  12067. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  12068. (this is done as a separate stage because the double types are extensions of the branching type,
  12069. but we can't discount the conditional jump until the last step) }
  12070. procedure EvaluateBranchingType;
  12071. begin
  12072. Inc(CMOVScore);
  12073. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  12074. { Too many instructions to be worthwhile }
  12075. fState := tsInvalid;
  12076. end;
  12077. var
  12078. hp1: tai;
  12079. Count: Integer;
  12080. begin
  12081. { Table of valid CMOV block types
  12082. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  12083. ---------- --------- --------- --------- --------- ---------
  12084. tsSimple X Yes X X X
  12085. tsDetour = 1st X X X X
  12086. tsBranching <> Mid Yes X X X
  12087. tsDouble End-label Yes * Yes X Yes
  12088. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  12089. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  12090. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  12091. * Only one reference allowed
  12092. }
  12093. hp1 := nil; { To prevent compiler warnings }
  12094. Optimizer.CopyUsedRegs(RegisterTracking);
  12095. fOptimizer := Optimizer;
  12096. fLabel := AFirstLabel;
  12097. CMOVScore := 0;
  12098. ConstCount := 0;
  12099. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  12100. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  12101. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  12102. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  12103. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  12104. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  12105. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  12106. fInsertionPoint := p_initialjump;
  12107. fCondition := nil;
  12108. fInitialJump := p_initialjump;
  12109. fFirstMovBlock := p_initialmov;
  12110. fFirstMovBlockStop := nil;
  12111. fSecondJump := nil;
  12112. fSecondMovBlock := nil;
  12113. fSecondMovBlockStop := nil;
  12114. fMidLabel := nil;
  12115. fSecondJump := nil;
  12116. fSecondMovBlock := nil;
  12117. fEndLabel := nil;
  12118. fAllocationRange := nil;
  12119. { Assume it all goes horribly wrong! }
  12120. fState := tsInvalid;
  12121. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  12122. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  12123. 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
  12124. begin
  12125. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  12126. for Count := 0 to 1 do
  12127. with taicpu(fCondition).oper[Count]^ do
  12128. case typ of
  12129. top_reg:
  12130. if getregtype(reg) = R_INTREGISTER then
  12131. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12132. top_ref:
  12133. begin
  12134. if
  12135. {$ifdef x86_64}
  12136. (ref^.base <> NR_RIP) and
  12137. {$endif x86_64}
  12138. (ref^.base <> NR_NO) then
  12139. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12140. if (ref^.index <> NR_NO) then
  12141. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12142. end
  12143. else
  12144. ;
  12145. end;
  12146. { When inserting instructions before hp_prev, try to insert them
  12147. before the allocation of the FLAGS register }
  12148. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  12149. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  12150. { If not found, set it equal to the condition so it's something sensible }
  12151. fInsertionPoint := fCondition;
  12152. { When dealing with a comparison against zero, take note of the
  12153. instruction before it to see if we can move instructions further
  12154. back in order to benefit PostPeepholeOptTestOr.
  12155. }
  12156. if (
  12157. (
  12158. (taicpu(fCondition).opcode = A_CMP) and
  12159. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  12160. ) or
  12161. (
  12162. (taicpu(fCondition).opcode = A_TEST) and
  12163. (
  12164. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  12165. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  12166. )
  12167. )
  12168. ) and
  12169. Optimizer.GetLastInstruction(fCondition, hp1) then
  12170. begin
  12171. { These instructions set the zero flag if the result is zero }
  12172. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  12173. begin
  12174. fInsertionPoint := hp1;
  12175. { Also mark all the registers in this previous instruction
  12176. as 'in use', even if they've just been deallocated }
  12177. for Count := 0 to 1 do
  12178. with taicpu(hp1).oper[Count]^ do
  12179. case typ of
  12180. top_reg:
  12181. if getregtype(reg) = R_INTREGISTER then
  12182. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12183. top_ref:
  12184. begin
  12185. if
  12186. {$ifdef x86_64}
  12187. (ref^.base <> NR_RIP) and
  12188. {$endif x86_64}
  12189. (ref^.base <> NR_NO) then
  12190. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12191. if (ref^.index <> NR_NO) then
  12192. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12193. end
  12194. else
  12195. ;
  12196. end;
  12197. end;
  12198. end;
  12199. end
  12200. else
  12201. fCondition := nil;
  12202. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  12203. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  12204. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  12205. { If not found, set it equal to p so it's something sensible }
  12206. fInsertionPoint := hp1;
  12207. hp1 := p_initialmov;
  12208. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  12209. Exit;
  12210. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  12211. if (hp1.typ <> ait_label) then { should be on a jump }
  12212. begin
  12213. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  12214. { Need a label afterwards }
  12215. Exit;
  12216. end
  12217. else
  12218. fMidLabel := hp1;
  12219. if tai_label(fMidLabel).labsym <> AFirstLabel then
  12220. { Not the correct label }
  12221. fMidLabel := nil;
  12222. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12223. { If there's neither a 2nd jump nor correct label, then it's invalid
  12224. (see above table) }
  12225. Exit;
  12226. { Analyse the first block of MOVs more closely }
  12227. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12228. if Assigned(fSecondJump) then
  12229. begin
  12230. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12231. begin
  12232. fState := tsDetour
  12233. end
  12234. else
  12235. begin
  12236. { Need the correct mid-label for this one }
  12237. if not Assigned(fMidLabel) then
  12238. Exit;
  12239. fState := tsBranching;
  12240. end;
  12241. end
  12242. else
  12243. { No jump. but mid-label is present }
  12244. fState := tsSimple;
  12245. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12246. begin
  12247. { Invalid or too many instructions to be worthwhile }
  12248. fState := tsInvalid;
  12249. Exit;
  12250. end;
  12251. { check further for
  12252. jCC xxx
  12253. <several movs 1>
  12254. jmp yyy
  12255. xxx:
  12256. <several movs 2>
  12257. yyy:
  12258. etc.
  12259. }
  12260. if (fState = tsBranching) and
  12261. { Estimate for required savings for extra jump }
  12262. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12263. { Only one reference is allowed for double blocks }
  12264. (AFirstLabel.getrefs = 1) then
  12265. begin
  12266. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12267. fSecondMovBlock := hp1;
  12268. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12269. begin
  12270. EvaluateBranchingType;
  12271. Exit;
  12272. end;
  12273. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12274. if (hp1.typ <> ait_label) then { should be on a jump }
  12275. begin
  12276. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12277. begin
  12278. { Need a label afterwards }
  12279. EvaluateBranchingType;
  12280. Exit;
  12281. end;
  12282. end
  12283. else
  12284. fEndLabel := hp1;
  12285. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12286. { Second jump doesn't go to the end }
  12287. fEndLabel := nil;
  12288. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12289. begin
  12290. { If there's neither a 3rd jump nor correct end label, then it's
  12291. not a invalid double block, but is a valid single branching
  12292. block (see above table) }
  12293. EvaluateBranchingType;
  12294. Exit;
  12295. end;
  12296. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12297. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12298. { Invalid or too many instructions to be worthwhile }
  12299. Exit;
  12300. Inc(CMOVScore, Count);
  12301. if Assigned(fThirdJump) then
  12302. begin
  12303. if not Assigned(fSecondJump) then
  12304. fState := tsDoubleSecondBranching
  12305. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12306. fState := tsDoubleBranchSame
  12307. else
  12308. fState := tsDoubleBranchDifferent;
  12309. end
  12310. else
  12311. fState := tsDouble;
  12312. end;
  12313. if fState = tsBranching then
  12314. EvaluateBranchingType;
  12315. end;
  12316. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12317. new register to store the constant }
  12318. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12319. var
  12320. RegSize: TSubRegister;
  12321. CurrentVal: TCGInt;
  12322. ANewReg: TRegister;
  12323. X: ShortInt;
  12324. begin
  12325. Result := False;
  12326. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12327. Exit;
  12328. if ConstCount >= MAX_CMOV_REGISTERS then
  12329. { Arrays are full }
  12330. Exit;
  12331. { Remember that CMOV can't encode 8-bit registers }
  12332. case taicpu(p).opsize of
  12333. S_W:
  12334. RegSize := R_SUBW;
  12335. S_L:
  12336. RegSize := R_SUBD;
  12337. {$ifdef x86_64}
  12338. S_Q:
  12339. RegSize := R_SUBQ;
  12340. {$endif x86_64}
  12341. else
  12342. InternalError(2021100401);
  12343. end;
  12344. { See if the value has already been reserved for another CMOV instruction }
  12345. CurrentVal := taicpu(p).oper[0]^.val;
  12346. for X := 0 to ConstCount - 1 do
  12347. if ConstVals[X] = CurrentVal then
  12348. begin
  12349. ConstRegs[ConstCount] := ConstRegs[X];
  12350. ConstSizes[ConstCount] := RegSize;
  12351. ConstVals[ConstCount] := CurrentVal;
  12352. Inc(ConstCount);
  12353. Inc(Count);
  12354. Result := True;
  12355. Exit;
  12356. end;
  12357. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12358. if ANewReg = NR_NO then
  12359. { No free registers }
  12360. Exit;
  12361. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12362. up vying for the same register }
  12363. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12364. ConstRegs[ConstCount] := ANewReg;
  12365. ConstSizes[ConstCount] := RegSize;
  12366. ConstVals[ConstCount] := CurrentVal;
  12367. Inc(ConstCount);
  12368. Inc(Count);
  12369. Result := True;
  12370. end;
  12371. destructor TCMOVTracking.Done;
  12372. begin
  12373. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12374. end;
  12375. procedure TCMOVTracking.Process(out new_p: tai);
  12376. var
  12377. Count, Writes: LongInt;
  12378. RegMatch: Boolean;
  12379. hp1, hp_new: tai;
  12380. inverted_condition, condition: TAsmCond;
  12381. begin
  12382. if (fState in [tsInvalid, tsProcessed]) then
  12383. InternalError(2023110701);
  12384. { Repurpose RegisterTracking to mark registers that we've defined }
  12385. RegisterTracking[R_INTREGISTER].Clear;
  12386. Count := 0;
  12387. Writes := 0;
  12388. condition := taicpu(fInitialJump).condition;
  12389. inverted_condition := inverse_cond(condition);
  12390. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12391. doesn't get CMOVs in this case }
  12392. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12393. begin
  12394. { Include the jump in the flag tracking }
  12395. if Assigned(fThirdJump) then
  12396. begin
  12397. if (fState = tsDoubleBranchSame) then
  12398. begin
  12399. { Will be an unconditional jump, so track to the instruction before it }
  12400. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12401. InternalError(2023110710);
  12402. end
  12403. else
  12404. hp1 := fThirdJump;
  12405. end
  12406. else
  12407. hp1 := fSecondMovBlockStop;
  12408. end
  12409. else
  12410. begin
  12411. { Include a conditional jump in the flag tracking }
  12412. if Assigned(fSecondJump) then
  12413. begin
  12414. if (fState = tsDetour) then
  12415. begin
  12416. { Will be an unconditional jump, so track to the instruction before it }
  12417. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12418. InternalError(2023110711);
  12419. end
  12420. else
  12421. hp1 := fSecondJump;
  12422. end
  12423. else
  12424. hp1 := fFirstMovBlockStop;
  12425. end;
  12426. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12427. { Process the second set of MOVs first, because if a destination
  12428. register is shared between the first and second MOV sets, it is more
  12429. efficient to turn the first one into a MOV instruction and place it
  12430. before the CMP if possible, but we won't know which registers are
  12431. shared until we've processed at least one list, so we might as well
  12432. make it the second one since that won't be modified again. }
  12433. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12434. begin
  12435. hp1 := fSecondMovBlock;
  12436. repeat
  12437. if not Assigned(hp1) then
  12438. InternalError(2018062902);
  12439. if (hp1.typ = ait_instruction) then
  12440. begin
  12441. { Extra safeguard }
  12442. if (taicpu(hp1).opcode <> A_MOV) then
  12443. InternalError(2018062903);
  12444. { Note: tsDoubleBranchDifferent is essentially identical to
  12445. tsBranching and the 2nd block is best left largely
  12446. untouched, but we need to evaluate which registers the MOVs
  12447. write to in order to track what would be complementary CMOV
  12448. pairs that can be further optimised. [Kit] }
  12449. if fState <> tsDoubleBranchDifferent then
  12450. begin
  12451. if taicpu(hp1).oper[0]^.typ = top_const then
  12452. begin
  12453. RegMatch := False;
  12454. for Count := 0 to ConstCount - 1 do
  12455. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12456. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12457. begin
  12458. RegMatch := True;
  12459. { If it's in RegisterTracking, then this register
  12460. is being used more than once and hence has
  12461. already had its value defined (it gets added to
  12462. UsedRegs through AllocRegBetween below) }
  12463. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12464. begin
  12465. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12466. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12467. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12468. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12469. ConstMovs[Count] := hp_new;
  12470. end
  12471. else
  12472. { We just need an instruction between hp_prev and hp1
  12473. where we know the register is marked as in use }
  12474. hp_new := fSecondMovBlock;
  12475. { Keep track of largest write for this register so it can be optimised later }
  12476. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12477. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12478. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12479. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12480. Break;
  12481. end;
  12482. if not RegMatch then
  12483. InternalError(2021100411);
  12484. end;
  12485. taicpu(hp1).opcode := A_CMOVcc;
  12486. taicpu(hp1).condition := condition;
  12487. end;
  12488. { Store these writes to search for duplicates later on }
  12489. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12490. Inc(Writes);
  12491. end;
  12492. fOptimizer.GetNextInstruction(hp1, hp1);
  12493. until (hp1 = fSecondMovBlockStop);
  12494. end;
  12495. { Now do the first set of MOVs }
  12496. hp1 := fFirstMovBlock;
  12497. repeat
  12498. if not Assigned(hp1) then
  12499. InternalError(2018062904);
  12500. if (hp1.typ = ait_instruction) then
  12501. begin
  12502. RegMatch := False;
  12503. { Extra safeguard }
  12504. if (taicpu(hp1).opcode <> A_MOV) then
  12505. InternalError(2018062905);
  12506. { Search through the RegWrites list to see if there are any
  12507. opposing CMOV pairs that write to the same register }
  12508. for Count := 0 to Writes - 1 do
  12509. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12510. begin
  12511. { We have a match. Keep this as a MOV }
  12512. { Move ahead in preparation }
  12513. fOptimizer.GetNextInstruction(hp1, hp1);
  12514. RegMatch := True;
  12515. Break;
  12516. end;
  12517. if RegMatch then
  12518. Continue;
  12519. if taicpu(hp1).oper[0]^.typ = top_const then
  12520. begin
  12521. for Count := 0 to ConstCount - 1 do
  12522. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12523. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12524. begin
  12525. RegMatch := True;
  12526. { If it's in RegisterTracking, then this register is
  12527. being used more than once and hence has already had
  12528. its value defined (it gets added to UsedRegs through
  12529. AllocRegBetween below) }
  12530. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12531. begin
  12532. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12533. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12534. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12535. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12536. ConstMovs[Count] := hp_new;
  12537. end
  12538. else
  12539. { We just need an instruction between hp_prev and hp1
  12540. where we know the register is marked as in use }
  12541. hp_new := fFirstMovBlock;
  12542. { Keep track of largest write for this register so it can be optimised later }
  12543. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12544. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12545. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12546. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12547. Break;
  12548. end;
  12549. if not RegMatch then
  12550. InternalError(2021100412);
  12551. end;
  12552. taicpu(hp1).opcode := A_CMOVcc;
  12553. taicpu(hp1).condition := inverted_condition;
  12554. if (fState = tsDoubleBranchDifferent) then
  12555. begin
  12556. { Store these writes to search for duplicates later on }
  12557. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12558. Inc(Writes);
  12559. end;
  12560. end;
  12561. fOptimizer.GetNextInstruction(hp1, hp1);
  12562. until (hp1 = fFirstMovBlockStop);
  12563. { Update initialisation MOVs to the smallest possible size }
  12564. for Count := 0 to ConstCount - 1 do
  12565. if Assigned(ConstMovs[Count]) then
  12566. begin
  12567. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12568. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12569. end;
  12570. case fState of
  12571. tsSimple:
  12572. begin
  12573. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12574. { No branch to delete }
  12575. end;
  12576. tsDetour:
  12577. begin
  12578. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12579. { Preserve jump }
  12580. end;
  12581. tsBranching, tsDoubleBranchDifferent:
  12582. begin
  12583. if (fState = tsBranching) then
  12584. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12585. else
  12586. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12587. taicpu(fSecondJump).opcode := A_JCC;
  12588. taicpu(fSecondJump).condition := inverted_condition;
  12589. end;
  12590. tsDouble, tsDoubleBranchSame:
  12591. begin
  12592. if (fState = tsDouble) then
  12593. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12594. else
  12595. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12596. { Delete second jump }
  12597. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12598. fOptimizer.RemoveInstruction(fSecondJump);
  12599. end;
  12600. tsDoubleSecondBranching:
  12601. begin
  12602. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12603. { Delete second jump, preserve third jump as conditional }
  12604. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12605. fOptimizer.RemoveInstruction(fSecondJump);
  12606. taicpu(fThirdJump).opcode := A_JCC;
  12607. taicpu(fThirdJump).condition := condition;
  12608. end;
  12609. else
  12610. InternalError(2023110720);
  12611. end;
  12612. { Now we can safely decrement the reference count }
  12613. tasmlabel(fLabel).decrefs;
  12614. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12615. { Remove the original jump }
  12616. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12617. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12618. fState := tsProcessed;
  12619. end;
  12620. {$endif 8086}
  12621. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12622. var
  12623. hp1,hp2: tai;
  12624. carryadd_opcode : TAsmOp;
  12625. symbol: TAsmSymbol;
  12626. increg, tmpreg: TRegister;
  12627. {$ifndef i8086}
  12628. CMOVTracking: PCMOVTracking;
  12629. hp3,hp4,hp5: tai;
  12630. {$endif i8086}
  12631. TempBool: Boolean;
  12632. begin
  12633. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12634. DoJumpOptimizations(p, TempBool) then
  12635. Exit(True);
  12636. result:=false;
  12637. if GetNextInstruction(p,hp1) then
  12638. begin
  12639. if (hp1.typ=ait_label) then
  12640. begin
  12641. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12642. Exit;
  12643. end
  12644. else if (hp1.typ<>ait_instruction) then
  12645. Exit;
  12646. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12647. if (
  12648. (
  12649. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12650. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12651. (Taicpu(hp1).oper[0]^.val=1)
  12652. ) or
  12653. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12654. ) and
  12655. GetNextInstruction(hp1,hp2) and
  12656. FindLabel(TAsmLabel(symbol), hp2) then
  12657. { jb @@1 cmc
  12658. inc/dec operand --> adc/sbb operand,0
  12659. @@1:
  12660. ... and ...
  12661. jnb @@1
  12662. inc/dec operand --> adc/sbb operand,0
  12663. @@1: }
  12664. begin
  12665. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12666. begin
  12667. case taicpu(hp1).opcode of
  12668. A_INC,
  12669. A_ADD:
  12670. carryadd_opcode:=A_ADC;
  12671. A_DEC,
  12672. A_SUB:
  12673. carryadd_opcode:=A_SBB;
  12674. else
  12675. InternalError(2021011001);
  12676. end;
  12677. Taicpu(p).clearop(0);
  12678. Taicpu(p).ops:=0;
  12679. Taicpu(p).is_jmp:=false;
  12680. Taicpu(p).opcode:=A_CMC;
  12681. Taicpu(p).condition:=C_NONE;
  12682. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12683. Taicpu(hp1).ops:=2;
  12684. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12685. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12686. else
  12687. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12688. Taicpu(hp1).loadconst(0,0);
  12689. Taicpu(hp1).opcode:=carryadd_opcode;
  12690. result:=true;
  12691. exit;
  12692. end
  12693. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12694. begin
  12695. case taicpu(hp1).opcode of
  12696. A_INC,
  12697. A_ADD:
  12698. carryadd_opcode:=A_ADC;
  12699. A_DEC,
  12700. A_SUB:
  12701. carryadd_opcode:=A_SBB;
  12702. else
  12703. InternalError(2021011002);
  12704. end;
  12705. Taicpu(hp1).ops:=2;
  12706. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12707. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12708. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12709. else
  12710. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12711. Taicpu(hp1).loadconst(0,0);
  12712. Taicpu(hp1).opcode:=carryadd_opcode;
  12713. RemoveCurrentP(p, hp1);
  12714. result:=true;
  12715. exit;
  12716. end
  12717. {
  12718. jcc @@1 setcc tmpreg
  12719. inc/dec/add/sub operand -> (movzx tmpreg)
  12720. @@1: add/sub tmpreg,operand
  12721. While this increases code size slightly, it makes the code much faster if the
  12722. jump is unpredictable
  12723. }
  12724. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12725. begin
  12726. { search for an available register which is volatile }
  12727. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12728. if increg <> NR_NO then
  12729. begin
  12730. { We don't need to check if tmpreg is in hp1 or not, because
  12731. it will be marked as in use at p (if not, this is
  12732. indictive of a compiler bug). }
  12733. TAsmLabel(symbol).decrefs;
  12734. Taicpu(p).clearop(0);
  12735. Taicpu(p).ops:=1;
  12736. Taicpu(p).is_jmp:=false;
  12737. Taicpu(p).opcode:=A_SETcc;
  12738. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12739. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12740. Taicpu(p).loadreg(0,increg);
  12741. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12742. begin
  12743. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12744. R_SUBW:
  12745. begin
  12746. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12747. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12748. end;
  12749. R_SUBD:
  12750. begin
  12751. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12752. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12753. end;
  12754. {$ifdef x86_64}
  12755. R_SUBQ:
  12756. begin
  12757. { MOVZX doesn't have a 64-bit variant, because
  12758. the 32-bit version implicitly zeroes the
  12759. upper 32-bits of the destination register }
  12760. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12761. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12762. setsubreg(tmpreg, R_SUBQ);
  12763. end;
  12764. {$endif x86_64}
  12765. else
  12766. Internalerror(2020030601);
  12767. end;
  12768. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12769. asml.InsertAfter(hp2,p);
  12770. end
  12771. else
  12772. tmpreg := increg;
  12773. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12774. begin
  12775. Taicpu(hp1).ops:=2;
  12776. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12777. end;
  12778. Taicpu(hp1).loadreg(0,tmpreg);
  12779. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12780. Result := True;
  12781. { p is no longer a Jcc instruction, so exit }
  12782. Exit;
  12783. end;
  12784. end;
  12785. end;
  12786. { Detect the following:
  12787. jmp<cond> @Lbl1
  12788. jmp @Lbl2
  12789. ...
  12790. @Lbl1:
  12791. ret
  12792. Change to:
  12793. jmp<inv_cond> @Lbl2
  12794. ret
  12795. }
  12796. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12797. begin
  12798. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12799. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12800. MatchInstruction(hp2,A_RET,[S_NO]) then
  12801. begin
  12802. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12803. { Change label address to that of the unconditional jump }
  12804. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12805. TAsmLabel(symbol).DecRefs;
  12806. taicpu(hp1).opcode := A_RET;
  12807. taicpu(hp1).is_jmp := false;
  12808. taicpu(hp1).ops := taicpu(hp2).ops;
  12809. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12810. case taicpu(hp2).ops of
  12811. 0:
  12812. taicpu(hp1).clearop(0);
  12813. 1:
  12814. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12815. else
  12816. internalerror(2016041302);
  12817. end;
  12818. end;
  12819. {$ifndef i8086}
  12820. end
  12821. {
  12822. convert
  12823. j<c> .L1
  12824. mov 1,reg
  12825. jmp .L2
  12826. .L1
  12827. mov 0,reg
  12828. .L2
  12829. into
  12830. mov 0,reg
  12831. set<not(c)> reg
  12832. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12833. would destroy the flag contents
  12834. }
  12835. else if MatchInstruction(hp1,A_MOV,[]) and
  12836. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12837. {$ifdef i386}
  12838. (
  12839. { Under i386, ESI, EDI, EBP and ESP
  12840. don't have an 8-bit representation }
  12841. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12842. ) and
  12843. {$endif i386}
  12844. (taicpu(hp1).oper[0]^.val=1) and
  12845. GetNextInstruction(hp1,hp2) and
  12846. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12847. GetNextInstruction(hp2,hp3) and
  12848. (hp3.typ=ait_label) and
  12849. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12850. (tai_label(hp3).labsym.getrefs=1) and
  12851. GetNextInstruction(hp3,hp4) and
  12852. MatchInstruction(hp4,A_MOV,[]) and
  12853. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12854. (taicpu(hp4).oper[0]^.val=0) and
  12855. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12856. GetNextInstruction(hp4,hp5) and
  12857. (hp5.typ=ait_label) and
  12858. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12859. (tai_label(hp5).labsym.getrefs=1) then
  12860. begin
  12861. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12862. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12863. { remove last label }
  12864. RemoveInstruction(hp5);
  12865. { remove second label }
  12866. RemoveInstruction(hp3);
  12867. { remove jmp }
  12868. RemoveInstruction(hp2);
  12869. if taicpu(hp1).opsize=S_B then
  12870. RemoveInstruction(hp1)
  12871. else
  12872. taicpu(hp1).loadconst(0,0);
  12873. taicpu(hp4).opcode:=A_SETcc;
  12874. taicpu(hp4).opsize:=S_B;
  12875. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12876. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12877. taicpu(hp4).opercnt:=1;
  12878. taicpu(hp4).ops:=1;
  12879. taicpu(hp4).freeop(1);
  12880. RemoveCurrentP(p);
  12881. Result:=true;
  12882. exit;
  12883. end
  12884. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12885. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12886. begin
  12887. { check for
  12888. jCC xxx
  12889. <several movs>
  12890. xxx:
  12891. Also spot:
  12892. Jcc xxx
  12893. <several movs>
  12894. jmp xxx
  12895. Change to:
  12896. <several cmovs with inverted condition>
  12897. jmp xxx (only for the 2nd case)
  12898. }
  12899. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12900. if CMOVTracking^.State <> tsInvalid then
  12901. begin
  12902. CMovTracking^.Process(p);
  12903. Result := True;
  12904. end;
  12905. CMOVTracking^.Done;
  12906. {$endif i8086}
  12907. end;
  12908. end;
  12909. end;
  12910. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12911. var
  12912. hp1,hp2,hp3: tai;
  12913. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12914. NewSize: TOpSize;
  12915. NewRegSize: TSubRegister;
  12916. Limit: TCgInt;
  12917. SwapOper: POper;
  12918. begin
  12919. result:=false;
  12920. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12921. GetNextInstruction(p,hp1) and
  12922. (hp1.typ = ait_instruction);
  12923. if reg_and_hp1_is_instr and
  12924. (
  12925. (taicpu(hp1).opcode <> A_LEA) or
  12926. { If the LEA instruction can be converted into an arithmetic instruction,
  12927. it may be possible to then fold it. }
  12928. (
  12929. { If the flags register is in use, don't change the instruction
  12930. to an ADD otherwise this will scramble the flags. [Kit] }
  12931. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12932. ConvertLEA(taicpu(hp1))
  12933. )
  12934. ) and
  12935. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12936. GetNextInstruction(hp1,hp2) and
  12937. MatchInstruction(hp2,A_MOV,[]) and
  12938. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12939. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12940. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12941. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12942. {$ifdef i386}
  12943. { not all registers have byte size sub registers on i386 }
  12944. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12945. {$endif i386}
  12946. (((taicpu(hp1).ops=2) and
  12947. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12948. ((taicpu(hp1).ops=1) and
  12949. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12950. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12951. begin
  12952. { change movsX/movzX reg/ref, reg2
  12953. add/sub/or/... reg3/$const, reg2
  12954. mov reg2 reg/ref
  12955. to add/sub/or/... reg3/$const, reg/ref }
  12956. { by example:
  12957. movswl %si,%eax movswl %si,%eax p
  12958. decl %eax addl %edx,%eax hp1
  12959. movw %ax,%si movw %ax,%si hp2
  12960. ->
  12961. movswl %si,%eax movswl %si,%eax p
  12962. decw %eax addw %edx,%eax hp1
  12963. movw %ax,%si movw %ax,%si hp2
  12964. }
  12965. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12966. {
  12967. ->
  12968. movswl %si,%eax movswl %si,%eax p
  12969. decw %si addw %dx,%si hp1
  12970. movw %ax,%si movw %ax,%si hp2
  12971. }
  12972. case taicpu(hp1).ops of
  12973. 1:
  12974. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12975. 2:
  12976. begin
  12977. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12978. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12979. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12980. end;
  12981. else
  12982. internalerror(2008042702);
  12983. end;
  12984. {
  12985. ->
  12986. decw %si addw %dx,%si p
  12987. }
  12988. DebugMsg(SPeepholeOptimization + 'var3',p);
  12989. RemoveCurrentP(p, hp1);
  12990. RemoveInstruction(hp2);
  12991. Result := True;
  12992. Exit;
  12993. end;
  12994. if reg_and_hp1_is_instr and
  12995. (taicpu(hp1).opcode = A_MOV) and
  12996. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12997. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12998. {$ifdef x86_64}
  12999. { check for implicit extension to 64 bit }
  13000. or
  13001. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13002. (taicpu(hp1).opsize=S_Q) and
  13003. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  13004. )
  13005. {$endif x86_64}
  13006. )
  13007. then
  13008. begin
  13009. { change
  13010. movx %reg1,%reg2
  13011. mov %reg2,%reg3
  13012. dealloc %reg2
  13013. into
  13014. movx %reg,%reg3
  13015. }
  13016. TransferUsedRegs(TmpUsedRegs);
  13017. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13018. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  13019. begin
  13020. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  13021. {$ifdef x86_64}
  13022. if (taicpu(p).opsize in [S_BL,S_WL]) and
  13023. (taicpu(hp1).opsize=S_Q) then
  13024. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  13025. else
  13026. {$endif x86_64}
  13027. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  13028. RemoveInstruction(hp1);
  13029. Result := True;
  13030. Exit;
  13031. end;
  13032. end;
  13033. if reg_and_hp1_is_instr and
  13034. ((taicpu(hp1).opcode=A_MOV) or
  13035. (taicpu(hp1).opcode=A_ADD) or
  13036. (taicpu(hp1).opcode=A_SUB) or
  13037. (taicpu(hp1).opcode=A_CMP) or
  13038. (taicpu(hp1).opcode=A_OR) or
  13039. (taicpu(hp1).opcode=A_XOR) or
  13040. (taicpu(hp1).opcode=A_AND)
  13041. ) and
  13042. (taicpu(hp1).oper[1]^.typ = top_reg) then
  13043. begin
  13044. AndTest := (taicpu(hp1).opcode=A_AND) and
  13045. GetNextInstruction(hp1, hp2) and
  13046. (hp2.typ = ait_instruction) and
  13047. (
  13048. (
  13049. (taicpu(hp2).opcode=A_TEST) and
  13050. (
  13051. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  13052. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  13053. (
  13054. { If the AND and TEST instructions share a constant, this is also valid }
  13055. (taicpu(hp1).oper[0]^.typ = top_const) and
  13056. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  13057. )
  13058. ) and
  13059. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13060. ) or
  13061. (
  13062. (taicpu(hp2).opcode=A_CMP) and
  13063. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  13064. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13065. )
  13066. );
  13067. { change
  13068. movx (oper),%reg2
  13069. and $x,%reg2
  13070. test %reg2,%reg2
  13071. dealloc %reg2
  13072. into
  13073. op %reg1,%reg3
  13074. if the second op accesses only the bits stored in reg1
  13075. }
  13076. if ((taicpu(p).oper[0]^.typ=top_reg) or
  13077. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  13078. (taicpu(hp1).oper[0]^.typ = top_const) and
  13079. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13080. AndTest then
  13081. begin
  13082. { Check if the AND constant is in range }
  13083. case taicpu(p).opsize of
  13084. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13085. begin
  13086. NewSize := S_B;
  13087. Limit := $FF;
  13088. end;
  13089. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13090. begin
  13091. NewSize := S_W;
  13092. Limit := $FFFF;
  13093. end;
  13094. {$ifdef x86_64}
  13095. S_LQ:
  13096. begin
  13097. NewSize := S_L;
  13098. Limit := $FFFFFFFF;
  13099. end;
  13100. {$endif x86_64}
  13101. else
  13102. InternalError(2021120303);
  13103. end;
  13104. if (
  13105. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  13106. { Check for negative operands }
  13107. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  13108. ) and
  13109. GetNextInstruction(hp2,hp3) and
  13110. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  13111. (taicpu(hp3).condition in [C_E,C_NE]) then
  13112. begin
  13113. TransferUsedRegs(TmpUsedRegs);
  13114. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13115. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13116. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  13117. begin
  13118. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  13119. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13120. taicpu(hp1).opcode := A_TEST;
  13121. taicpu(hp1).opsize := NewSize;
  13122. RemoveInstruction(hp2);
  13123. RemoveCurrentP(p, hp1);
  13124. Result:=true;
  13125. exit;
  13126. end;
  13127. end;
  13128. end;
  13129. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13130. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  13131. (taicpu(hp1).opsize=S_B)) or
  13132. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  13133. (taicpu(hp1).opsize=S_W))
  13134. {$ifdef x86_64}
  13135. or ((taicpu(p).opsize=S_LQ) and
  13136. (taicpu(hp1).opsize=S_L))
  13137. {$endif x86_64}
  13138. ) and
  13139. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  13140. begin
  13141. { change
  13142. movx %reg1,%reg2
  13143. op %reg2,%reg3
  13144. dealloc %reg2
  13145. into
  13146. op %reg1,%reg3
  13147. if the second op accesses only the bits stored in reg1
  13148. }
  13149. TransferUsedRegs(TmpUsedRegs);
  13150. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13151. if AndTest then
  13152. begin
  13153. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13154. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13155. end
  13156. else
  13157. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13158. if not RegUsed then
  13159. begin
  13160. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  13161. if taicpu(p).oper[0]^.typ=top_reg then
  13162. begin
  13163. case taicpu(hp1).opsize of
  13164. S_B:
  13165. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  13166. S_W:
  13167. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  13168. S_L:
  13169. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  13170. else
  13171. Internalerror(2020102301);
  13172. end;
  13173. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  13174. end
  13175. else
  13176. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  13177. RemoveCurrentP(p);
  13178. if AndTest then
  13179. RemoveInstruction(hp2);
  13180. result:=true;
  13181. exit;
  13182. end;
  13183. end
  13184. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13185. (
  13186. { Bitwise operations only }
  13187. (taicpu(hp1).opcode=A_AND) or
  13188. (taicpu(hp1).opcode=A_TEST) or
  13189. (
  13190. (taicpu(hp1).oper[0]^.typ = top_const) and
  13191. (
  13192. (taicpu(hp1).opcode=A_OR) or
  13193. (taicpu(hp1).opcode=A_XOR)
  13194. )
  13195. )
  13196. ) and
  13197. (
  13198. (taicpu(hp1).oper[0]^.typ = top_const) or
  13199. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  13200. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13201. ) then
  13202. begin
  13203. { change
  13204. movx %reg2,%reg2
  13205. op const,%reg2
  13206. into
  13207. op const,%reg2 (smaller version)
  13208. movx %reg2,%reg2
  13209. also change
  13210. movx %reg1,%reg2
  13211. and/test (oper),%reg2
  13212. dealloc %reg2
  13213. into
  13214. and/test (oper),%reg1
  13215. }
  13216. case taicpu(p).opsize of
  13217. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13218. begin
  13219. NewSize := S_B;
  13220. NewRegSize := R_SUBL;
  13221. Limit := $FF;
  13222. end;
  13223. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13224. begin
  13225. NewSize := S_W;
  13226. NewRegSize := R_SUBW;
  13227. Limit := $FFFF;
  13228. end;
  13229. {$ifdef x86_64}
  13230. S_LQ:
  13231. begin
  13232. NewSize := S_L;
  13233. NewRegSize := R_SUBD;
  13234. Limit := $FFFFFFFF;
  13235. end;
  13236. {$endif x86_64}
  13237. else
  13238. Internalerror(2021120302);
  13239. end;
  13240. TransferUsedRegs(TmpUsedRegs);
  13241. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13242. if AndTest then
  13243. begin
  13244. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13245. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13246. end
  13247. else
  13248. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13249. if
  13250. (
  13251. (taicpu(p).opcode = A_MOVZX) and
  13252. (
  13253. (taicpu(hp1).opcode=A_AND) or
  13254. (taicpu(hp1).opcode=A_TEST)
  13255. ) and
  13256. not (
  13257. { If both are references, then the final instruction will have
  13258. both operands as references, which is not allowed }
  13259. (taicpu(p).oper[0]^.typ = top_ref) and
  13260. (taicpu(hp1).oper[0]^.typ = top_ref)
  13261. ) and
  13262. not RegUsed
  13263. ) or
  13264. (
  13265. (
  13266. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13267. not RegUsed
  13268. ) and
  13269. (taicpu(p).oper[0]^.typ = top_reg) and
  13270. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13271. (taicpu(hp1).oper[0]^.typ = top_const) and
  13272. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13273. ) then
  13274. begin
  13275. {$if defined(i386) or defined(i8086)}
  13276. { If the target size is 8-bit, make sure we can actually encode it }
  13277. 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
  13278. Exit;
  13279. {$endif i386 or i8086}
  13280. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13281. taicpu(hp1).opsize := NewSize;
  13282. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13283. if AndTest then
  13284. begin
  13285. RemoveInstruction(hp2);
  13286. if not RegUsed then
  13287. begin
  13288. taicpu(hp1).opcode := A_TEST;
  13289. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13290. begin
  13291. { Make sure the reference is the second operand }
  13292. SwapOper := taicpu(hp1).oper[0];
  13293. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13294. taicpu(hp1).oper[1] := SwapOper;
  13295. end;
  13296. end;
  13297. end;
  13298. case taicpu(hp1).oper[0]^.typ of
  13299. top_reg:
  13300. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13301. top_const:
  13302. { For the AND/TEST case }
  13303. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13304. else
  13305. ;
  13306. end;
  13307. if RegUsed then
  13308. begin
  13309. AsmL.Remove(p);
  13310. AsmL.InsertAfter(p, hp1);
  13311. p := hp1;
  13312. end
  13313. else
  13314. RemoveCurrentP(p, hp1);
  13315. result:=true;
  13316. exit;
  13317. end;
  13318. end;
  13319. end;
  13320. if reg_and_hp1_is_instr and
  13321. (taicpu(p).oper[0]^.typ = top_reg) and
  13322. (
  13323. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13324. ) and
  13325. (taicpu(hp1).oper[0]^.typ = top_const) and
  13326. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13327. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13328. { Minimum shift value allowed is the bit difference between the sizes }
  13329. (taicpu(hp1).oper[0]^.val >=
  13330. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13331. 8 * (
  13332. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13333. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13334. )
  13335. ) then
  13336. begin
  13337. { For:
  13338. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13339. shl/sal ##, %reg1
  13340. Remove the movsx/movzx instruction if the shift overwrites the
  13341. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13342. }
  13343. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13344. RemoveCurrentP(p, hp1);
  13345. Result := True;
  13346. Exit;
  13347. end
  13348. else if reg_and_hp1_is_instr and
  13349. (taicpu(p).oper[0]^.typ = top_reg) and
  13350. (
  13351. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13352. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13353. ) and
  13354. (taicpu(hp1).oper[0]^.typ = top_const) and
  13355. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13356. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13357. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13358. (taicpu(hp1).oper[0]^.val <
  13359. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13360. 8 * (
  13361. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13362. )
  13363. ) then
  13364. begin
  13365. { For:
  13366. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13367. sar ##, %reg1 shr ##, %reg1
  13368. Move the shift to before the movx instruction if the shift value
  13369. is not too large.
  13370. }
  13371. asml.Remove(hp1);
  13372. asml.InsertBefore(hp1, p);
  13373. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13374. case taicpu(p).opsize of
  13375. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13376. taicpu(hp1).opsize := S_B;
  13377. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13378. taicpu(hp1).opsize := S_W;
  13379. {$ifdef x86_64}
  13380. S_LQ:
  13381. taicpu(hp1).opsize := S_L;
  13382. {$endif}
  13383. else
  13384. InternalError(2020112401);
  13385. end;
  13386. if (taicpu(hp1).opcode = A_SHR) then
  13387. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13388. else
  13389. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13390. Result := True;
  13391. end;
  13392. if reg_and_hp1_is_instr and
  13393. (taicpu(p).oper[0]^.typ = top_reg) and
  13394. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13395. (
  13396. (taicpu(hp1).opcode = taicpu(p).opcode)
  13397. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13398. {$ifdef x86_64}
  13399. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13400. {$endif x86_64}
  13401. ) then
  13402. begin
  13403. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13404. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13405. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13406. begin
  13407. {
  13408. For example:
  13409. movzbw %al,%ax
  13410. movzwl %ax,%eax
  13411. Compress into:
  13412. movzbl %al,%eax
  13413. }
  13414. RegUsed := False;
  13415. case taicpu(p).opsize of
  13416. S_BW:
  13417. case taicpu(hp1).opsize of
  13418. S_WL:
  13419. begin
  13420. taicpu(p).opsize := S_BL;
  13421. RegUsed := True;
  13422. end;
  13423. {$ifdef x86_64}
  13424. S_WQ:
  13425. begin
  13426. if taicpu(p).opcode = A_MOVZX then
  13427. begin
  13428. taicpu(p).opsize := S_BL;
  13429. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13430. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13431. end
  13432. else
  13433. taicpu(p).opsize := S_BQ;
  13434. RegUsed := True;
  13435. end;
  13436. {$endif x86_64}
  13437. else
  13438. ;
  13439. end;
  13440. {$ifdef x86_64}
  13441. S_BL:
  13442. case taicpu(hp1).opsize of
  13443. S_LQ:
  13444. begin
  13445. if taicpu(p).opcode = A_MOVZX then
  13446. begin
  13447. taicpu(p).opsize := S_BL;
  13448. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13449. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13450. end
  13451. else
  13452. taicpu(p).opsize := S_BQ;
  13453. RegUsed := True;
  13454. end;
  13455. else
  13456. ;
  13457. end;
  13458. S_WL:
  13459. case taicpu(hp1).opsize of
  13460. S_LQ:
  13461. begin
  13462. if taicpu(p).opcode = A_MOVZX then
  13463. begin
  13464. taicpu(p).opsize := S_WL;
  13465. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13466. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13467. end
  13468. else
  13469. taicpu(p).opsize := S_WQ;
  13470. RegUsed := True;
  13471. end;
  13472. else
  13473. ;
  13474. end;
  13475. {$endif x86_64}
  13476. else
  13477. ;
  13478. end;
  13479. if RegUsed then
  13480. begin
  13481. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13482. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13483. RemoveInstruction(hp1);
  13484. Result := True;
  13485. Exit;
  13486. end;
  13487. end;
  13488. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13489. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13490. GetNextInstruction(hp1, hp2) and
  13491. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13492. (
  13493. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13494. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13495. {$ifdef x86_64}
  13496. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13497. {$endif x86_64}
  13498. ) and
  13499. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13500. (
  13501. (
  13502. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13503. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13504. ) or
  13505. (
  13506. { Only allow the operands in reverse order for TEST instructions }
  13507. (taicpu(hp2).opcode = A_TEST) and
  13508. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13509. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13510. )
  13511. ) then
  13512. begin
  13513. {
  13514. For example:
  13515. movzbl %al,%eax
  13516. movzbl (ref),%edx
  13517. andl %edx,%eax
  13518. (%edx deallocated)
  13519. Change to:
  13520. andb (ref),%al
  13521. movzbl %al,%eax
  13522. Rules are:
  13523. - First two instructions have the same opcode and opsize
  13524. - First instruction's operands are the same super-register
  13525. - Second instruction operates on a different register
  13526. - Third instruction is AND, OR, XOR or TEST
  13527. - Third instruction's operands are the destination registers of the first two instructions
  13528. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13529. - Second instruction's destination register is deallocated afterwards
  13530. }
  13531. TransferUsedRegs(TmpUsedRegs);
  13532. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13533. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13534. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13535. begin
  13536. case taicpu(p).opsize of
  13537. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13538. NewSize := S_B;
  13539. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13540. NewSize := S_W;
  13541. {$ifdef x86_64}
  13542. S_LQ:
  13543. NewSize := S_L;
  13544. {$endif x86_64}
  13545. else
  13546. InternalError(2021120301);
  13547. end;
  13548. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13549. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13550. taicpu(hp2).opsize := NewSize;
  13551. RemoveInstruction(hp1);
  13552. { With TEST, it's best to keep the MOVX instruction at the top }
  13553. if (taicpu(hp2).opcode <> A_TEST) then
  13554. begin
  13555. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13556. asml.Remove(p);
  13557. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13558. asml.InsertAfter(p, hp2);
  13559. p := hp2;
  13560. end
  13561. else
  13562. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13563. Result := True;
  13564. Exit;
  13565. end;
  13566. end;
  13567. end;
  13568. if taicpu(p).opcode=A_MOVZX then
  13569. begin
  13570. { removes superfluous And's after movzx's }
  13571. if reg_and_hp1_is_instr and
  13572. (taicpu(hp1).opcode = A_AND) and
  13573. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13574. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13575. {$ifdef x86_64}
  13576. { check for implicit extension to 64 bit }
  13577. or
  13578. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13579. (taicpu(hp1).opsize=S_Q) and
  13580. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13581. )
  13582. {$endif x86_64}
  13583. )
  13584. then
  13585. begin
  13586. case taicpu(p).opsize Of
  13587. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13588. if (taicpu(hp1).oper[0]^.val = $ff) then
  13589. begin
  13590. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13591. RemoveInstruction(hp1);
  13592. Result:=true;
  13593. exit;
  13594. end;
  13595. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13596. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13597. begin
  13598. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13599. RemoveInstruction(hp1);
  13600. Result:=true;
  13601. exit;
  13602. end;
  13603. {$ifdef x86_64}
  13604. S_LQ:
  13605. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13606. begin
  13607. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13608. RemoveInstruction(hp1);
  13609. Result:=true;
  13610. exit;
  13611. end;
  13612. {$endif x86_64}
  13613. else
  13614. ;
  13615. end;
  13616. { we cannot get rid of the and, but can we get rid of the movz ?}
  13617. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13618. begin
  13619. case taicpu(p).opsize Of
  13620. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13621. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13622. begin
  13623. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13624. RemoveCurrentP(p,hp1);
  13625. Result:=true;
  13626. exit;
  13627. end;
  13628. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13629. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13630. begin
  13631. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13632. RemoveCurrentP(p,hp1);
  13633. Result:=true;
  13634. exit;
  13635. end;
  13636. {$ifdef x86_64}
  13637. S_LQ:
  13638. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13639. begin
  13640. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13641. RemoveCurrentP(p,hp1);
  13642. Result:=true;
  13643. exit;
  13644. end;
  13645. {$endif x86_64}
  13646. else
  13647. ;
  13648. end;
  13649. end;
  13650. end;
  13651. { changes some movzx constructs to faster synonyms (all examples
  13652. are given with eax/ax, but are also valid for other registers)}
  13653. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13654. begin
  13655. case taicpu(p).opsize of
  13656. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13657. (the machine code is equivalent to movzbl %al,%eax), but the
  13658. code generator still generates that assembler instruction and
  13659. it is silently converted. This should probably be checked.
  13660. [Kit] }
  13661. S_BW:
  13662. begin
  13663. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13664. (
  13665. not IsMOVZXAcceptable
  13666. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13667. or (
  13668. (cs_opt_size in current_settings.optimizerswitches) and
  13669. (taicpu(p).oper[1]^.reg = NR_AX)
  13670. )
  13671. ) then
  13672. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13673. begin
  13674. DebugMsg(SPeepholeOptimization + 'var7',p);
  13675. taicpu(p).opcode := A_AND;
  13676. taicpu(p).changeopsize(S_W);
  13677. taicpu(p).loadConst(0,$ff);
  13678. Result := True;
  13679. end
  13680. else if not IsMOVZXAcceptable and
  13681. GetNextInstruction(p, hp1) and
  13682. (tai(hp1).typ = ait_instruction) and
  13683. (taicpu(hp1).opcode = A_AND) and
  13684. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13685. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13686. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13687. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13688. begin
  13689. DebugMsg(SPeepholeOptimization + 'var8',p);
  13690. taicpu(p).opcode := A_MOV;
  13691. taicpu(p).changeopsize(S_W);
  13692. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13693. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13694. Result := True;
  13695. end;
  13696. end;
  13697. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13698. S_BL:
  13699. if not IsMOVZXAcceptable then
  13700. begin
  13701. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13702. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13703. begin
  13704. DebugMsg(SPeepholeOptimization + 'var9',p);
  13705. taicpu(p).opcode := A_AND;
  13706. taicpu(p).changeopsize(S_L);
  13707. taicpu(p).loadConst(0,$ff);
  13708. Result := True;
  13709. end
  13710. else if GetNextInstruction(p, hp1) and
  13711. (tai(hp1).typ = ait_instruction) and
  13712. (taicpu(hp1).opcode = A_AND) and
  13713. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13714. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13715. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13716. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13717. begin
  13718. DebugMsg(SPeepholeOptimization + 'var10',p);
  13719. taicpu(p).opcode := A_MOV;
  13720. taicpu(p).changeopsize(S_L);
  13721. { do not use R_SUBWHOLE
  13722. as movl %rdx,%eax
  13723. is invalid in assembler PM }
  13724. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13725. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13726. Result := True;
  13727. end;
  13728. end;
  13729. {$endif i8086}
  13730. S_WL:
  13731. if not IsMOVZXAcceptable then
  13732. begin
  13733. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13734. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13735. begin
  13736. DebugMsg(SPeepholeOptimization + 'var11',p);
  13737. taicpu(p).opcode := A_AND;
  13738. taicpu(p).changeopsize(S_L);
  13739. taicpu(p).loadConst(0,$ffff);
  13740. Result := True;
  13741. end
  13742. else if GetNextInstruction(p, hp1) and
  13743. (tai(hp1).typ = ait_instruction) and
  13744. (taicpu(hp1).opcode = A_AND) and
  13745. (taicpu(hp1).oper[0]^.typ = top_const) and
  13746. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13747. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13748. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13749. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13750. begin
  13751. DebugMsg(SPeepholeOptimization + 'var12',p);
  13752. taicpu(p).opcode := A_MOV;
  13753. taicpu(p).changeopsize(S_L);
  13754. { do not use R_SUBWHOLE
  13755. as movl %rdx,%eax
  13756. is invalid in assembler PM }
  13757. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13758. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13759. Result := True;
  13760. end;
  13761. end;
  13762. else
  13763. InternalError(2017050705);
  13764. end;
  13765. end
  13766. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13767. begin
  13768. if GetNextInstruction(p, hp1) and
  13769. (tai(hp1).typ = ait_instruction) and
  13770. (taicpu(hp1).opcode = A_AND) and
  13771. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13772. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13773. begin
  13774. case taicpu(p).opsize Of
  13775. S_BL:
  13776. if (taicpu(hp1).opsize <> S_L) or
  13777. (taicpu(hp1).oper[0]^.val > $FF) then
  13778. begin
  13779. DebugMsg(SPeepholeOptimization + 'var13',p);
  13780. taicpu(hp1).changeopsize(S_L);
  13781. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13782. Include(OptsToCheck, aoc_ForceNewIteration);
  13783. end;
  13784. S_WL:
  13785. if (taicpu(hp1).opsize <> S_L) or
  13786. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13787. begin
  13788. DebugMsg(SPeepholeOptimization + 'var14',p);
  13789. taicpu(hp1).changeopsize(S_L);
  13790. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13791. Include(OptsToCheck, aoc_ForceNewIteration);
  13792. end;
  13793. S_BW:
  13794. if (taicpu(hp1).opsize <> S_W) or
  13795. (taicpu(hp1).oper[0]^.val > $FF) then
  13796. begin
  13797. DebugMsg(SPeepholeOptimization + 'var15',p);
  13798. taicpu(hp1).changeopsize(S_W);
  13799. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13800. Include(OptsToCheck, aoc_ForceNewIteration);
  13801. end;
  13802. else
  13803. Internalerror(2017050704)
  13804. end;
  13805. end;
  13806. end;
  13807. end;
  13808. end;
  13809. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13810. var
  13811. hp1, hp2 : tai;
  13812. MaskLength : Cardinal;
  13813. MaskedBits : TCgInt;
  13814. ActiveReg : TRegister;
  13815. begin
  13816. Result:=false;
  13817. { There are no optimisations for reference targets }
  13818. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13819. Exit;
  13820. while GetNextInstruction(p, hp1) and
  13821. (hp1.typ = ait_instruction) do
  13822. begin
  13823. if (taicpu(p).oper[0]^.typ = top_const) then
  13824. begin
  13825. case taicpu(hp1).opcode of
  13826. A_AND:
  13827. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13828. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13829. { the second register must contain the first one, so compare their subreg types }
  13830. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13831. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13832. { change
  13833. and const1, reg
  13834. and const2, reg
  13835. to
  13836. and (const1 and const2), reg
  13837. }
  13838. begin
  13839. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13840. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13841. RemoveCurrentP(p, hp1);
  13842. Result:=true;
  13843. exit;
  13844. end;
  13845. A_CMP:
  13846. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13847. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13848. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13849. { Just check that the condition on the next instruction is compatible }
  13850. GetNextInstruction(hp1, hp2) and
  13851. (hp2.typ = ait_instruction) and
  13852. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13853. then
  13854. { change
  13855. and 2^n, reg
  13856. cmp 2^n, reg
  13857. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13858. to
  13859. and 2^n, reg
  13860. test reg, reg
  13861. j(~c) / set(~c) / cmov(~c)
  13862. }
  13863. begin
  13864. { Keep TEST instruction in, rather than remove it, because
  13865. it may trigger other optimisations such as MovAndTest2Test }
  13866. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13867. taicpu(hp1).opcode := A_TEST;
  13868. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13869. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13870. Result := True;
  13871. Exit;
  13872. end
  13873. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13874. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13875. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13876. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13877. { change
  13878. and $ff/$ff/$ffff, reg
  13879. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13880. dealloc reg
  13881. to
  13882. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13883. }
  13884. begin
  13885. TransferUsedRegs(TmpUsedRegs);
  13886. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13887. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13888. begin
  13889. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13890. case taicpu(p).oper[0]^.val of
  13891. $ff:
  13892. begin
  13893. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13894. taicpu(hp1).opsize:=S_B;
  13895. end;
  13896. $ffff:
  13897. begin
  13898. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13899. taicpu(hp1).opsize:=S_W;
  13900. end;
  13901. $ffffffff:
  13902. begin
  13903. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13904. taicpu(hp1).opsize:=S_L;
  13905. end;
  13906. else
  13907. Internalerror(2023030401);
  13908. end;
  13909. RemoveCurrentP(p);
  13910. Result := True;
  13911. Exit;
  13912. end;
  13913. end;
  13914. A_MOVZX:
  13915. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13916. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13917. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13918. (
  13919. (
  13920. (taicpu(p).opsize=S_W) and
  13921. (taicpu(hp1).opsize=S_BW)
  13922. ) or
  13923. (
  13924. (taicpu(p).opsize=S_L) and
  13925. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13926. )
  13927. {$ifdef x86_64}
  13928. or
  13929. (
  13930. (taicpu(p).opsize=S_Q) and
  13931. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13932. )
  13933. {$endif x86_64}
  13934. ) then
  13935. begin
  13936. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13937. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13938. ) or
  13939. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13940. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13941. then
  13942. begin
  13943. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13944. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13945. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13946. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13947. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13948. }
  13949. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13950. RemoveInstruction(hp1);
  13951. { See if there are other optimisations possible }
  13952. Continue;
  13953. end;
  13954. end;
  13955. A_SHL:
  13956. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13957. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13958. begin
  13959. {$ifopt R+}
  13960. {$define RANGE_WAS_ON}
  13961. {$R-}
  13962. {$endif}
  13963. { get length of potential and mask }
  13964. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13965. { really a mask? }
  13966. {$ifdef RANGE_WAS_ON}
  13967. {$R+}
  13968. {$endif}
  13969. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13970. { unmasked part shifted out? }
  13971. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13972. begin
  13973. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13974. RemoveCurrentP(p, hp1);
  13975. Result:=true;
  13976. exit;
  13977. end;
  13978. end;
  13979. A_SHR:
  13980. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13981. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13982. (taicpu(hp1).oper[0]^.val <= 63) then
  13983. begin
  13984. { Does SHR combined with the AND cover all the bits?
  13985. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13986. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13987. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13988. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13989. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13990. begin
  13991. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13992. RemoveCurrentP(p, hp1);
  13993. Result := True;
  13994. Exit;
  13995. end;
  13996. end;
  13997. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13998. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13999. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14000. begin
  14001. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14002. (
  14003. (
  14004. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  14005. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  14006. ) or (
  14007. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  14008. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  14009. {$ifdef x86_64}
  14010. ) or (
  14011. (taicpu(hp1).opsize = S_LQ) and
  14012. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  14013. {$endif x86_64}
  14014. )
  14015. ) then
  14016. begin
  14017. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  14018. begin
  14019. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  14020. RemoveInstruction(hp1);
  14021. { See if there are other optimisations possible }
  14022. Continue;
  14023. end;
  14024. { The super-registers are the same though.
  14025. Note that this change by itself doesn't improve
  14026. code speed, but it opens up other optimisations. }
  14027. {$ifdef x86_64}
  14028. { Convert 64-bit register to 32-bit }
  14029. case taicpu(hp1).opsize of
  14030. S_BQ:
  14031. begin
  14032. taicpu(hp1).opsize := S_BL;
  14033. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14034. end;
  14035. S_WQ:
  14036. begin
  14037. taicpu(hp1).opsize := S_WL;
  14038. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14039. end
  14040. else
  14041. ;
  14042. end;
  14043. {$endif x86_64}
  14044. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  14045. taicpu(hp1).opcode := A_MOVZX;
  14046. { See if there are other optimisations possible }
  14047. Continue;
  14048. end;
  14049. end;
  14050. else
  14051. ;
  14052. end;
  14053. end
  14054. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  14055. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14056. begin
  14057. {$ifdef x86_64}
  14058. if (taicpu(p).opsize = S_Q) then
  14059. begin
  14060. { Never necessary }
  14061. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  14062. RemoveCurrentP(p, hp1);
  14063. Result := True;
  14064. Exit;
  14065. end;
  14066. {$endif x86_64}
  14067. { Forward check to determine necessity of and %reg,%reg }
  14068. TransferUsedRegs(TmpUsedRegs);
  14069. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14070. { Saves on a bunch of dereferences }
  14071. ActiveReg := taicpu(p).oper[1]^.reg;
  14072. case taicpu(hp1).opcode of
  14073. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14074. if (
  14075. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14076. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14077. ) and
  14078. (
  14079. (taicpu(hp1).opcode <> A_MOV) or
  14080. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  14081. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  14082. ) and
  14083. not (
  14084. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  14085. (taicpu(hp1).opcode = A_MOV) and
  14086. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  14087. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  14088. ) and
  14089. (
  14090. (
  14091. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14092. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  14093. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  14094. ) or
  14095. (
  14096. {$ifdef x86_64}
  14097. (
  14098. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  14099. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  14100. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  14101. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  14102. ) and
  14103. {$endif x86_64}
  14104. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  14105. )
  14106. ) then
  14107. begin
  14108. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  14109. RemoveCurrentP(p, hp1);
  14110. Result := True;
  14111. Exit;
  14112. end;
  14113. A_ADD,
  14114. A_AND,
  14115. A_BSF,
  14116. A_BSR,
  14117. A_BTC,
  14118. A_BTR,
  14119. A_BTS,
  14120. A_OR,
  14121. A_SUB,
  14122. A_XOR:
  14123. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  14124. if (
  14125. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14126. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14127. ) and
  14128. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  14129. begin
  14130. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  14131. RemoveCurrentP(p, hp1);
  14132. Result := True;
  14133. Exit;
  14134. end;
  14135. A_CMP,
  14136. A_TEST:
  14137. if (
  14138. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14139. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14140. ) and
  14141. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  14142. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  14143. begin
  14144. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  14145. RemoveCurrentP(p, hp1);
  14146. Result := True;
  14147. Exit;
  14148. end;
  14149. A_BSWAP,
  14150. A_NEG,
  14151. A_NOT:
  14152. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  14153. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  14154. begin
  14155. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  14156. RemoveCurrentP(p, hp1);
  14157. Result := True;
  14158. Exit;
  14159. end;
  14160. else
  14161. ;
  14162. end;
  14163. end;
  14164. if (taicpu(hp1).is_jmp) and
  14165. (taicpu(hp1).opcode<>A_JMP) and
  14166. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  14167. begin
  14168. { change
  14169. and x, reg
  14170. jxx
  14171. to
  14172. test x, reg
  14173. jxx
  14174. if reg is deallocated before the
  14175. jump, but only if it's a conditional jump (PFV)
  14176. }
  14177. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  14178. taicpu(p).opcode := A_TEST;
  14179. Exit;
  14180. end;
  14181. Break;
  14182. end;
  14183. { Lone AND tests }
  14184. if (taicpu(p).oper[0]^.typ = top_const) then
  14185. begin
  14186. {
  14187. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  14188. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  14189. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  14190. }
  14191. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  14192. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  14193. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  14194. begin
  14195. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  14196. if taicpu(p).opsize = S_L then
  14197. begin
  14198. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  14199. Result := True;
  14200. end;
  14201. end;
  14202. end;
  14203. { Backward check to determine necessity of and %reg,%reg }
  14204. if (taicpu(p).oper[0]^.typ = top_reg) and
  14205. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  14206. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14207. GetLastInstruction(p, hp2) and
  14208. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  14209. { Check size of adjacent instruction to determine if the AND is
  14210. effectively a null operation }
  14211. (
  14212. (taicpu(p).opsize = taicpu(hp2).opsize) or
  14213. { Note: Don't include S_Q }
  14214. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  14215. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  14216. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  14217. ) then
  14218. begin
  14219. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  14220. { If GetNextInstruction returned False, hp1 will be nil }
  14221. RemoveCurrentP(p, hp1);
  14222. Result := True;
  14223. Exit;
  14224. end;
  14225. end;
  14226. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14227. var
  14228. hp1, hp2: tai;
  14229. NewRef: TReference;
  14230. Distance: Cardinal;
  14231. TempTracking: TAllUsedRegs;
  14232. DoAddMov2Lea: Boolean;
  14233. { This entire nested function is used in an if-statement below, but we
  14234. want to avoid all the used reg transfers and GetNextInstruction calls
  14235. until we really have to check }
  14236. function MemRegisterNotUsedLater: Boolean; inline;
  14237. var
  14238. hp2: tai;
  14239. begin
  14240. TransferUsedRegs(TmpUsedRegs);
  14241. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14242. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14243. else
  14244. { p and hp1 will be adjacent }
  14245. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14246. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14247. end;
  14248. begin
  14249. Result := False;
  14250. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14251. (taicpu(p).oper[1]^.typ = top_reg) then
  14252. begin
  14253. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14254. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14255. (hp1.typ <> ait_instruction) or
  14256. not
  14257. (
  14258. (cs_opt_level3 in current_settings.optimizerswitches) or
  14259. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14260. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14261. ) then
  14262. Exit;
  14263. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14264. addq $x, %rax
  14265. movq %rax, %rdx
  14266. sarq $63, %rdx
  14267. (%rax still in use)
  14268. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14269. leaq $x(%rax),%rdx
  14270. addq $x, %rax
  14271. sarq $63, %rdx
  14272. ...which is okay since it breaks the dependency chain between
  14273. addq and movq, but if OptPass2MOV is called first:
  14274. addq $x, %rax
  14275. cqto
  14276. ...which is better in all ways, taking only 2 cycles to execute
  14277. and much smaller in code size.
  14278. }
  14279. { The extra register tracking is quite strenuous }
  14280. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14281. MatchInstruction(hp1, A_MOV, []) then
  14282. begin
  14283. { Update the register tracking to the MOV instruction }
  14284. CopyUsedRegs(TempTracking);
  14285. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14286. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14287. else
  14288. { p and hp1 will be adjacent }
  14289. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14290. hp2 := hp1;
  14291. if OptPass2MOV(hp1) then
  14292. Include(OptsToCheck, aoc_ForceNewIteration);
  14293. { Reset the tracking to the current instruction }
  14294. RestoreUsedRegs(TempTracking);
  14295. ReleaseUsedRegs(TempTracking);
  14296. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14297. OptPass2ADD get called again }
  14298. if (hp1 <> hp2) then
  14299. begin
  14300. Result := True;
  14301. Exit;
  14302. end;
  14303. end;
  14304. { Change:
  14305. add %reg2,%reg1
  14306. (%reg2 not modified in between)
  14307. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14308. To:
  14309. mov/s/z #(%reg1,%reg2),%reg1
  14310. }
  14311. if (taicpu(p).oper[0]^.typ = top_reg) and
  14312. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14313. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14314. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14315. (
  14316. (
  14317. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14318. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14319. { r/esp cannot be an index }
  14320. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14321. ) or (
  14322. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14323. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14324. )
  14325. ) and (
  14326. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14327. (
  14328. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14329. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14330. MemRegisterNotUsedLater
  14331. )
  14332. ) then
  14333. begin
  14334. if (
  14335. { Instructions are guaranteed to be adjacent on -O2 and under }
  14336. (cs_opt_level3 in current_settings.optimizerswitches) and
  14337. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14338. ) then
  14339. begin
  14340. { If the other register is used in between, move the MOV
  14341. instruction to right after the ADD instruction so a
  14342. saving can still be made }
  14343. Asml.Remove(hp1);
  14344. Asml.InsertAfter(hp1, p);
  14345. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14346. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14347. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14348. RemoveCurrentp(p, hp1);
  14349. end
  14350. else
  14351. begin
  14352. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14353. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14354. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14355. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14356. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14357. { hp1 may not be the immediate next instruction under -O3 }
  14358. RemoveCurrentp(p)
  14359. else
  14360. RemoveCurrentp(p, hp1);
  14361. end;
  14362. Result := True;
  14363. Exit;
  14364. end;
  14365. { Change:
  14366. addl/q $x,%reg1
  14367. movl/q %reg1,%reg2
  14368. To:
  14369. leal/q $x(%reg1),%reg2
  14370. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14371. Breaks the dependency chain.
  14372. }
  14373. if (taicpu(p).oper[0]^.typ = top_const) and
  14374. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14375. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14376. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14377. (
  14378. { Instructions are guaranteed to be adjacent on -O2 and under }
  14379. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14380. (
  14381. { If the flags are used, don't make the optimisation,
  14382. otherwise they will be scrambled. Fixes #41148 }
  14383. (
  14384. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14385. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14386. ) and
  14387. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14388. )
  14389. ) then
  14390. begin
  14391. TransferUsedRegs(TmpUsedRegs);
  14392. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14393. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14394. else
  14395. { p and hp1 will be adjacent }
  14396. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14397. if (
  14398. SetAndTest(
  14399. (
  14400. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14401. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14402. ),
  14403. DoAddMov2Lea
  14404. ) or
  14405. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14406. not (cs_opt_size in current_settings.optimizerswitches)
  14407. ) then
  14408. begin
  14409. { Change the MOV instruction to a LEA instruction, and update the
  14410. first operand }
  14411. reference_reset(NewRef, 1, []);
  14412. NewRef.base := taicpu(p).oper[1]^.reg;
  14413. NewRef.scalefactor := 1;
  14414. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14415. taicpu(hp1).opcode := A_LEA;
  14416. taicpu(hp1).loadref(0, NewRef);
  14417. if DoAddMov2Lea then
  14418. begin
  14419. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14420. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14421. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14422. { hp1 may not be the immediate next instruction under -O3 }
  14423. RemoveCurrentp(p)
  14424. else
  14425. RemoveCurrentp(p, hp1);
  14426. end
  14427. else
  14428. begin
  14429. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14430. { Move what is now the LEA instruction to before the ADD instruction }
  14431. Asml.Remove(hp1);
  14432. Asml.InsertBefore(hp1, p);
  14433. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14434. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14435. p := hp1;
  14436. end;
  14437. Result := True;
  14438. end;
  14439. end;
  14440. end;
  14441. end;
  14442. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14443. var
  14444. SubReg: TSubRegister;
  14445. hp1, hp2: tai;
  14446. CallJmp: Boolean;
  14447. begin
  14448. Result := False;
  14449. CallJmp := False;
  14450. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14451. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14452. with taicpu(p).oper[0]^.ref^ do
  14453. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14454. if (offset = 0) then
  14455. begin
  14456. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14457. begin
  14458. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14459. taicpu(p).opcode := A_ADD;
  14460. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14461. Result := True;
  14462. end
  14463. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14464. begin
  14465. if (base <> NR_NO) then
  14466. begin
  14467. if (scalefactor <= 1) then
  14468. begin
  14469. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14470. taicpu(p).opcode := A_ADD;
  14471. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14472. Result := True;
  14473. end;
  14474. end
  14475. else
  14476. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14477. if (scalefactor in [2, 4, 8]) then
  14478. begin
  14479. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14480. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14481. taicpu(p).opcode := A_SHL;
  14482. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14483. Result := True;
  14484. end;
  14485. end;
  14486. end
  14487. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14488. lot of latency, so break off the offset if %reg3 is used soon
  14489. afterwards }
  14490. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14491. { If 3-component addresses don't have additional latency, don't
  14492. perform this optimisation }
  14493. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14494. GetNextInstruction(p, hp1) and
  14495. (hp1.typ = ait_instruction) and
  14496. (
  14497. (
  14498. { Permit jumps and calls since they have a larger degree of overhead }
  14499. (
  14500. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14501. (
  14502. { ... unless the register specifies the location }
  14503. (taicpu(hp1).ops > 0) and
  14504. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14505. )
  14506. ) and
  14507. (
  14508. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14509. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14510. )
  14511. )
  14512. or
  14513. (
  14514. { Check up to two instructions ahead }
  14515. GetNextInstruction(hp1, hp2) and
  14516. (hp2.typ = ait_instruction) and
  14517. (
  14518. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14519. (
  14520. { Same as above }
  14521. (taicpu(hp2).ops > 0) and
  14522. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14523. )
  14524. ) and
  14525. (
  14526. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14527. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14528. )
  14529. )
  14530. ) then
  14531. begin
  14532. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14533. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14534. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14535. offset := 0;
  14536. if Assigned(symbol) or Assigned(relsymbol) then
  14537. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14538. else
  14539. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14540. { Inserting before the next instruction rather than after the
  14541. current instruction gives more accurate register tracking }
  14542. asml.InsertBefore(hp2, hp1);
  14543. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14544. Result := True;
  14545. end;
  14546. end;
  14547. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14548. var
  14549. hp1, hp2: tai;
  14550. NewRef: TReference;
  14551. Distance: Cardinal;
  14552. TempTracking: TAllUsedRegs;
  14553. DoSubMov2Lea: Boolean;
  14554. begin
  14555. Result := False;
  14556. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14557. MatchOpType(taicpu(p),top_const,top_reg) then
  14558. begin
  14559. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14560. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14561. (hp1.typ <> ait_instruction) or
  14562. not
  14563. (
  14564. (cs_opt_level3 in current_settings.optimizerswitches) or
  14565. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14566. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14567. ) then
  14568. Exit;
  14569. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14570. subq $x, %rax
  14571. movq %rax, %rdx
  14572. sarq $63, %rdx
  14573. (%rax still in use)
  14574. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14575. leaq $-x(%rax),%rdx
  14576. movq $x, %rax
  14577. sarq $63, %rdx
  14578. ...which is okay since it breaks the dependency chain between
  14579. subq and movq, but if OptPass2MOV is called first:
  14580. subq $x, %rax
  14581. cqto
  14582. ...which is better in all ways, taking only 2 cycles to execute
  14583. and much smaller in code size.
  14584. }
  14585. { The extra register tracking is quite strenuous }
  14586. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14587. MatchInstruction(hp1, A_MOV, []) then
  14588. begin
  14589. { Update the register tracking to the MOV instruction }
  14590. CopyUsedRegs(TempTracking);
  14591. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14592. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14593. else
  14594. { p and hp1 will be adjacent }
  14595. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14596. hp2 := hp1;
  14597. if OptPass2MOV(hp1) then
  14598. Include(OptsToCheck, aoc_ForceNewIteration);
  14599. { Reset the tracking to the current instruction }
  14600. RestoreUsedRegs(TempTracking);
  14601. ReleaseUsedRegs(TempTracking);
  14602. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14603. OptPass2SUB get called again }
  14604. if (hp1 <> hp2) then
  14605. begin
  14606. Result := True;
  14607. Exit;
  14608. end;
  14609. end;
  14610. { Change:
  14611. subl/q $x,%reg1
  14612. movl/q %reg1,%reg2
  14613. To:
  14614. leal/q $-x(%reg1),%reg2
  14615. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14616. Breaks the dependency chain and potentially permits the removal of
  14617. a CMP instruction if one follows.
  14618. }
  14619. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14620. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14621. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14622. (
  14623. { Instructions are guaranteed to be adjacent on -O2 and under }
  14624. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14625. (
  14626. { If the flags are used, don't make the optimisation,
  14627. otherwise they will be scrambled. Fixes #41148 }
  14628. (
  14629. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14630. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14631. ) and
  14632. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14633. )
  14634. ) then
  14635. begin
  14636. TransferUsedRegs(TmpUsedRegs);
  14637. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14638. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14639. else
  14640. { p and hp1 will be adjacent }
  14641. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14642. if (
  14643. SetAndTest(
  14644. (
  14645. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14646. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14647. ),
  14648. DoSubMov2Lea
  14649. ) or
  14650. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14651. not (cs_opt_size in current_settings.optimizerswitches)
  14652. ) then
  14653. begin
  14654. { Change the MOV instruction to a LEA instruction, and update the
  14655. first operand }
  14656. reference_reset(NewRef, 1, []);
  14657. NewRef.base := taicpu(p).oper[1]^.reg;
  14658. NewRef.scalefactor := 1;
  14659. NewRef.offset := -taicpu(p).oper[0]^.val;
  14660. taicpu(hp1).opcode := A_LEA;
  14661. taicpu(hp1).loadref(0, NewRef);
  14662. if DoSubMov2Lea then
  14663. begin
  14664. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14665. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14666. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14667. { hp1 may not be the immediate next instruction under -O3 }
  14668. RemoveCurrentp(p)
  14669. else
  14670. RemoveCurrentp(p, hp1);
  14671. end
  14672. else
  14673. begin
  14674. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14675. { Move what is now the LEA instruction to before the SUB instruction }
  14676. Asml.Remove(hp1);
  14677. Asml.InsertBefore(hp1, p);
  14678. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14679. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14680. p := hp1;
  14681. end;
  14682. Result := True;
  14683. end;
  14684. end;
  14685. end;
  14686. end;
  14687. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14688. begin
  14689. { we can skip all instructions not messing with the stack pointer }
  14690. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14691. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14692. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14693. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14694. ({(taicpu(hp1).ops=0) or }
  14695. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14696. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14697. ) and }
  14698. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14699. )
  14700. ) do
  14701. GetNextInstruction(hp1,hp1);
  14702. Result:=assigned(hp1);
  14703. end;
  14704. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14705. var
  14706. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14707. begin
  14708. Result:=false;
  14709. hp5:=nil;
  14710. hp6:=nil;
  14711. hp7:=nil;
  14712. hp8:=nil;
  14713. { replace
  14714. leal(q) x(<stackpointer>),<stackpointer>
  14715. <optional .seh_stackalloc ...>
  14716. <optional .seh_endprologue ...>
  14717. call procname
  14718. <optional NOP>
  14719. leal(q) -x(<stackpointer>),<stackpointer>
  14720. <optional VZEROUPPER>
  14721. ret
  14722. by
  14723. jmp procname
  14724. but do it only on level 4 because it destroys stack back traces
  14725. }
  14726. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14727. MatchOpType(taicpu(p),top_ref,top_reg) and
  14728. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14729. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14730. { the -8, -24, -40 are not required, but bail out early if possible,
  14731. higher values are unlikely }
  14732. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14733. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14734. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14735. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14736. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14737. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14738. GetNextInstruction(p, hp1) and
  14739. { Take a copy of hp1 }
  14740. SetAndTest(hp1, hp4) and
  14741. { trick to skip label }
  14742. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14743. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14744. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14745. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14746. SkipSimpleInstructions(hp1) and
  14747. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14748. GetNextInstruction(hp1, hp2) and
  14749. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14750. { skip nop instruction on win64 }
  14751. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14752. SetAndTest(hp2,hp6) and
  14753. GetNextInstruction(hp2,hp2) and
  14754. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14755. ) and
  14756. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14757. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14758. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14759. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14760. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14761. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14762. { Segment register will be NR_NO }
  14763. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14764. GetNextInstruction(hp2, hp3) and
  14765. { trick to skip label }
  14766. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14767. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14768. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14769. SetAndTest(hp3,hp5) and
  14770. GetNextInstruction(hp3,hp3) and
  14771. MatchInstruction(hp3,A_RET,[S_NO])
  14772. )
  14773. ) and
  14774. (taicpu(hp3).ops=0) then
  14775. begin
  14776. taicpu(hp1).opcode := A_JMP;
  14777. taicpu(hp1).is_jmp := true;
  14778. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14779. { search for the stackalloc directive and remove it }
  14780. hp7:=tai(p.next);
  14781. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14782. begin
  14783. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14784. begin
  14785. { sanity check }
  14786. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14787. Internalerror(2024012201);
  14788. hp8:=tai(hp7.next);
  14789. RemoveInstruction(tai(hp7));
  14790. hp7:=hp8;
  14791. break;
  14792. end
  14793. else
  14794. hp7:=tai(hp7.next);
  14795. end;
  14796. RemoveCurrentP(p, hp4);
  14797. RemoveInstruction(hp2);
  14798. RemoveInstruction(hp3);
  14799. { if there is a vzeroupper instruction then move it before the jmp }
  14800. if Assigned(hp5) then
  14801. begin
  14802. AsmL.Remove(hp5);
  14803. ASmL.InsertBefore(hp5,hp1)
  14804. end;
  14805. { remove nop on win64 }
  14806. if Assigned(hp6) then
  14807. RemoveInstruction(hp6);
  14808. Result:=true;
  14809. end;
  14810. end;
  14811. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14812. {$ifdef x86_64}
  14813. var
  14814. hp1, hp2, hp3, hp4, hp5: tai;
  14815. {$endif x86_64}
  14816. begin
  14817. Result:=false;
  14818. {$ifdef x86_64}
  14819. hp5:=nil;
  14820. { replace
  14821. push %rax
  14822. call procname
  14823. pop %rcx
  14824. ret
  14825. by
  14826. jmp procname
  14827. but do it only on level 4 because it destroys stack back traces
  14828. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14829. for all supported calling conventions
  14830. }
  14831. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14832. MatchOpType(taicpu(p),top_reg) and
  14833. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14834. GetNextInstruction(p, hp1) and
  14835. { Take a copy of hp1 }
  14836. SetAndTest(hp1, hp4) and
  14837. { trick to skip label }
  14838. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14839. SkipSimpleInstructions(hp1) and
  14840. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14841. GetNextInstruction(hp1, hp2) and
  14842. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14843. MatchOpType(taicpu(hp2),top_reg) and
  14844. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14845. GetNextInstruction(hp2, hp3) and
  14846. { trick to skip label }
  14847. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14848. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14849. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14850. SetAndTest(hp3,hp5) and
  14851. GetNextInstruction(hp3,hp3) and
  14852. MatchInstruction(hp3,A_RET,[S_NO])
  14853. )
  14854. ) and
  14855. (taicpu(hp3).ops=0) then
  14856. begin
  14857. taicpu(hp1).opcode := A_JMP;
  14858. taicpu(hp1).is_jmp := true;
  14859. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14860. RemoveCurrentP(p, hp4);
  14861. RemoveInstruction(hp2);
  14862. RemoveInstruction(hp3);
  14863. if Assigned(hp5) then
  14864. begin
  14865. AsmL.Remove(hp5);
  14866. ASmL.InsertBefore(hp5,hp1)
  14867. end;
  14868. Result:=true;
  14869. end;
  14870. {$endif x86_64}
  14871. end;
  14872. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14873. var
  14874. Value, RegName: string;
  14875. hp1: tai;
  14876. begin
  14877. Result:=false;
  14878. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14879. begin
  14880. case taicpu(p).oper[0]^.val of
  14881. 0:
  14882. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14883. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14884. (
  14885. { See if we can still convert the instruction }
  14886. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14887. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14888. ) then
  14889. begin
  14890. { change "mov $0,%reg" into "xor %reg,%reg" }
  14891. taicpu(p).opcode := A_XOR;
  14892. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14893. Result := True;
  14894. {$ifdef x86_64}
  14895. end
  14896. else if (taicpu(p).opsize = S_Q) then
  14897. begin
  14898. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14899. { The actual optimization }
  14900. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14901. taicpu(p).changeopsize(S_L);
  14902. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14903. Result := True;
  14904. end;
  14905. $1..$FFFFFFFF:
  14906. begin
  14907. { Code size reduction by J. Gareth "Kit" Moreton }
  14908. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14909. case taicpu(p).opsize of
  14910. S_Q:
  14911. begin
  14912. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14913. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14914. { The actual optimization }
  14915. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14916. taicpu(p).changeopsize(S_L);
  14917. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14918. Result := True;
  14919. end;
  14920. else
  14921. { Do nothing };
  14922. end;
  14923. {$endif x86_64}
  14924. end;
  14925. -1:
  14926. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14927. if (cs_opt_size in current_settings.optimizerswitches) and
  14928. (taicpu(p).opsize <> S_B) and
  14929. (
  14930. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14931. (
  14932. { See if we can still convert the instruction }
  14933. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14934. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14935. )
  14936. ) then
  14937. begin
  14938. { change "mov $-1,%reg" into "or $-1,%reg" }
  14939. { NOTES:
  14940. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14941. - This operation creates a false dependency on the register, so only do it when optimising for size
  14942. - 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
  14943. }
  14944. taicpu(p).opcode := A_OR;
  14945. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14946. Result := True;
  14947. end;
  14948. else
  14949. { Do nothing };
  14950. end;
  14951. end;
  14952. end;
  14953. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14954. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14955. begin
  14956. Result := False;
  14957. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14958. Exit;
  14959. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14960. so don't bother optimising }
  14961. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14962. Exit;
  14963. if (taicpu(p).oper[0]^.typ <> top_const) or
  14964. { If the value can fit into an 8-bit signed integer, a smaller
  14965. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14966. falls within this range }
  14967. (
  14968. (taicpu(p).oper[0]^.val > -128) and
  14969. (taicpu(p).oper[0]^.val <= 127)
  14970. ) then
  14971. Exit;
  14972. { If we're optimising for size, this is acceptable }
  14973. if (cs_opt_size in current_settings.optimizerswitches) then
  14974. Exit(True);
  14975. if (taicpu(p).oper[1]^.typ = top_reg) and
  14976. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14977. Exit(True);
  14978. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14979. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14980. Exit(True);
  14981. end;
  14982. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14983. var
  14984. hp1: tai;
  14985. Value: TCGInt;
  14986. begin
  14987. Result := False;
  14988. if MatchOpType(taicpu(p), top_const, top_reg) then
  14989. begin
  14990. { Detect:
  14991. andw x, %ax (0 <= x < $8000)
  14992. ...
  14993. movzwl %ax,%eax
  14994. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14995. }
  14996. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14997. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14998. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14999. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  15000. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  15001. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  15002. begin
  15003. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  15004. taicpu(hp1).opcode := A_CWDE;
  15005. taicpu(hp1).clearop(0);
  15006. taicpu(hp1).clearop(1);
  15007. taicpu(hp1).ops := 0;
  15008. { A change was made, but not with p, so don't set Result, but
  15009. notify the compiler that a change was made }
  15010. Include(OptsToCheck, aoc_ForceNewIteration);
  15011. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  15012. end;
  15013. end;
  15014. { If "not x" is a power of 2 (popcnt = 1), change:
  15015. and $x, %reg/ref
  15016. To:
  15017. btr lb(x), %reg/ref
  15018. }
  15019. if IsBTXAcceptable(p) and
  15020. (
  15021. { Make sure a TEST doesn't follow that plays with the register }
  15022. not GetNextInstruction(p, hp1) or
  15023. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  15024. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  15025. ) then
  15026. begin
  15027. {$push}{$R-}{$Q-}
  15028. { Value is a sign-extended 32-bit integer - just correct it
  15029. if it's represented as an unsigned value. Also, IsBTXAcceptable
  15030. checks to see if this operand is an immediate. }
  15031. Value := not taicpu(p).oper[0]^.val;
  15032. {$pop}
  15033. {$ifdef x86_64}
  15034. if taicpu(p).opsize = S_L then
  15035. {$endif x86_64}
  15036. Value := Value and $FFFFFFFF;
  15037. if (PopCnt(QWord(Value)) = 1) then
  15038. begin
  15039. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  15040. taicpu(p).opcode := A_BTR;
  15041. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  15042. Result := True;
  15043. Exit;
  15044. end;
  15045. end;
  15046. end;
  15047. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  15048. begin
  15049. Result := False;
  15050. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  15051. Exit;
  15052. { Convert:
  15053. movswl %ax,%eax -> cwtl
  15054. movslq %eax,%rax -> cdqe
  15055. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  15056. refer to the same opcode and depends only on the assembler's
  15057. current operand-size attribute. [Kit]
  15058. }
  15059. with taicpu(p) do
  15060. case opsize of
  15061. S_WL:
  15062. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  15063. begin
  15064. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  15065. opcode := A_CWDE;
  15066. clearop(0);
  15067. clearop(1);
  15068. ops := 0;
  15069. Result := True;
  15070. end;
  15071. {$ifdef x86_64}
  15072. S_LQ:
  15073. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  15074. begin
  15075. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  15076. opcode := A_CDQE;
  15077. clearop(0);
  15078. clearop(1);
  15079. ops := 0;
  15080. Result := True;
  15081. end;
  15082. {$endif x86_64}
  15083. else
  15084. ;
  15085. end;
  15086. end;
  15087. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  15088. var
  15089. hp1: tai;
  15090. begin
  15091. Result := False;
  15092. { All these optimisations work on "shr const,%reg" }
  15093. if not MatchOpType(taicpu(p), top_const, top_reg) then
  15094. Exit;
  15095. if HandleSHRMerge(p, True) then
  15096. begin
  15097. Result := True;
  15098. Exit;
  15099. end;
  15100. { Detect the following (looking backwards):
  15101. shr %cl,%reg
  15102. shr x, %reg
  15103. Swap the two SHR instructions to minimise a pipeline stall.
  15104. }
  15105. if GetLastInstruction(p, hp1) and
  15106. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15107. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15108. { First operand will be %cl }
  15109. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15110. { Just to be sure }
  15111. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15112. begin
  15113. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15114. { Moving the entries this way ensures the register tracking remains correct }
  15115. Asml.Remove(p);
  15116. Asml.InsertBefore(p, hp1);
  15117. p := hp1;
  15118. { Don't set Result to True because the current instruction is now
  15119. "shr %cl,%reg" and there's nothing more we can do with it }
  15120. end;
  15121. end;
  15122. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15123. var
  15124. hp1, hp2: tai;
  15125. Opposite, SecondOpposite: TAsmOp;
  15126. NewCond: TAsmCond;
  15127. begin
  15128. Result := False;
  15129. { Change:
  15130. add/sub 128,(dest)
  15131. To:
  15132. sub/add -128,(dest)
  15133. This generaally takes fewer bytes to encode because -128 can be stored
  15134. in a signed byte, whereas +128 cannot.
  15135. }
  15136. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15137. begin
  15138. if taicpu(p).opcode = A_ADD then
  15139. Opposite := A_SUB
  15140. else
  15141. Opposite := A_ADD;
  15142. { Be careful if the flags are in use, because the CF flag inverts
  15143. when changing from ADD to SUB and vice versa }
  15144. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15145. GetNextInstruction(p, hp1) then
  15146. begin
  15147. TransferUsedRegs(TmpUsedRegs);
  15148. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15149. hp2 := hp1;
  15150. { Scan ahead to check if everything's safe }
  15151. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15152. begin
  15153. if (hp1.typ <> ait_instruction) then
  15154. { Probably unsafe since the flags are still in use }
  15155. Exit;
  15156. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15157. { Stop searching at an unconditional jump }
  15158. Break;
  15159. if not
  15160. (
  15161. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15162. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15163. ) and
  15164. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15165. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15166. Exit;
  15167. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15168. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15169. { Move to the next instruction }
  15170. GetNextInstruction(hp1, hp1);
  15171. end;
  15172. while Assigned(hp2) and (hp2 <> hp1) do
  15173. begin
  15174. NewCond := C_None;
  15175. case taicpu(hp2).condition of
  15176. C_A, C_NBE:
  15177. NewCond := C_BE;
  15178. C_B, C_C, C_NAE:
  15179. NewCond := C_AE;
  15180. C_AE, C_NB, C_NC:
  15181. NewCond := C_B;
  15182. C_BE, C_NA:
  15183. NewCond := C_A;
  15184. else
  15185. { No change needed };
  15186. end;
  15187. if NewCond <> C_None then
  15188. begin
  15189. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15190. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15191. taicpu(hp2).condition := NewCond;
  15192. end
  15193. else
  15194. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15195. begin
  15196. { Because of the flipping of the carry bit, to ensure
  15197. the operation remains equivalent, ADC becomes SBB
  15198. and vice versa, and the constant is not-inverted.
  15199. If multiple ADCs or SBBs appear in a row, each one
  15200. changed causes the carry bit to invert, so they all
  15201. need to be flipped }
  15202. if taicpu(hp2).opcode = A_ADC then
  15203. SecondOpposite := A_SBB
  15204. else
  15205. SecondOpposite := A_ADC;
  15206. if taicpu(hp2).oper[0]^.typ <> top_const then
  15207. { Should have broken out of this optimisation already }
  15208. InternalError(2021112901);
  15209. 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]^) + ' -> ' +
  15210. 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);
  15211. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15212. taicpu(hp2).opcode := SecondOpposite;
  15213. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15214. end;
  15215. { Move to the next instruction }
  15216. GetNextInstruction(hp2, hp2);
  15217. end;
  15218. if (hp2 <> hp1) then
  15219. InternalError(2021111501);
  15220. end;
  15221. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15222. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15223. taicpu(p).opcode := Opposite;
  15224. taicpu(p).oper[0]^.val := -128;
  15225. { No further optimisations can be made on this instruction, so move
  15226. onto the next one to save time }
  15227. p := tai(p.Next);
  15228. UpdateUsedRegs(p);
  15229. Result := True;
  15230. Exit;
  15231. end;
  15232. { Detect:
  15233. add/sub %reg2,(dest)
  15234. add/sub x, (dest)
  15235. (dest can be a register or a reference)
  15236. Swap the instructions to minimise a pipeline stall. This reverses the
  15237. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15238. optimisations could be made.
  15239. }
  15240. if (taicpu(p).oper[0]^.typ = top_reg) and
  15241. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15242. (
  15243. (
  15244. (taicpu(p).oper[1]^.typ = top_reg) and
  15245. { We can try searching further ahead if we're writing to a register }
  15246. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15247. ) or
  15248. (
  15249. (taicpu(p).oper[1]^.typ = top_ref) and
  15250. GetNextInstruction(p, hp1)
  15251. )
  15252. ) and
  15253. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15254. (taicpu(hp1).oper[0]^.typ = top_const) and
  15255. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15256. begin
  15257. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15258. TransferUsedRegs(TmpUsedRegs);
  15259. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15260. hp2 := p;
  15261. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15262. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15263. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15264. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15265. begin
  15266. asml.remove(hp1);
  15267. asml.InsertBefore(hp1, p);
  15268. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15269. Result := True;
  15270. end;
  15271. end;
  15272. end;
  15273. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15274. var
  15275. hp1: tai;
  15276. begin
  15277. Result:=false;
  15278. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15279. while GetNextInstruction(p, hp1) and
  15280. TrySwapMovCmp(p, hp1) do
  15281. begin
  15282. if MatchInstruction(hp1, A_MOV, []) then
  15283. begin
  15284. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15285. begin
  15286. { A little hacky, but since CMP doesn't read the flags, only
  15287. modify them, it's safe if they get scrambled by MOV -> XOR }
  15288. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15289. Result := PostPeepholeOptMov(hp1);
  15290. {$ifdef x86_64}
  15291. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15292. { Used to shrink instruction size }
  15293. PostPeepholeOptXor(hp1);
  15294. {$endif x86_64}
  15295. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15296. end
  15297. else
  15298. begin
  15299. Result := PostPeepholeOptMov(hp1);
  15300. {$ifdef x86_64}
  15301. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15302. { Used to shrink instruction size }
  15303. PostPeepholeOptXor(hp1);
  15304. {$endif x86_64}
  15305. end;
  15306. end;
  15307. { Enabling this flag is actually a null operation, but it marks
  15308. the code as 'modified' during this pass }
  15309. Include(OptsToCheck, aoc_ForceNewIteration);
  15310. end;
  15311. { change "cmp $0, %reg" to "test %reg, %reg" }
  15312. if MatchOpType(taicpu(p),top_const,top_reg) and
  15313. (taicpu(p).oper[0]^.val = 0) then
  15314. begin
  15315. taicpu(p).opcode := A_TEST;
  15316. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15317. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15318. Result:=true;
  15319. end;
  15320. end;
  15321. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15322. var
  15323. IsTestConstX, IsValid : Boolean;
  15324. hp1,hp2 : tai;
  15325. begin
  15326. Result:=false;
  15327. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15328. if (taicpu(p).opcode = A_TEST) then
  15329. while GetNextInstruction(p, hp1) and
  15330. TrySwapMovCmp(p, hp1) do
  15331. begin
  15332. if MatchInstruction(hp1, A_MOV, []) then
  15333. begin
  15334. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15335. begin
  15336. { A little hacky, but since TEST doesn't read the flags, only
  15337. modify them, it's safe if they get scrambled by MOV -> XOR }
  15338. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15339. Result := PostPeepholeOptMov(hp1);
  15340. {$ifdef x86_64}
  15341. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15342. { Used to shrink instruction size }
  15343. PostPeepholeOptXor(hp1);
  15344. {$endif x86_64}
  15345. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15346. end
  15347. else
  15348. begin
  15349. Result := PostPeepholeOptMov(hp1);
  15350. {$ifdef x86_64}
  15351. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15352. { Used to shrink instruction size }
  15353. PostPeepholeOptXor(hp1);
  15354. {$endif x86_64}
  15355. end;
  15356. end;
  15357. { Enabling this flag is actually a null operation, but it marks
  15358. the code as 'modified' during this pass }
  15359. Include(OptsToCheck, aoc_ForceNewIteration);
  15360. end;
  15361. { If x is a power of 2 (popcnt = 1), change:
  15362. or $x, %reg/ref
  15363. To:
  15364. bts lb(x), %reg/ref
  15365. }
  15366. if (taicpu(p).opcode = A_OR) and
  15367. IsBTXAcceptable(p) and
  15368. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15369. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15370. (
  15371. { Don't optimise if a test instruction follows }
  15372. not GetNextInstruction(p, hp1) or
  15373. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15374. ) then
  15375. begin
  15376. 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);
  15377. taicpu(p).opcode := A_BTS;
  15378. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15379. Result := True;
  15380. Exit;
  15381. end;
  15382. { If x is a power of 2 (popcnt = 1), change:
  15383. test $x, %reg/ref
  15384. je / sete / cmove (or jne / setne)
  15385. To:
  15386. bt lb(x), %reg/ref
  15387. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15388. }
  15389. if (taicpu(p).opcode = A_TEST) and
  15390. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15391. (taicpu(p).oper[0]^.typ = top_const) and
  15392. (
  15393. (cs_opt_size in current_settings.optimizerswitches) or
  15394. (
  15395. (taicpu(p).oper[1]^.typ = top_reg) and
  15396. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15397. ) or
  15398. (
  15399. (taicpu(p).oper[1]^.typ <> top_reg) and
  15400. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15401. )
  15402. ) and
  15403. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15404. { For sizes less than S_L, the byte size is equal or larger with BT,
  15405. so don't bother optimising }
  15406. (taicpu(p).opsize >= S_L) then
  15407. begin
  15408. IsValid := True;
  15409. { Check the next set of instructions, watching the FLAGS register
  15410. and the conditions used }
  15411. TransferUsedRegs(TmpUsedRegs);
  15412. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15413. hp1 := p;
  15414. hp2 := nil;
  15415. while GetNextInstruction(hp1, hp1) do
  15416. begin
  15417. if not Assigned(hp2) then
  15418. { The first instruction after TEST }
  15419. hp2 := hp1;
  15420. if (hp1.typ <> ait_instruction) then
  15421. begin
  15422. { If the flags are no longer in use, everything is fine }
  15423. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15424. IsValid := False;
  15425. Break;
  15426. end;
  15427. case taicpu(hp1).condition of
  15428. C_None:
  15429. begin
  15430. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15431. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15432. { Something is not quite normal, so play safe and don't change }
  15433. IsValid := False;
  15434. Break;
  15435. end;
  15436. C_E, C_Z, C_NE, C_NZ:
  15437. { This is fine };
  15438. else
  15439. begin
  15440. { Unsupported condition }
  15441. IsValid := False;
  15442. Break;
  15443. end;
  15444. end;
  15445. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15446. end;
  15447. if IsValid then
  15448. begin
  15449. while hp2 <> hp1 do
  15450. begin
  15451. case taicpu(hp2).condition of
  15452. C_Z, C_E:
  15453. taicpu(hp2).condition := C_NC;
  15454. C_NZ, C_NE:
  15455. taicpu(hp2).condition := C_C;
  15456. else
  15457. { Should not get this by this point }
  15458. InternalError(2022110701);
  15459. end;
  15460. GetNextInstruction(hp2, hp2);
  15461. end;
  15462. 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);
  15463. taicpu(p).opcode := A_BT;
  15464. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15465. Result := True;
  15466. Exit;
  15467. end;
  15468. end;
  15469. { removes the line marked with (x) from the sequence
  15470. and/or/xor/add/sub/... $x, %y
  15471. test/or %y, %y | test $-1, %y (x)
  15472. j(n)z _Label
  15473. as the first instruction already adjusts the ZF
  15474. %y operand may also be a reference }
  15475. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15476. MatchOperand(taicpu(p).oper[0]^,-1);
  15477. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15478. GetLastInstruction(p, hp1) and
  15479. (tai(hp1).typ = ait_instruction) and
  15480. GetNextInstruction(p,hp2) and
  15481. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15482. case taicpu(hp1).opcode Of
  15483. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15484. { These two instructions set the zero flag if the result is zero }
  15485. A_POPCNT, A_LZCNT:
  15486. begin
  15487. if (
  15488. { With POPCNT, an input of zero will set the zero flag
  15489. because the population count of zero is zero }
  15490. (taicpu(hp1).opcode = A_POPCNT) and
  15491. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15492. (
  15493. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15494. { Faster than going through the second half of the 'or'
  15495. condition below }
  15496. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15497. )
  15498. ) or (
  15499. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15500. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15501. { and in case of carry for A(E)/B(E)/C/NC }
  15502. (
  15503. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15504. (
  15505. (taicpu(hp1).opcode <> A_ADD) and
  15506. (taicpu(hp1).opcode <> A_SUB) and
  15507. (taicpu(hp1).opcode <> A_LZCNT)
  15508. )
  15509. )
  15510. ) then
  15511. begin
  15512. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15513. RemoveCurrentP(p, hp2);
  15514. Result:=true;
  15515. Exit;
  15516. end;
  15517. end;
  15518. A_SHL, A_SAL, A_SHR, A_SAR:
  15519. begin
  15520. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15521. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15522. { therefore, it's only safe to do this optimization for }
  15523. { shifts by a (nonzero) constant }
  15524. (taicpu(hp1).oper[0]^.typ = top_const) and
  15525. (taicpu(hp1).oper[0]^.val <> 0) and
  15526. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15527. { and in case of carry for A(E)/B(E)/C/NC }
  15528. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15529. begin
  15530. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15531. RemoveCurrentP(p, hp2);
  15532. Result:=true;
  15533. Exit;
  15534. end;
  15535. end;
  15536. A_DEC, A_INC, A_NEG:
  15537. begin
  15538. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15539. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15540. { and in case of carry for A(E)/B(E)/C/NC }
  15541. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15542. begin
  15543. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15544. RemoveCurrentP(p, hp2);
  15545. Result:=true;
  15546. Exit;
  15547. end;
  15548. end;
  15549. A_ANDN, A_BZHI:
  15550. begin
  15551. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15552. { Only the zero and sign flags are consistent with what the result is }
  15553. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15554. begin
  15555. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15556. RemoveCurrentP(p, hp2);
  15557. Result:=true;
  15558. Exit;
  15559. end;
  15560. end;
  15561. A_BEXTR:
  15562. begin
  15563. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15564. { Only the zero flag is set }
  15565. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15566. begin
  15567. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15568. RemoveCurrentP(p, hp2);
  15569. Result:=true;
  15570. Exit;
  15571. end;
  15572. end;
  15573. else
  15574. ;
  15575. end; { case }
  15576. { change "test $-1,%reg" into "test %reg,%reg" }
  15577. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15578. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15579. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15580. if MatchInstruction(p, A_OR, []) and
  15581. { Can only match if they're both registers }
  15582. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15583. begin
  15584. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15585. taicpu(p).opcode := A_TEST;
  15586. { No need to set Result to True, as we've done all the optimisations we can }
  15587. end;
  15588. end;
  15589. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15590. var
  15591. hp1,hp3 : tai;
  15592. {$ifndef x86_64}
  15593. hp2 : taicpu;
  15594. {$endif x86_64}
  15595. begin
  15596. Result:=false;
  15597. hp3:=nil;
  15598. {$ifndef x86_64}
  15599. { don't do this on modern CPUs, this really hurts them due to
  15600. broken call/ret pairing }
  15601. if (current_settings.optimizecputype < cpu_Pentium2) and
  15602. not(cs_create_pic in current_settings.moduleswitches) and
  15603. GetNextInstruction(p, hp1) and
  15604. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15605. MatchOpType(taicpu(hp1),top_ref) and
  15606. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15607. begin
  15608. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15609. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15610. InsertLLItem(p.previous, p, hp2);
  15611. taicpu(p).opcode := A_JMP;
  15612. taicpu(p).is_jmp := true;
  15613. RemoveInstruction(hp1);
  15614. Result:=true;
  15615. end
  15616. else
  15617. {$endif x86_64}
  15618. { replace
  15619. call procname
  15620. ret
  15621. by
  15622. jmp procname
  15623. but do it only on level 4 because it destroys stack back traces
  15624. else if the subroutine is marked as no return, remove the ret
  15625. }
  15626. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15627. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15628. GetNextInstruction(p, hp1) and
  15629. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15630. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15631. SetAndTest(hp1,hp3) and
  15632. GetNextInstruction(hp1,hp1) and
  15633. MatchInstruction(hp1,A_RET,[S_NO])
  15634. )
  15635. ) and
  15636. (taicpu(hp1).ops=0) then
  15637. begin
  15638. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15639. { we might destroy stack alignment here if we do not do a call }
  15640. (target_info.stackalign<=sizeof(SizeUInt)) then
  15641. begin
  15642. taicpu(p).opcode := A_JMP;
  15643. taicpu(p).is_jmp := true;
  15644. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15645. end
  15646. else
  15647. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15648. RemoveInstruction(hp1);
  15649. if Assigned(hp3) then
  15650. begin
  15651. AsmL.Remove(hp3);
  15652. AsmL.InsertBefore(hp3,p)
  15653. end;
  15654. Result:=true;
  15655. end;
  15656. end;
  15657. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15658. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15659. begin
  15660. case OpSize of
  15661. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15662. Result := (Val <= $FF) and (Val >= -128);
  15663. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15664. Result := (Val <= $FFFF) and (Val >= -32768);
  15665. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15666. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15667. else
  15668. Result := True;
  15669. end;
  15670. end;
  15671. var
  15672. hp1, hp2 : tai;
  15673. SizeChange: Boolean;
  15674. PreMessage: string;
  15675. begin
  15676. Result := False;
  15677. if (taicpu(p).oper[0]^.typ = top_reg) and
  15678. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15679. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15680. begin
  15681. { Change (using movzbl %al,%eax as an example):
  15682. movzbl %al, %eax movzbl %al, %eax
  15683. cmpl x, %eax testl %eax,%eax
  15684. To:
  15685. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15686. movzbl %al, %eax movzbl %al, %eax
  15687. Smaller instruction and minimises pipeline stall as the CPU
  15688. doesn't have to wait for the register to get zero-extended. [Kit]
  15689. Also allow if the smaller of the two registers is being checked,
  15690. as this still removes the false dependency.
  15691. }
  15692. if
  15693. (
  15694. (
  15695. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15696. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15697. ) or (
  15698. { If MatchOperand returns True, they must both be registers }
  15699. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15700. )
  15701. ) and
  15702. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15703. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15704. begin
  15705. 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);
  15706. asml.Remove(hp1);
  15707. asml.InsertBefore(hp1, p);
  15708. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15709. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15710. begin
  15711. taicpu(hp1).opcode := A_TEST;
  15712. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15713. end;
  15714. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15715. case taicpu(p).opsize of
  15716. S_BW, S_BL:
  15717. begin
  15718. SizeChange := taicpu(hp1).opsize <> S_B;
  15719. taicpu(hp1).changeopsize(S_B);
  15720. end;
  15721. S_WL:
  15722. begin
  15723. SizeChange := taicpu(hp1).opsize <> S_W;
  15724. taicpu(hp1).changeopsize(S_W);
  15725. end
  15726. else
  15727. InternalError(2020112701);
  15728. end;
  15729. UpdateUsedRegs(tai(p.Next));
  15730. { Check if the register is used aferwards - if not, we can
  15731. remove the movzx instruction completely }
  15732. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15733. begin
  15734. { Hp1 is a better position than p for debugging purposes }
  15735. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15736. RemoveCurrentp(p, hp1);
  15737. Result := True;
  15738. end;
  15739. if SizeChange then
  15740. DebugMsg(SPeepholeOptimization + PreMessage +
  15741. 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)
  15742. else
  15743. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15744. Exit;
  15745. end;
  15746. { Change (using movzwl %ax,%eax as an example):
  15747. movzwl %ax, %eax
  15748. movb %al, (dest) (Register is smaller than read register in movz)
  15749. To:
  15750. movb %al, (dest) (Move one back to avoid a false dependency)
  15751. movzwl %ax, %eax
  15752. }
  15753. if (taicpu(hp1).opcode = A_MOV) and
  15754. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15755. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15756. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15757. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15758. begin
  15759. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15760. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15761. asml.Remove(hp1);
  15762. asml.InsertBefore(hp1, p);
  15763. if taicpu(hp1).oper[1]^.typ = top_reg then
  15764. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15765. { Check if the register is used aferwards - if not, we can
  15766. remove the movzx instruction completely }
  15767. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15768. begin
  15769. { Hp1 is a better position than p for debugging purposes }
  15770. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15771. RemoveCurrentp(p, hp1);
  15772. Result := True;
  15773. end;
  15774. Exit;
  15775. end;
  15776. end;
  15777. end;
  15778. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15779. var
  15780. hp1: tai;
  15781. {$ifdef x86_64}
  15782. PreMessage, RegName: string;
  15783. {$endif x86_64}
  15784. begin
  15785. Result := False;
  15786. { If x is a power of 2 (popcnt = 1), change:
  15787. xor $x, %reg/ref
  15788. To:
  15789. btc lb(x), %reg/ref
  15790. }
  15791. if IsBTXAcceptable(p) and
  15792. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15793. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15794. (
  15795. { Don't optimise if a test instruction follows }
  15796. not GetNextInstruction(p, hp1) or
  15797. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15798. ) then
  15799. begin
  15800. 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);
  15801. taicpu(p).opcode := A_BTC;
  15802. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15803. Result := True;
  15804. Exit;
  15805. end;
  15806. {$ifdef x86_64}
  15807. { Code size reduction by J. Gareth "Kit" Moreton }
  15808. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15809. as this removes the REX prefix }
  15810. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15811. Exit;
  15812. if taicpu(p).oper[0]^.typ <> top_reg then
  15813. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15814. InternalError(2018011500);
  15815. case taicpu(p).opsize of
  15816. S_Q:
  15817. begin
  15818. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15819. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15820. { The actual optimization }
  15821. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15822. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15823. taicpu(p).changeopsize(S_L);
  15824. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15825. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15826. end;
  15827. else
  15828. ;
  15829. end;
  15830. {$endif x86_64}
  15831. end;
  15832. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15833. var
  15834. XReg: TRegister;
  15835. begin
  15836. Result := False;
  15837. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15838. Smaller encoding and slightly faster on some platforms (also works for
  15839. ZMM-sized registers) }
  15840. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15841. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15842. begin
  15843. XReg := taicpu(p).oper[0]^.reg;
  15844. if (taicpu(p).oper[1]^.reg = XReg) then
  15845. begin
  15846. taicpu(p).changeopsize(S_XMM);
  15847. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15848. if (cs_opt_size in current_settings.optimizerswitches) then
  15849. begin
  15850. { Change input registers to %xmm0 to reduce size. Note that
  15851. there's a risk of a false dependency doing this, so only
  15852. optimise for size here }
  15853. XReg := NR_XMM0;
  15854. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15855. end
  15856. else
  15857. begin
  15858. setsubreg(XReg, R_SUBMMX);
  15859. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15860. end;
  15861. taicpu(p).oper[0]^.reg := XReg;
  15862. taicpu(p).oper[1]^.reg := XReg;
  15863. Result := True;
  15864. end;
  15865. end;
  15866. end;
  15867. function TX86AsmOptimizer.PostPeepholeOptRET(var p: tai): Boolean;
  15868. var
  15869. hp1, p_new: tai;
  15870. begin
  15871. Result := False;
  15872. { Check for:
  15873. ret
  15874. .Lbl:
  15875. ret
  15876. Remove first 'ret'
  15877. }
  15878. if GetNextInstruction(p, hp1) and
  15879. { Remember where the label is }
  15880. SetAndTest(hp1, p_new) and
  15881. (hp1.typ in [ait_align, ait_label]) and
  15882. SkipLabels(hp1, hp1) and
  15883. MatchInstruction(hp1, A_RET, []) and
  15884. { To be safe, make sure the RET instructions are identical }
  15885. (taicpu(p).ops = taicpu(hp1).ops) and
  15886. (
  15887. (taicpu(p).ops = 0) or
  15888. (
  15889. (taicpu(p).ops = 1) and
  15890. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^)
  15891. )
  15892. ) then
  15893. begin
  15894. DebugMsg(SPeepholeOptimization + 'Removed superfluous RET', p);
  15895. UpdateUsedRegs(tai(p.Next));
  15896. RemoveCurrentP(p, p_new);
  15897. Result := True;
  15898. Exit;
  15899. end;
  15900. end;
  15901. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15902. var
  15903. OperIdx: Integer;
  15904. begin
  15905. for OperIdx := 0 to p.ops - 1 do
  15906. if p.oper[OperIdx]^.typ = top_ref then
  15907. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15908. end;
  15909. end.