aoptx86.pas 757 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646
  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 PrePeepholeOptSxx(var p : tai) : boolean;
  126. function PrePeepholeOptIMUL(var p : tai) : boolean;
  127. function PrePeepholeOptAND(var p : tai) : boolean;
  128. function OptPass1Test(var p: tai): boolean;
  129. function OptPass1Add(var p: tai): boolean;
  130. function OptPass1AND(var p : tai) : boolean;
  131. function OptPass1CMOVcc(var p: tai): Boolean;
  132. function OptPass1_V_MOVAP(var p : tai) : boolean;
  133. function OptPass1VOP(var p : tai) : boolean;
  134. function OptPass1MOV(var p : tai) : boolean;
  135. function OptPass1Movx(var p : tai) : boolean;
  136. function OptPass1MOVXX(var p : tai) : boolean;
  137. function OptPass1OP(var p : tai) : boolean;
  138. function OptPass1LEA(var p : tai) : boolean;
  139. function OptPass1Sub(var p : tai) : boolean;
  140. function OptPass1SHLSAL(var p : tai) : boolean;
  141. function OptPass1SHR(var p : tai) : boolean;
  142. function OptPass1FSTP(var p : tai) : boolean;
  143. function OptPass1FLD(var p : tai) : boolean;
  144. function OptPass1Cmp(var p : tai) : boolean;
  145. function OptPass1PXor(var p : tai) : boolean;
  146. function OptPass1VPXor(var p: tai): boolean;
  147. function OptPass1Imul(var p : tai) : boolean;
  148. function OptPass1Jcc(var p : tai) : boolean;
  149. function OptPass1SHXX(var p: tai): boolean;
  150. function OptPass1VMOVDQ(var p: tai): Boolean;
  151. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  152. function OptPass1STCCLC(var p: tai): Boolean;
  153. function OptPass2STCCLC(var p: tai): Boolean;
  154. function OptPass2CMOVcc(var p: tai): Boolean;
  155. function OptPass2Movx(var p : tai): Boolean;
  156. function OptPass2MOV(var p : tai) : boolean;
  157. function OptPass2Imul(var p : tai) : boolean;
  158. function OptPass2Jmp(var p : tai) : boolean;
  159. function OptPass2Jcc(var p : tai) : boolean;
  160. function OptPass2Lea(var p: tai): Boolean;
  161. function OptPass2SUB(var p: tai): Boolean;
  162. function OptPass2ADD(var p : tai): Boolean;
  163. function OptPass2SETcc(var p : tai) : boolean;
  164. function OptPass2Cmp(var p: tai): Boolean;
  165. function OptPass2Test(var p: tai): Boolean;
  166. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  167. function PostPeepholeOptMov(var p : tai) : Boolean;
  168. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  169. function PostPeepholeOptXor(var p : tai) : Boolean;
  170. function PostPeepholeOptAnd(var p : tai) : boolean;
  171. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  172. function PostPeepholeOptCmp(var p : tai) : Boolean;
  173. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  174. function PostPeepholeOptCall(var p : tai) : Boolean;
  175. function PostPeepholeOptLea(var p : tai) : Boolean;
  176. function PostPeepholeOptPush(var p: tai): Boolean;
  177. function PostPeepholeOptShr(var p : tai) : boolean;
  178. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  179. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  180. function PostPeepholeOptRET(var p: tai): Boolean;
  181. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  182. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  183. function TrySwapMovOp(var p, hp1: tai): Boolean;
  184. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  185. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  186. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  187. { Processor-dependent reference optimisation }
  188. class procedure OptimizeRefs(var p: taicpu); static;
  189. end;
  190. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  191. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  192. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  193. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  194. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  195. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  196. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  197. {$if max_operands>2}
  198. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  199. {$endif max_operands>2}
  200. function RefsEqual(const r1, r2: treference): boolean;
  201. { Like RefsEqual, but doesn't compare the offsets }
  202. function RefsAlmostEqual(const r1, r2: treference): boolean;
  203. { Note that Result is set to True if the references COULD overlap but the
  204. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  205. might still overlap because %reg2 could be equal to %reg1-4 }
  206. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  207. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  208. { returns true, if ref is a reference using only the registers passed as base and index
  209. and having an offset }
  210. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  211. implementation
  212. uses
  213. cutils,verbose,
  214. systems,
  215. globals,
  216. cpuinfo,
  217. procinfo,
  218. paramgr,
  219. aasmbase,
  220. aoptbase,aoptutils,
  221. symconst,symsym,
  222. cgx86,
  223. itcpugas;
  224. {$ifndef 8086}
  225. const
  226. MAX_CMOV_INSTRUCTIONS = 4;
  227. MAX_CMOV_REGISTERS = 8;
  228. type
  229. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  230. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  231. tsProcessed);
  232. { For OptPass2Jcc }
  233. TCMOVTracking = object
  234. private
  235. CMOVScore, ConstCount: LongInt;
  236. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  237. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  238. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  239. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  240. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  241. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  242. fOptimizer: TX86AsmOptimizer;
  243. fLabel: TAsmSymbol;
  244. fInsertionPoint,
  245. fCondition,
  246. fInitialJump,
  247. fFirstMovBlock,
  248. fFirstMovBlockStop,
  249. fSecondJump,
  250. fThirdJump,
  251. fSecondMovBlock,
  252. fSecondMovBlockStop,
  253. fMidLabel,
  254. fEndLabel,
  255. fAllocationRange: tai;
  256. fState: TCMovTrackingState;
  257. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  258. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  259. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  260. public
  261. RegisterTracking: TAllUsedRegs;
  262. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  263. destructor Done;
  264. procedure Process(out new_p: tai);
  265. property State: TCMovTrackingState read fState;
  266. end;
  267. PCMOVTracking = ^TCMOVTracking;
  268. {$endif 8086}
  269. {$ifdef DEBUG_AOPTCPU}
  270. const
  271. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  272. {$else DEBUG_AOPTCPU}
  273. { Empty strings help the optimizer to remove string concatenations that won't
  274. ever appear to the user on release builds. [Kit] }
  275. const
  276. SPeepholeOptimization = '';
  277. {$endif DEBUG_AOPTCPU}
  278. LIST_STEP_SIZE = 4;
  279. type
  280. TJumpTrackingItem = class(TLinkedListItem)
  281. private
  282. FSymbol: TAsmSymbol;
  283. FRefs: LongInt;
  284. public
  285. constructor Create(ASymbol: TAsmSymbol);
  286. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  287. property Symbol: TAsmSymbol read FSymbol;
  288. property Refs: LongInt read FRefs;
  289. end;
  290. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  291. begin
  292. inherited Create;
  293. FSymbol := ASymbol;
  294. FRefs := 0;
  295. end;
  296. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  297. begin
  298. Inc(FRefs);
  299. end;
  300. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  301. begin
  302. result :=
  303. (instr.typ = ait_instruction) and
  304. (taicpu(instr).opcode = op) and
  305. ((opsize = []) or (taicpu(instr).opsize in opsize));
  306. end;
  307. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  308. begin
  309. result :=
  310. (instr.typ = ait_instruction) and
  311. ((taicpu(instr).opcode = op1) or
  312. (taicpu(instr).opcode = op2)
  313. ) and
  314. ((opsize = []) or (taicpu(instr).opsize in opsize));
  315. end;
  316. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  317. begin
  318. result :=
  319. (instr.typ = ait_instruction) and
  320. ((taicpu(instr).opcode = op1) or
  321. (taicpu(instr).opcode = op2) or
  322. (taicpu(instr).opcode = op3)
  323. ) and
  324. ((opsize = []) or (taicpu(instr).opsize in opsize));
  325. end;
  326. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  327. const opsize : topsizes) : boolean;
  328. var
  329. op : TAsmOp;
  330. begin
  331. result:=false;
  332. if (instr.typ <> ait_instruction) or
  333. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  334. exit;
  335. for op in ops do
  336. begin
  337. if taicpu(instr).opcode = op then
  338. begin
  339. result:=true;
  340. exit;
  341. end;
  342. end;
  343. end;
  344. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  345. begin
  346. result := (oper.typ = top_reg) and (oper.reg = reg);
  347. end;
  348. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  349. begin
  350. result := (oper.typ = top_const) and (oper.val = a);
  351. end;
  352. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  353. begin
  354. result := oper1.typ = oper2.typ;
  355. if result then
  356. case oper1.typ of
  357. top_const:
  358. Result:=oper1.val = oper2.val;
  359. top_reg:
  360. Result:=oper1.reg = oper2.reg;
  361. top_ref:
  362. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  363. else
  364. internalerror(2013102801);
  365. end
  366. end;
  367. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  368. begin
  369. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  370. if result then
  371. case oper1.typ of
  372. top_const:
  373. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  374. top_reg:
  375. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  376. top_ref:
  377. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  378. else
  379. internalerror(2020052401);
  380. end
  381. end;
  382. function RefsEqual(const r1, r2: treference): boolean;
  383. begin
  384. RefsEqual :=
  385. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  386. (r1.relsymbol = r2.relsymbol) and
  387. (r1.segment = r2.segment) and (r1.base = r2.base) and
  388. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  389. (r1.offset = r2.offset) and
  390. (r1.volatility + r2.volatility = []);
  391. end;
  392. function RefsAlmostEqual(const r1, r2: treference): boolean;
  393. begin
  394. RefsAlmostEqual :=
  395. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  396. (r1.relsymbol = r2.relsymbol) and
  397. (r1.segment = r2.segment) and (r1.base = r2.base) and
  398. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  399. { Don't compare the offsets }
  400. (r1.volatility + r2.volatility = []);
  401. end;
  402. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  403. begin
  404. if (r1.symbol<>r2.symbol) then
  405. { If the index registers are different, there's a chance one could
  406. be set so it equals the other symbol }
  407. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  408. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  409. (r1.relsymbol = r2.relsymbol) and
  410. (r1.segment = r2.segment) and (r1.base = r2.base) and
  411. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  412. (r1.volatility + r2.volatility = []) then
  413. { In this case, it all depends on the offsets }
  414. Exit(abs(r1.offset - r2.offset) < Range);
  415. { There's a chance things MIGHT overlap, so take no chances }
  416. Result := True;
  417. end;
  418. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  419. begin
  420. Result:=(ref.offset=0) and
  421. (ref.scalefactor in [0,1]) and
  422. (ref.segment=NR_NO) and
  423. (ref.symbol=nil) and
  424. (ref.relsymbol=nil) and
  425. ((base=NR_INVALID) or
  426. (ref.base=base)) and
  427. ((index=NR_INVALID) or
  428. (ref.index=index)) and
  429. (ref.volatility=[]);
  430. end;
  431. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  432. begin
  433. Result:=(ref.scalefactor in [0,1]) and
  434. (ref.segment=NR_NO) and
  435. (ref.symbol=nil) and
  436. (ref.relsymbol=nil) and
  437. ((base=NR_INVALID) or
  438. (ref.base=base)) and
  439. ((index=NR_INVALID) or
  440. (ref.index=index)) and
  441. (ref.volatility=[]);
  442. end;
  443. function InstrReadsFlags(p: tai): boolean;
  444. begin
  445. InstrReadsFlags := true;
  446. case p.typ of
  447. ait_instruction:
  448. if InsProp[taicpu(p).opcode].Ch*
  449. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  450. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  451. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  452. exit;
  453. ait_label:
  454. exit;
  455. else
  456. ;
  457. end;
  458. InstrReadsFlags := false;
  459. end;
  460. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  461. begin
  462. Next:=Current;
  463. repeat
  464. Result:=GetNextInstruction(Next,Next);
  465. until not (Result) or
  466. not(cs_opt_level3 in current_settings.optimizerswitches) or
  467. (Next.typ<>ait_instruction) or
  468. RegInInstruction(reg,Next) or
  469. is_calljmp(taicpu(Next).opcode);
  470. end;
  471. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  472. var
  473. GetNextResult: Boolean;
  474. begin
  475. Result:=0;
  476. Next:=Current;
  477. repeat
  478. GetNextResult := GetNextInstruction(Next,Next);
  479. if GetNextResult then
  480. Inc(Result)
  481. else
  482. { Must return zero upon hitting the end of the linked list without a match }
  483. Result := 0;
  484. until not (GetNextResult) or
  485. not(cs_opt_level3 in current_settings.optimizerswitches) or
  486. (Next.typ<>ait_instruction) or
  487. RegInInstruction(reg,Next) or
  488. is_calljmp(taicpu(Next).opcode);
  489. end;
  490. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  491. procedure TrackJump(Symbol: TAsmSymbol);
  492. var
  493. Search: TJumpTrackingItem;
  494. begin
  495. { See if an entry already exists in our jump tracking list
  496. (faster to search backwards due to the higher chance of
  497. matching destinations) }
  498. Search := TJumpTrackingItem(JumpTracking.Last);
  499. while Assigned(Search) do
  500. begin
  501. if Search.Symbol = Symbol then
  502. begin
  503. { Found it - remove it so it can be pushed to the front }
  504. JumpTracking.Remove(Search);
  505. Break;
  506. end;
  507. Search := TJumpTrackingItem(Search.Previous);
  508. end;
  509. if not Assigned(Search) then
  510. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  511. JumpTracking.Concat(Search);
  512. Search.IncRefs;
  513. end;
  514. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  515. var
  516. Search: TJumpTrackingItem;
  517. begin
  518. Result := False;
  519. { See if this label appears in the tracking list }
  520. Search := TJumpTrackingItem(JumpTracking.Last);
  521. while Assigned(Search) do
  522. begin
  523. if Search.Symbol = Symbol then
  524. begin
  525. { Found it - let's see what we can discover }
  526. if Search.Symbol.getrefs = Search.Refs then
  527. begin
  528. { Success - all the references are accounted for }
  529. JumpTracking.Remove(Search);
  530. Search.Free;
  531. { It is logically impossible for CrossJump to be false here
  532. because we must have run into a conditional jump for
  533. this label at some point }
  534. if not CrossJump then
  535. InternalError(2022041710);
  536. if JumpTracking.First = nil then
  537. { Tracking list is now empty - no more cross jumps }
  538. CrossJump := False;
  539. Result := True;
  540. Exit;
  541. end;
  542. { If the references don't match, it's possible to enter
  543. this label through other means, so drop out }
  544. Exit;
  545. end;
  546. Search := TJumpTrackingItem(Search.Previous);
  547. end;
  548. end;
  549. var
  550. Next_Label: tai;
  551. begin
  552. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  553. Next := Current;
  554. repeat
  555. Result := GetNextInstruction(Next,Next);
  556. if not Result then
  557. Break;
  558. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  559. if is_calljmpuncondret(taicpu(Next).opcode) then
  560. begin
  561. if (taicpu(Next).opcode = A_JMP) and
  562. { Remove dead code now to save time }
  563. RemoveDeadCodeAfterJump(taicpu(Next)) then
  564. { A jump was removed, but not the current instruction, and
  565. Result doesn't necessarily translate into an optimisation
  566. routine's Result, so use the "Force New Iteration" flag so
  567. mark a new pass }
  568. Include(OptsToCheck, aoc_ForceNewIteration);
  569. if not Assigned(JumpTracking) then
  570. begin
  571. { Cross-label optimisations often causes other optimisations
  572. to perform worse because they're not given the chance to
  573. optimise locally. In this case, don't do the cross-label
  574. optimisations yet, but flag them as a potential possibility
  575. for the next iteration of Pass 1 }
  576. if not NotFirstIteration then
  577. Include(OptsToCheck, aoc_ForceNewIteration);
  578. end
  579. else if IsJumpToLabel(taicpu(Next)) and
  580. GetNextInstruction(Next, Next_Label) then
  581. begin
  582. { If we have JMP .lbl, and the label after it has all of its
  583. references tracked, then this is probably an if-else style of
  584. block and we can keep tracking. If the label for this jump
  585. then appears later and is fully tracked, then it's the end
  586. of the if-else blocks and the code paths converge (thus
  587. marking the end of the cross-jump) }
  588. if (Next_Label.typ = ait_label) then
  589. begin
  590. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  591. begin
  592. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  593. Next := Next_Label;
  594. { CrossJump gets set to false by LabelAccountedFor if the
  595. list is completely emptied (as it indicates that all
  596. code paths have converged). We could avoid this nuance
  597. by moving the TrackJump call to before the
  598. LabelAccountedFor call, but this is slower in situations
  599. where LabelAccountedFor would return False due to the
  600. creation of a new object that is not used and destroyed
  601. soon after. }
  602. CrossJump := True;
  603. Continue;
  604. end;
  605. end
  606. else if (Next_Label.typ <> ait_marker) then
  607. { We just did a RemoveDeadCodeAfterJump, so either we find
  608. a label, the end of the procedure or some kind of marker}
  609. InternalError(2022041720);
  610. end;
  611. Result := False;
  612. Exit;
  613. end
  614. else
  615. begin
  616. if not Assigned(JumpTracking) then
  617. begin
  618. { Cross-label optimisations often causes other optimisations
  619. to perform worse because they're not given the chance to
  620. optimise locally. In this case, don't do the cross-label
  621. optimisations yet, but flag them as a potential possibility
  622. for the next iteration of Pass 1 }
  623. if not NotFirstIteration then
  624. Include(OptsToCheck, aoc_ForceNewIteration);
  625. end
  626. else if IsJumpToLabel(taicpu(Next)) then
  627. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  628. else
  629. { Conditional jumps should always be a jump to label }
  630. InternalError(2022041701);
  631. CrossJump := True;
  632. Continue;
  633. end;
  634. if Next.typ = ait_label then
  635. begin
  636. if not Assigned(JumpTracking) then
  637. begin
  638. { Cross-label optimisations often causes other optimisations
  639. to perform worse because they're not given the chance to
  640. optimise locally. In this case, don't do the cross-label
  641. optimisations yet, but flag them as a potential possibility
  642. for the next iteration of Pass 1 }
  643. if not NotFirstIteration then
  644. Include(OptsToCheck, aoc_ForceNewIteration);
  645. end
  646. else if LabelAccountedFor(tai_label(Next).labsym) then
  647. Continue;
  648. { If we reach here, we're at a label that hasn't been seen before
  649. (or JumpTracking was nil) }
  650. Break;
  651. end;
  652. until not Result or
  653. not (cs_opt_level3 in current_settings.optimizerswitches) or
  654. not (Next.typ in [ait_label, ait_instruction]) or
  655. RegInInstruction(reg,Next);
  656. end;
  657. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  658. begin
  659. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  660. begin
  661. Result:=GetNextInstruction(Current,Next);
  662. exit;
  663. end;
  664. Next:=tai(Current.Next);
  665. Result:=false;
  666. while assigned(Next) do
  667. begin
  668. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  669. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  670. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  671. exit
  672. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  673. begin
  674. Result:=true;
  675. exit;
  676. end;
  677. Next:=tai(Next.Next);
  678. end;
  679. end;
  680. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  681. begin
  682. Result:=RegReadByInstruction(reg,hp);
  683. end;
  684. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  685. var
  686. p: taicpu;
  687. opcount: longint;
  688. begin
  689. RegReadByInstruction := false;
  690. if hp.typ <> ait_instruction then
  691. exit;
  692. p := taicpu(hp);
  693. case p.opcode of
  694. A_CALL:
  695. regreadbyinstruction := true;
  696. A_IMUL:
  697. case p.ops of
  698. 1:
  699. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  700. (
  701. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  702. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  703. );
  704. 2,3:
  705. regReadByInstruction :=
  706. reginop(reg,p.oper[0]^) or
  707. reginop(reg,p.oper[1]^);
  708. else
  709. InternalError(2019112801);
  710. end;
  711. A_MUL:
  712. begin
  713. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  714. (
  715. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  716. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  717. );
  718. end;
  719. A_IDIV,A_DIV:
  720. begin
  721. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  722. (
  723. (getregtype(reg)=R_INTREGISTER) and
  724. (
  725. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  726. )
  727. );
  728. end;
  729. else
  730. begin
  731. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  732. begin
  733. RegReadByInstruction := false;
  734. exit;
  735. end;
  736. for opcount := 0 to p.ops-1 do
  737. if (p.oper[opCount]^.typ = top_ref) and
  738. RegInRef(reg,p.oper[opcount]^.ref^) then
  739. begin
  740. RegReadByInstruction := true;
  741. exit
  742. end;
  743. { special handling for SSE MOVSD }
  744. if (p.opcode=A_MOVSD) and (p.ops>0) then
  745. begin
  746. if p.ops<>2 then
  747. internalerror(2017042702);
  748. regReadByInstruction := reginop(reg,p.oper[0]^) or
  749. (
  750. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  751. );
  752. exit;
  753. end;
  754. with insprop[p.opcode] do
  755. begin
  756. case getregtype(reg) of
  757. R_INTREGISTER:
  758. begin
  759. case getsupreg(reg) of
  760. RS_EAX:
  761. if [Ch_REAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  762. begin
  763. RegReadByInstruction := true;
  764. exit
  765. end;
  766. RS_ECX:
  767. if [Ch_RECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  768. begin
  769. RegReadByInstruction := true;
  770. exit
  771. end;
  772. RS_EDX:
  773. if [Ch_REDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  774. begin
  775. RegReadByInstruction := true;
  776. exit
  777. end;
  778. RS_EBX:
  779. if [Ch_REBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  780. begin
  781. RegReadByInstruction := true;
  782. exit
  783. end;
  784. RS_ESP:
  785. if [Ch_RESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  786. begin
  787. RegReadByInstruction := true;
  788. exit
  789. end;
  790. RS_EBP:
  791. if [Ch_REBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  792. begin
  793. RegReadByInstruction := true;
  794. exit
  795. end;
  796. RS_ESI:
  797. if [Ch_RESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. RS_EDI:
  803. if [Ch_REDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  804. begin
  805. RegReadByInstruction := true;
  806. exit
  807. end;
  808. end;
  809. end;
  810. R_MMREGISTER:
  811. begin
  812. case getsupreg(reg) of
  813. RS_XMM0:
  814. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  815. begin
  816. RegReadByInstruction := true;
  817. exit
  818. end;
  819. end;
  820. end;
  821. else
  822. ;
  823. end;
  824. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  825. begin
  826. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  827. begin
  828. case p.condition of
  829. C_A,C_NBE, { CF=0 and ZF=0 }
  830. C_BE,C_NA: { CF=1 or ZF=1 }
  831. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  832. C_AE,C_NB,C_NC, { CF=0 }
  833. C_B,C_NAE,C_C: { CF=1 }
  834. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  835. C_NE,C_NZ, { ZF=0 }
  836. C_E,C_Z: { ZF=1 }
  837. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  838. C_G,C_NLE, { ZF=0 and SF=OF }
  839. C_LE,C_NG: { ZF=1 or SF<>OF }
  840. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  841. C_GE,C_NL, { SF=OF }
  842. C_L,C_NGE: { SF<>OF }
  843. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  844. C_NO, { OF=0 }
  845. C_O: { OF=1 }
  846. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  847. C_NP,C_PO, { PF=0 }
  848. C_P,C_PE: { PF=1 }
  849. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  850. C_NS, { SF=0 }
  851. C_S: { SF=1 }
  852. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  853. else
  854. internalerror(2017042701);
  855. end;
  856. if RegReadByInstruction then
  857. exit;
  858. end;
  859. case getsubreg(reg) of
  860. R_SUBW,R_SUBD,R_SUBQ:
  861. RegReadByInstruction :=
  862. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  863. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  864. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  865. R_SUBFLAGCARRY:
  866. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  867. R_SUBFLAGPARITY:
  868. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  869. R_SUBFLAGAUXILIARY:
  870. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  871. R_SUBFLAGZERO:
  872. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  873. R_SUBFLAGSIGN:
  874. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  875. R_SUBFLAGOVERFLOW:
  876. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  877. R_SUBFLAGINTERRUPT:
  878. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  879. R_SUBFLAGDIRECTION:
  880. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  881. else
  882. internalerror(2017042601);
  883. end;
  884. exit;
  885. end;
  886. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  887. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  888. (p.oper[0]^.reg=p.oper[1]^.reg) then
  889. exit;
  890. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  891. begin
  892. RegReadByInstruction := true;
  893. exit
  894. end;
  895. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  896. begin
  897. RegReadByInstruction := true;
  898. exit
  899. end;
  900. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  901. begin
  902. RegReadByInstruction := true;
  903. exit
  904. end;
  905. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  906. begin
  907. RegReadByInstruction := true;
  908. exit
  909. end;
  910. end;
  911. end;
  912. end;
  913. end;
  914. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  915. begin
  916. result:=false;
  917. if p1.typ<>ait_instruction then
  918. exit;
  919. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  920. exit(true);
  921. if (getregtype(reg)=R_INTREGISTER) and
  922. { change information for xmm movsd are not correct }
  923. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  924. begin
  925. { Handle instructions that behave differently depending on the size and operand count }
  926. case taicpu(p1).opcode of
  927. A_MUL, A_DIV, A_IDIV:
  928. if taicpu(p1).opsize = S_B then
  929. Result := (getsupreg(Reg) = RS_EAX)
  930. else
  931. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  932. A_IMUL:
  933. if taicpu(p1).ops = 1 then
  934. begin
  935. if taicpu(p1).opsize = S_B then
  936. Result := (getsupreg(Reg) = RS_EAX)
  937. else
  938. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  939. end;
  940. { If ops are greater than 1, call inherited method }
  941. else
  942. case getsupreg(reg) of
  943. { RS_EAX = RS_RAX on x86-64 }
  944. RS_EAX:
  945. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  946. RS_ECX:
  947. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  948. RS_EDX:
  949. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  950. RS_EBX:
  951. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  952. RS_ESP:
  953. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  954. RS_EBP:
  955. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  956. RS_ESI:
  957. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  958. RS_EDI:
  959. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  960. else
  961. ;
  962. end;
  963. end;
  964. if result then
  965. exit;
  966. end
  967. else if getregtype(reg)=R_MMREGISTER then
  968. begin
  969. case getsupreg(reg) of
  970. RS_XMM0:
  971. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  972. else
  973. ;
  974. end;
  975. if result then
  976. exit;
  977. end
  978. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  979. begin
  980. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  981. exit(true);
  982. case getsubreg(reg) of
  983. R_SUBFLAGCARRY:
  984. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  985. R_SUBFLAGPARITY:
  986. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  987. R_SUBFLAGAUXILIARY:
  988. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  989. R_SUBFLAGZERO:
  990. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  991. R_SUBFLAGSIGN:
  992. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  993. R_SUBFLAGOVERFLOW:
  994. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  995. R_SUBFLAGINTERRUPT:
  996. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  997. R_SUBFLAGDIRECTION:
  998. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  999. R_SUBW,R_SUBD,R_SUBQ:
  1000. { Everything except the direction bits }
  1001. Result:=
  1002. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1003. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1004. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1005. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1006. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1007. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1008. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1009. else
  1010. ;
  1011. end;
  1012. if result then
  1013. exit;
  1014. end
  1015. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1016. exit(true);
  1017. Result:=inherited RegInInstruction(Reg, p1);
  1018. end;
  1019. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1020. const
  1021. WriteOps: array[0..3] of set of TInsChange =
  1022. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1023. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1024. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1025. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1026. var
  1027. OperIdx: Integer;
  1028. begin
  1029. Result := False;
  1030. if p1.typ <> ait_instruction then
  1031. exit;
  1032. with insprop[taicpu(p1).opcode] do
  1033. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1034. begin
  1035. case getsubreg(reg) of
  1036. R_SUBW,R_SUBD,R_SUBQ:
  1037. Result :=
  1038. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1039. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1040. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1041. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1042. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1043. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1044. R_SUBFLAGCARRY:
  1045. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1046. R_SUBFLAGPARITY:
  1047. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1048. R_SUBFLAGAUXILIARY:
  1049. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1050. R_SUBFLAGZERO:
  1051. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1052. R_SUBFLAGSIGN:
  1053. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1054. R_SUBFLAGOVERFLOW:
  1055. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1056. R_SUBFLAGINTERRUPT:
  1057. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1058. R_SUBFLAGDIRECTION:
  1059. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1060. else
  1061. internalerror(2017042602);
  1062. end;
  1063. exit;
  1064. end;
  1065. case taicpu(p1).opcode of
  1066. A_CALL:
  1067. { We could potentially set Result to False if the register in
  1068. question is non-volatile for the subroutine's calling convention,
  1069. but this would require detecting the calling convention in use and
  1070. also assuming that the routine doesn't contain malformed assembly
  1071. language, for example... so it could only be done under -O4 as it
  1072. would be considered a side-effect. [Kit] }
  1073. Result := True;
  1074. A_MOVSD:
  1075. { special handling for SSE MOVSD }
  1076. if (taicpu(p1).ops>0) then
  1077. begin
  1078. if taicpu(p1).ops<>2 then
  1079. internalerror(2017042703);
  1080. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1081. end;
  1082. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1083. so fix it here (FK)
  1084. }
  1085. A_VMOVSS,
  1086. A_VMOVSD:
  1087. begin
  1088. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1089. exit;
  1090. end;
  1091. A_MUL, A_DIV, A_IDIV:
  1092. begin
  1093. if taicpu(p1).opsize = S_B then
  1094. Result := (getsupreg(Reg) = RS_EAX)
  1095. else
  1096. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1097. end;
  1098. A_IMUL:
  1099. begin
  1100. if taicpu(p1).ops = 1 then
  1101. begin
  1102. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1103. end
  1104. else
  1105. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1106. Exit;
  1107. end;
  1108. else
  1109. ;
  1110. end;
  1111. if Result then
  1112. exit;
  1113. with insprop[taicpu(p1).opcode] do
  1114. begin
  1115. if getregtype(reg)=R_INTREGISTER then
  1116. begin
  1117. case getsupreg(reg) of
  1118. RS_EAX:
  1119. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1120. begin
  1121. Result := True;
  1122. exit
  1123. end;
  1124. RS_ECX:
  1125. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1126. begin
  1127. Result := True;
  1128. exit
  1129. end;
  1130. RS_EDX:
  1131. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1132. begin
  1133. Result := True;
  1134. exit
  1135. end;
  1136. RS_EBX:
  1137. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1138. begin
  1139. Result := True;
  1140. exit
  1141. end;
  1142. RS_ESP:
  1143. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1144. begin
  1145. Result := True;
  1146. exit
  1147. end;
  1148. RS_EBP:
  1149. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1150. begin
  1151. Result := True;
  1152. exit
  1153. end;
  1154. RS_ESI:
  1155. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1156. begin
  1157. Result := True;
  1158. exit
  1159. end;
  1160. RS_EDI:
  1161. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1162. begin
  1163. Result := True;
  1164. exit
  1165. end;
  1166. end;
  1167. end;
  1168. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1169. if (WriteOps[OperIdx]*Ch<>[]) and
  1170. { The register doesn't get modified inside a reference }
  1171. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1172. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1173. begin
  1174. Result := true;
  1175. exit
  1176. end;
  1177. end;
  1178. end;
  1179. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1180. const
  1181. WriteOps: array[0..3] of set of TInsChange =
  1182. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1183. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1184. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1185. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1186. var
  1187. X: Integer;
  1188. CurrentP1Size: asizeint;
  1189. begin
  1190. Result := (
  1191. (Ref.base <> NR_NO) and
  1192. {$ifdef x86_64}
  1193. (Ref.base <> NR_RIP) and
  1194. {$endif x86_64}
  1195. RegModifiedBetween(Ref.base, p1, p2)
  1196. ) or
  1197. (
  1198. (Ref.index <> NR_NO) and
  1199. (Ref.index <> Ref.base) and
  1200. RegModifiedBetween(Ref.index, p1, p2)
  1201. );
  1202. { Now check to see if the memory itself is written to }
  1203. if not Result then
  1204. begin
  1205. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1206. if p1.typ = ait_instruction then
  1207. begin
  1208. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1209. with insprop[taicpu(p1).opcode] do
  1210. for X := 0 to taicpu(p1).ops - 1 do
  1211. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1212. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1213. { Catch any potential overlaps }
  1214. (
  1215. (RefSize = 0) or
  1216. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1217. ) and
  1218. (
  1219. (CurrentP1Size = 0) or
  1220. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1221. ) and
  1222. { Reference is used, but does the instruction write to it? }
  1223. (
  1224. (Ch_All in Ch) or
  1225. ((WriteOps[X] * Ch) <> [])
  1226. ) then
  1227. begin
  1228. Result := True;
  1229. Break;
  1230. end;
  1231. end;
  1232. end;
  1233. end;
  1234. {$ifdef DEBUG_AOPTCPU}
  1235. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1236. begin
  1237. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1238. end;
  1239. function debug_tostr(i: tcgint): string; inline;
  1240. begin
  1241. Result := tostr(i);
  1242. end;
  1243. function debug_hexstr(i: tcgint): string;
  1244. begin
  1245. Result := '0x';
  1246. case i of
  1247. 0..$FF:
  1248. Result := Result + hexstr(i, 2);
  1249. $100..$FFFF:
  1250. Result := Result + hexstr(i, 4);
  1251. $10000..$FFFFFF:
  1252. Result := Result + hexstr(i, 6);
  1253. $1000000..$FFFFFFFF:
  1254. Result := Result + hexstr(i, 8);
  1255. else
  1256. Result := Result + hexstr(i, 16);
  1257. end;
  1258. end;
  1259. function debug_regname(r: TRegister): string; inline;
  1260. begin
  1261. Result := '%' + std_regname(r);
  1262. end;
  1263. { Debug output function - creates a string representation of an operator }
  1264. function debug_operstr(oper: TOper): string;
  1265. begin
  1266. case oper.typ of
  1267. top_const:
  1268. Result := '$' + debug_tostr(oper.val);
  1269. top_reg:
  1270. Result := debug_regname(oper.reg);
  1271. top_ref:
  1272. begin
  1273. if oper.ref^.offset <> 0 then
  1274. Result := debug_tostr(oper.ref^.offset) + '('
  1275. else
  1276. Result := '(';
  1277. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1278. begin
  1279. Result := Result + debug_regname(oper.ref^.base);
  1280. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1281. Result := Result + ',' + debug_regname(oper.ref^.index);
  1282. end
  1283. else
  1284. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1285. Result := Result + debug_regname(oper.ref^.index);
  1286. if (oper.ref^.scalefactor > 1) then
  1287. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1288. else
  1289. Result := Result + ')';
  1290. end;
  1291. else
  1292. Result := '[UNKNOWN]';
  1293. end;
  1294. end;
  1295. function debug_op2str(opcode: tasmop): string; inline;
  1296. begin
  1297. Result := std_op2str[opcode];
  1298. end;
  1299. function debug_opsize2str(opsize: topsize): string; inline;
  1300. begin
  1301. Result := gas_opsize2str[opsize];
  1302. end;
  1303. {$else DEBUG_AOPTCPU}
  1304. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1305. begin
  1306. end;
  1307. function debug_tostr(i: tcgint): string; inline;
  1308. begin
  1309. Result := '';
  1310. end;
  1311. function debug_hexstr(i: tcgint): string; inline;
  1312. begin
  1313. Result := '';
  1314. end;
  1315. function debug_regname(r: TRegister): string; inline;
  1316. begin
  1317. Result := '';
  1318. end;
  1319. function debug_operstr(oper: TOper): string; inline;
  1320. begin
  1321. Result := '';
  1322. end;
  1323. function debug_op2str(opcode: tasmop): string; inline;
  1324. begin
  1325. Result := '';
  1326. end;
  1327. function debug_opsize2str(opsize: topsize): string; inline;
  1328. begin
  1329. Result := '';
  1330. end;
  1331. {$endif DEBUG_AOPTCPU}
  1332. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1333. begin
  1334. {$ifdef x86_64}
  1335. { Always fine on x86-64 }
  1336. Result := True;
  1337. {$else x86_64}
  1338. Result :=
  1339. {$ifdef i8086}
  1340. (current_settings.cputype >= cpu_386) and
  1341. {$endif i8086}
  1342. (
  1343. { Always accept if optimising for size }
  1344. (cs_opt_size in current_settings.optimizerswitches) or
  1345. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1346. (current_settings.optimizecputype >= cpu_Pentium2)
  1347. );
  1348. {$endif x86_64}
  1349. end;
  1350. { Attempts to allocate a volatile integer register for use between p and hp,
  1351. using AUsedRegs for the current register usage information. Returns NR_NO
  1352. if no free register could be found }
  1353. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1354. var
  1355. RegSet: TCPURegisterSet;
  1356. CurrentSuperReg: Integer;
  1357. CurrentReg: TRegister;
  1358. Currentp: tai;
  1359. Breakout: Boolean;
  1360. begin
  1361. Result := NR_NO;
  1362. RegSet :=
  1363. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1364. current_procinfo.saved_regs_int;
  1365. (*
  1366. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1367. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1368. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1369. *)
  1370. for CurrentSuperReg in RegSet do
  1371. begin
  1372. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1373. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1374. {$if defined(i386) or defined(i8086)}
  1375. { If the target size is 8-bit, make sure we can actually encode it }
  1376. and (
  1377. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1378. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1379. )
  1380. {$endif i386 or i8086}
  1381. then
  1382. begin
  1383. Currentp := p;
  1384. Breakout := False;
  1385. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1386. begin
  1387. case Currentp.typ of
  1388. ait_instruction:
  1389. begin
  1390. if RegInInstruction(CurrentReg, Currentp) then
  1391. begin
  1392. Breakout := True;
  1393. Break;
  1394. end;
  1395. { Cannot allocate across an unconditional jump }
  1396. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1397. Exit;
  1398. end;
  1399. ait_marker:
  1400. { Don't try anything more if a marker is hit }
  1401. Exit;
  1402. ait_regalloc:
  1403. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1404. begin
  1405. Breakout := True;
  1406. Break;
  1407. end;
  1408. else
  1409. ;
  1410. end;
  1411. end;
  1412. if Breakout then
  1413. { Try the next register }
  1414. Continue;
  1415. { We have a free register available }
  1416. Result := CurrentReg;
  1417. if not DontAlloc then
  1418. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1419. Exit;
  1420. end;
  1421. end;
  1422. end;
  1423. { Attempts to allocate a volatile MM register for use between p and hp,
  1424. using AUsedRegs for the current register usage information. Returns NR_NO
  1425. if no free register could be found }
  1426. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1427. var
  1428. RegSet: TCPURegisterSet;
  1429. CurrentSuperReg: Integer;
  1430. CurrentReg: TRegister;
  1431. Currentp: tai;
  1432. Breakout: Boolean;
  1433. begin
  1434. Result := NR_NO;
  1435. RegSet :=
  1436. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1437. current_procinfo.saved_regs_mm;
  1438. for CurrentSuperReg in RegSet do
  1439. begin
  1440. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1441. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1442. begin
  1443. Currentp := p;
  1444. Breakout := False;
  1445. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1446. begin
  1447. case Currentp.typ of
  1448. ait_instruction:
  1449. begin
  1450. if RegInInstruction(CurrentReg, Currentp) then
  1451. begin
  1452. Breakout := True;
  1453. Break;
  1454. end;
  1455. { Cannot allocate across an unconditional jump }
  1456. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1457. Exit;
  1458. end;
  1459. ait_marker:
  1460. { Don't try anything more if a marker is hit }
  1461. Exit;
  1462. ait_regalloc:
  1463. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1464. begin
  1465. Breakout := True;
  1466. Break;
  1467. end;
  1468. else
  1469. ;
  1470. end;
  1471. end;
  1472. if Breakout then
  1473. { Try the next register }
  1474. Continue;
  1475. { We have a free register available }
  1476. Result := CurrentReg;
  1477. if not DontAlloc then
  1478. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1479. Exit;
  1480. end;
  1481. end;
  1482. end;
  1483. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1484. begin
  1485. if not SuperRegistersEqual(reg1,reg2) then
  1486. exit(false);
  1487. if getregtype(reg1)<>R_INTREGISTER then
  1488. exit(true); {because SuperRegisterEqual is true}
  1489. case getsubreg(reg1) of
  1490. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1491. higher, it preserves the high bits, so the new value depends on
  1492. reg2's previous value. In other words, it is equivalent to doing:
  1493. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1494. R_SUBL:
  1495. exit(getsubreg(reg2)=R_SUBL);
  1496. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1497. higher, it actually does a:
  1498. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1499. R_SUBH:
  1500. exit(getsubreg(reg2)=R_SUBH);
  1501. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1502. bits of reg2:
  1503. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1504. R_SUBW:
  1505. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1506. { a write to R_SUBD always overwrites every other subregister,
  1507. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1508. R_SUBD,
  1509. R_SUBQ:
  1510. exit(true);
  1511. else
  1512. internalerror(2017042801);
  1513. end;
  1514. end;
  1515. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1516. begin
  1517. if not SuperRegistersEqual(reg1,reg2) then
  1518. exit(false);
  1519. if getregtype(reg1)<>R_INTREGISTER then
  1520. exit(true); {because SuperRegisterEqual is true}
  1521. case getsubreg(reg1) of
  1522. R_SUBL:
  1523. exit(getsubreg(reg2)<>R_SUBH);
  1524. R_SUBH:
  1525. exit(getsubreg(reg2)<>R_SUBL);
  1526. R_SUBW,
  1527. R_SUBD,
  1528. R_SUBQ:
  1529. exit(true);
  1530. else
  1531. internalerror(2017042802);
  1532. end;
  1533. end;
  1534. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1535. var
  1536. hp1 : tai;
  1537. l : TCGInt;
  1538. begin
  1539. result:=false;
  1540. if not(GetNextInstruction(p, hp1)) then
  1541. exit;
  1542. { changes the code sequence
  1543. shr/sar const1, x
  1544. shl const2, x
  1545. to
  1546. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1547. if (taicpu(p).oper[0]^.typ = top_const) and
  1548. MatchInstruction(hp1,A_SHL,[]) and
  1549. (taicpu(hp1).oper[0]^.typ = top_const) and
  1550. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1551. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1552. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1553. begin
  1554. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1555. not(cs_opt_size in current_settings.optimizerswitches) then
  1556. begin
  1557. { shr/sar const1, %reg
  1558. shl const2, %reg
  1559. with const1 > const2 }
  1560. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1561. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1562. taicpu(hp1).opcode := A_AND;
  1563. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1564. case taicpu(p).opsize Of
  1565. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1566. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1567. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1568. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1569. else
  1570. Internalerror(2017050703)
  1571. end;
  1572. end
  1573. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1574. not(cs_opt_size in current_settings.optimizerswitches) then
  1575. begin
  1576. { shr/sar const1, %reg
  1577. shl const2, %reg
  1578. with const1 < const2 }
  1579. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1580. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1581. taicpu(p).opcode := A_AND;
  1582. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1583. case taicpu(p).opsize Of
  1584. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1585. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1586. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1587. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1588. else
  1589. Internalerror(2017050702)
  1590. end;
  1591. end
  1592. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1593. begin
  1594. { shr/sar const1, %reg
  1595. shl const2, %reg
  1596. with const1 = const2 }
  1597. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  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(2017050701)
  1607. end;
  1608. RemoveInstruction(hp1);
  1609. end;
  1610. end;
  1611. end;
  1612. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1613. var
  1614. opsize : topsize;
  1615. hp1, hp2 : tai;
  1616. tmpref : treference;
  1617. ShiftValue : Cardinal;
  1618. BaseValue : TCGInt;
  1619. begin
  1620. result:=false;
  1621. opsize:=taicpu(p).opsize;
  1622. { changes certain "imul const, %reg"'s to lea sequences }
  1623. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1624. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1625. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1626. if (taicpu(p).oper[0]^.val = 1) then
  1627. if (taicpu(p).ops = 2) then
  1628. { remove "imul $1, reg" }
  1629. begin
  1630. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1631. Result := RemoveCurrentP(p);
  1632. end
  1633. else
  1634. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1635. begin
  1636. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1637. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1638. asml.InsertAfter(hp1, p);
  1639. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1640. RemoveCurrentP(p, hp1);
  1641. Result := True;
  1642. end
  1643. else if ((taicpu(p).ops <= 2) or
  1644. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1645. not(cs_opt_size in current_settings.optimizerswitches) and
  1646. (not(GetNextInstruction(p, hp1)) or
  1647. not((tai(hp1).typ = ait_instruction) and
  1648. ((taicpu(hp1).opcode=A_Jcc) and
  1649. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1650. begin
  1651. {
  1652. imul X, reg1, reg2 to
  1653. lea (reg1,reg1,Y), reg2
  1654. shl ZZ,reg2
  1655. imul XX, reg1 to
  1656. lea (reg1,reg1,YY), reg1
  1657. shl ZZ,reg2
  1658. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1659. it does not exist as a separate optimization target in FPC though.
  1660. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1661. at most two zeros
  1662. }
  1663. reference_reset(tmpref,1,[]);
  1664. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1665. begin
  1666. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1667. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1668. TmpRef.base := taicpu(p).oper[1]^.reg;
  1669. TmpRef.index := taicpu(p).oper[1]^.reg;
  1670. if not(BaseValue in [3,5,9]) then
  1671. Internalerror(2018110101);
  1672. TmpRef.ScaleFactor := BaseValue-1;
  1673. if (taicpu(p).ops = 2) then
  1674. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1675. else
  1676. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1677. AsmL.InsertAfter(hp1,p);
  1678. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1679. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1680. RemoveCurrentP(p, hp1);
  1681. if ShiftValue>0 then
  1682. begin
  1683. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1684. AsmL.InsertAfter(hp2,hp1);
  1685. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1686. end;
  1687. Result := True;
  1688. end;
  1689. end;
  1690. end;
  1691. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1692. begin
  1693. Result := False;
  1694. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1695. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1696. begin
  1697. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1698. taicpu(p).opcode := A_MOV;
  1699. Result := True;
  1700. end;
  1701. end;
  1702. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1703. var
  1704. p: taicpu absolute hp; { Implicit typecast }
  1705. i: Integer;
  1706. begin
  1707. Result := False;
  1708. if not assigned(hp) or
  1709. (hp.typ <> ait_instruction) then
  1710. Exit;
  1711. Prefetch(insprop[p.opcode]);
  1712. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1713. with insprop[p.opcode] do
  1714. begin
  1715. case getsubreg(reg) of
  1716. R_SUBW,R_SUBD,R_SUBQ:
  1717. Result:=
  1718. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1719. uncommon flags are checked first }
  1720. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1721. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1722. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1723. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1724. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1725. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1726. R_SUBFLAGCARRY:
  1727. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1728. R_SUBFLAGPARITY:
  1729. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1730. R_SUBFLAGAUXILIARY:
  1731. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1732. R_SUBFLAGZERO:
  1733. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1734. R_SUBFLAGSIGN:
  1735. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1736. R_SUBFLAGOVERFLOW:
  1737. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1738. R_SUBFLAGINTERRUPT:
  1739. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1740. R_SUBFLAGDIRECTION:
  1741. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1742. else
  1743. internalerror(2017050501);
  1744. end;
  1745. exit;
  1746. end;
  1747. { Handle special cases first }
  1748. case p.opcode of
  1749. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1750. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1751. begin
  1752. Result :=
  1753. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1754. (p.oper[1]^.typ = top_reg) and
  1755. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1756. (
  1757. (p.oper[0]^.typ = top_const) or
  1758. (
  1759. (p.oper[0]^.typ = top_reg) and
  1760. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1761. ) or (
  1762. (p.oper[0]^.typ = top_ref) and
  1763. not RegInRef(reg,p.oper[0]^.ref^)
  1764. )
  1765. );
  1766. end;
  1767. A_MUL, A_IMUL:
  1768. Result :=
  1769. (
  1770. (p.ops=3) and { IMUL only }
  1771. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1772. (
  1773. (
  1774. (p.oper[1]^.typ=top_reg) and
  1775. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1776. ) or (
  1777. (p.oper[1]^.typ=top_ref) and
  1778. not RegInRef(reg,p.oper[1]^.ref^)
  1779. )
  1780. )
  1781. ) or (
  1782. (
  1783. (p.ops=1) and
  1784. (
  1785. (
  1786. (
  1787. (p.oper[0]^.typ=top_reg) and
  1788. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1789. )
  1790. ) or (
  1791. (p.oper[0]^.typ=top_ref) and
  1792. not RegInRef(reg,p.oper[0]^.ref^)
  1793. )
  1794. ) and (
  1795. (
  1796. (p.opsize=S_B) and
  1797. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1798. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1799. ) or (
  1800. (p.opsize=S_W) and
  1801. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1802. ) or (
  1803. (p.opsize=S_L) and
  1804. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1805. {$ifdef x86_64}
  1806. ) or (
  1807. (p.opsize=S_Q) and
  1808. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1809. {$endif x86_64}
  1810. )
  1811. )
  1812. )
  1813. );
  1814. A_CBW:
  1815. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1816. {$ifndef x86_64}
  1817. A_LDS:
  1818. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1819. A_LES:
  1820. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1821. {$endif not x86_64}
  1822. A_LFS:
  1823. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1824. A_LGS:
  1825. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1826. A_LSS:
  1827. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1828. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1829. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1830. A_LODSB:
  1831. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1832. A_LODSW:
  1833. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1834. {$ifdef x86_64}
  1835. A_LODSQ:
  1836. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1837. {$endif x86_64}
  1838. A_LODSD:
  1839. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1840. A_FSTSW, A_FNSTSW:
  1841. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1842. else
  1843. begin
  1844. with insprop[p.opcode] do
  1845. begin
  1846. if (
  1847. { xor %reg,%reg etc. is classed as a new value }
  1848. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1849. MatchOpType(p, top_reg, top_reg) and
  1850. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1851. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1852. ) then
  1853. begin
  1854. Result := True;
  1855. Exit;
  1856. end;
  1857. { Make sure the entire register is overwritten }
  1858. if (getregtype(reg) = R_INTREGISTER) then
  1859. begin
  1860. if (p.ops > 0) then
  1861. begin
  1862. if RegInOp(reg, p.oper[0]^) then
  1863. begin
  1864. if (p.oper[0]^.typ = top_ref) then
  1865. begin
  1866. if RegInRef(reg, p.oper[0]^.ref^) then
  1867. begin
  1868. Result := False;
  1869. Exit;
  1870. end;
  1871. end
  1872. else if (p.oper[0]^.typ = top_reg) then
  1873. begin
  1874. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1875. begin
  1876. Result := False;
  1877. Exit;
  1878. end
  1879. else if ([Ch_WOp1]*Ch<>[]) then
  1880. begin
  1881. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1882. Result := True
  1883. else
  1884. begin
  1885. Result := False;
  1886. Exit;
  1887. end;
  1888. end;
  1889. end;
  1890. end;
  1891. if (p.ops > 1) then
  1892. begin
  1893. if RegInOp(reg, p.oper[1]^) then
  1894. begin
  1895. if (p.oper[1]^.typ = top_ref) then
  1896. begin
  1897. if RegInRef(reg, p.oper[1]^.ref^) then
  1898. begin
  1899. Result := False;
  1900. Exit;
  1901. end;
  1902. end
  1903. else if (p.oper[1]^.typ = top_reg) then
  1904. begin
  1905. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1906. begin
  1907. Result := False;
  1908. Exit;
  1909. end
  1910. else if ([Ch_WOp2]*Ch<>[]) then
  1911. begin
  1912. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1913. Result := True
  1914. else
  1915. begin
  1916. Result := False;
  1917. Exit;
  1918. end;
  1919. end;
  1920. end;
  1921. end;
  1922. if (p.ops > 2) then
  1923. begin
  1924. if RegInOp(reg, p.oper[2]^) then
  1925. begin
  1926. if (p.oper[2]^.typ = top_ref) then
  1927. begin
  1928. if RegInRef(reg, p.oper[2]^.ref^) then
  1929. begin
  1930. Result := False;
  1931. Exit;
  1932. end;
  1933. end
  1934. else if (p.oper[2]^.typ = top_reg) then
  1935. begin
  1936. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1937. begin
  1938. Result := False;
  1939. Exit;
  1940. end
  1941. else if ([Ch_WOp3]*Ch<>[]) then
  1942. begin
  1943. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1944. Result := True
  1945. else
  1946. begin
  1947. Result := False;
  1948. Exit;
  1949. end;
  1950. end;
  1951. end;
  1952. end;
  1953. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1954. begin
  1955. if (p.oper[3]^.typ = top_ref) then
  1956. begin
  1957. if RegInRef(reg, p.oper[3]^.ref^) then
  1958. begin
  1959. Result := False;
  1960. Exit;
  1961. end;
  1962. end
  1963. else if (p.oper[3]^.typ = top_reg) then
  1964. begin
  1965. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1966. begin
  1967. Result := False;
  1968. Exit;
  1969. end
  1970. else if ([Ch_WOp4]*Ch<>[]) then
  1971. begin
  1972. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1973. Result := True
  1974. else
  1975. begin
  1976. Result := False;
  1977. Exit;
  1978. end;
  1979. end;
  1980. end;
  1981. end;
  1982. end;
  1983. end;
  1984. end;
  1985. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1986. case getsupreg(reg) of
  1987. RS_EAX:
  1988. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1989. begin
  1990. Result := True;
  1991. Exit;
  1992. end;
  1993. RS_ECX:
  1994. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1995. begin
  1996. Result := True;
  1997. Exit;
  1998. end;
  1999. RS_EDX:
  2000. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2001. begin
  2002. Result := True;
  2003. Exit;
  2004. end;
  2005. RS_EBX:
  2006. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2007. begin
  2008. Result := True;
  2009. Exit;
  2010. end;
  2011. RS_ESP:
  2012. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2013. begin
  2014. Result := True;
  2015. Exit;
  2016. end;
  2017. RS_EBP:
  2018. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2019. begin
  2020. Result := True;
  2021. Exit;
  2022. end;
  2023. RS_ESI:
  2024. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2025. begin
  2026. Result := True;
  2027. Exit;
  2028. end;
  2029. RS_EDI:
  2030. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2031. begin
  2032. Result := True;
  2033. Exit;
  2034. end;
  2035. else
  2036. ;
  2037. end;
  2038. end;
  2039. end;
  2040. end;
  2041. end;
  2042. end;
  2043. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2044. var
  2045. hp2,hp3 : tai;
  2046. begin
  2047. { some x86-64 issue a NOP before the real exit code }
  2048. if MatchInstruction(p,A_NOP,[]) then
  2049. GetNextInstruction(p,p);
  2050. result:=assigned(p) and (p.typ=ait_instruction) and
  2051. ((taicpu(p).opcode = A_RET) or
  2052. ((taicpu(p).opcode=A_LEAVE) and
  2053. GetNextInstruction(p,hp2) and
  2054. MatchInstruction(hp2,A_RET,[S_NO])
  2055. ) or
  2056. (((taicpu(p).opcode=A_LEA) and
  2057. MatchOpType(taicpu(p),top_ref,top_reg) and
  2058. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2059. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2060. ) and
  2061. GetNextInstruction(p,hp2) and
  2062. MatchInstruction(hp2,A_RET,[S_NO])
  2063. ) or
  2064. ((((taicpu(p).opcode=A_MOV) and
  2065. MatchOpType(taicpu(p),top_reg,top_reg) and
  2066. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2067. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2068. ((taicpu(p).opcode=A_LEA) and
  2069. MatchOpType(taicpu(p),top_ref,top_reg) and
  2070. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2071. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2072. )
  2073. ) and
  2074. GetNextInstruction(p,hp2) and
  2075. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2076. MatchOpType(taicpu(hp2),top_reg) and
  2077. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2078. GetNextInstruction(hp2,hp3) and
  2079. MatchInstruction(hp3,A_RET,[S_NO])
  2080. )
  2081. );
  2082. end;
  2083. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2084. begin
  2085. isFoldableArithOp := False;
  2086. case hp1.opcode of
  2087. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2088. isFoldableArithOp :=
  2089. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2090. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2091. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2092. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2093. (taicpu(hp1).oper[1]^.reg = reg);
  2094. A_INC,A_DEC,A_NEG,A_NOT:
  2095. isFoldableArithOp :=
  2096. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2097. (taicpu(hp1).oper[0]^.reg = reg);
  2098. else
  2099. ;
  2100. end;
  2101. end;
  2102. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2103. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2104. var
  2105. hp2: tai;
  2106. begin
  2107. hp2 := p;
  2108. repeat
  2109. hp2 := tai(hp2.previous);
  2110. if assigned(hp2) and
  2111. (hp2.typ = ait_regalloc) and
  2112. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2113. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2114. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2115. begin
  2116. RemoveInstruction(hp2);
  2117. break;
  2118. end;
  2119. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2120. end;
  2121. begin
  2122. case current_procinfo.procdef.returndef.typ of
  2123. arraydef,recorddef,pointerdef,
  2124. stringdef,enumdef,procdef,objectdef,errordef,
  2125. filedef,setdef,procvardef,
  2126. classrefdef,forwarddef:
  2127. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2128. orddef:
  2129. if current_procinfo.procdef.returndef.size <> 0 then
  2130. begin
  2131. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2132. { for int64/qword }
  2133. if current_procinfo.procdef.returndef.size = 8 then
  2134. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2135. end;
  2136. else
  2137. ;
  2138. end;
  2139. end;
  2140. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2141. var
  2142. hp1: tai;
  2143. operswap: poper;
  2144. begin
  2145. Result := False;
  2146. { Optimise:
  2147. cmov(c) %reg1,%reg2
  2148. mov %reg2,%reg1
  2149. (%reg2 dealloc.)
  2150. To:
  2151. cmov(~c) %reg2,%reg1
  2152. }
  2153. if (taicpu(p).oper[0]^.typ = top_reg) then
  2154. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2155. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2156. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2157. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2158. begin
  2159. TransferUsedRegs(TmpUsedRegs);
  2160. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2161. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2162. begin
  2163. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2164. { Save time by swapping the pointers (they're both registers, so
  2165. we don't need to worry about reference counts) }
  2166. operswap := taicpu(p).oper[0];
  2167. taicpu(p).oper[0] := taicpu(p).oper[1];
  2168. taicpu(p).oper[1] := operswap;
  2169. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2170. RemoveInstruction(hp1);
  2171. { It's still a CMOV, so we can look further ahead }
  2172. Include(OptsToCheck, aoc_ForceNewIteration);
  2173. { But first, let's see if this will get optimised again
  2174. (probably won't happen, but best to be sure) }
  2175. Continue;
  2176. end;
  2177. Break;
  2178. end;
  2179. end;
  2180. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2181. var
  2182. hp1,hp2 : tai;
  2183. begin
  2184. result:=false;
  2185. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2186. begin
  2187. { vmova* reg1,reg1
  2188. =>
  2189. <nop> }
  2190. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2191. begin
  2192. RemoveCurrentP(p);
  2193. result:=true;
  2194. exit;
  2195. end;
  2196. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2197. (hp1.typ = ait_instruction) and
  2198. (
  2199. { Under -O2 and below, the instructions are always adjacent }
  2200. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2201. (taicpu(hp1).ops <= 1) or
  2202. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2203. { If reg1 = reg3, reg1 must not be modified in between }
  2204. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2205. ) then
  2206. begin
  2207. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2208. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2209. begin
  2210. { vmova* reg1,reg2
  2211. ...
  2212. vmova* reg2,reg3
  2213. dealloc reg2
  2214. =>
  2215. vmova* reg1,reg3 }
  2216. TransferUsedRegs(TmpUsedRegs);
  2217. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2218. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2219. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2220. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2221. begin
  2222. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2223. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2224. TransferUsedRegs(TmpUsedRegs);
  2225. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2226. RemoveInstruction(hp1);
  2227. result:=true;
  2228. exit;
  2229. end;
  2230. { special case:
  2231. vmova* reg1,<op>
  2232. ...
  2233. vmova* <op>,reg1
  2234. =>
  2235. vmova* reg1,<op> }
  2236. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2237. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2238. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2239. ) then
  2240. begin
  2241. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2242. RemoveInstruction(hp1);
  2243. result:=true;
  2244. exit;
  2245. end
  2246. end
  2247. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2248. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2249. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2250. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2251. ) and
  2252. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2253. begin
  2254. { vmova* reg1,reg2
  2255. ...
  2256. vmovs* reg2,<op>
  2257. dealloc reg2
  2258. =>
  2259. vmovs* reg1,<op> }
  2260. TransferUsedRegs(TmpUsedRegs);
  2261. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2262. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2263. begin
  2264. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2265. taicpu(p).opcode:=taicpu(hp1).opcode;
  2266. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2267. TransferUsedRegs(TmpUsedRegs);
  2268. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2269. RemoveInstruction(hp1);
  2270. result:=true;
  2271. exit;
  2272. end
  2273. end;
  2274. if MatchInstruction(hp1,[A_VFMADDPD,
  2275. A_VFMADD132PD,
  2276. A_VFMADD132PS,
  2277. A_VFMADD132SD,
  2278. A_VFMADD132SS,
  2279. A_VFMADD213PD,
  2280. A_VFMADD213PS,
  2281. A_VFMADD213SD,
  2282. A_VFMADD213SS,
  2283. A_VFMADD231PD,
  2284. A_VFMADD231PS,
  2285. A_VFMADD231SD,
  2286. A_VFMADD231SS,
  2287. A_VFMADDSUB132PD,
  2288. A_VFMADDSUB132PS,
  2289. A_VFMADDSUB213PD,
  2290. A_VFMADDSUB213PS,
  2291. A_VFMADDSUB231PD,
  2292. A_VFMADDSUB231PS,
  2293. A_VFMSUB132PD,
  2294. A_VFMSUB132PS,
  2295. A_VFMSUB132SD,
  2296. A_VFMSUB132SS,
  2297. A_VFMSUB213PD,
  2298. A_VFMSUB213PS,
  2299. A_VFMSUB213SD,
  2300. A_VFMSUB213SS,
  2301. A_VFMSUB231PD,
  2302. A_VFMSUB231PS,
  2303. A_VFMSUB231SD,
  2304. A_VFMSUB231SS,
  2305. A_VFMSUBADD132PD,
  2306. A_VFMSUBADD132PS,
  2307. A_VFMSUBADD213PD,
  2308. A_VFMSUBADD213PS,
  2309. A_VFMSUBADD231PD,
  2310. A_VFMSUBADD231PS,
  2311. A_VFNMADD132PD,
  2312. A_VFNMADD132PS,
  2313. A_VFNMADD132SD,
  2314. A_VFNMADD132SS,
  2315. A_VFNMADD213PD,
  2316. A_VFNMADD213PS,
  2317. A_VFNMADD213SD,
  2318. A_VFNMADD213SS,
  2319. A_VFNMADD231PD,
  2320. A_VFNMADD231PS,
  2321. A_VFNMADD231SD,
  2322. A_VFNMADD231SS,
  2323. A_VFNMSUB132PD,
  2324. A_VFNMSUB132PS,
  2325. A_VFNMSUB132SD,
  2326. A_VFNMSUB132SS,
  2327. A_VFNMSUB213PD,
  2328. A_VFNMSUB213PS,
  2329. A_VFNMSUB213SD,
  2330. A_VFNMSUB213SS,
  2331. A_VFNMSUB231PD,
  2332. A_VFNMSUB231PS,
  2333. A_VFNMSUB231SD,
  2334. A_VFNMSUB231SS],[S_NO]) and
  2335. { we mix single and double opperations here because we assume that the compiler
  2336. generates vmovapd only after double operations and vmovaps only after single operations }
  2337. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2338. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2339. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2340. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2341. begin
  2342. TransferUsedRegs(TmpUsedRegs);
  2343. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2344. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2345. begin
  2346. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2347. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2348. RemoveCurrentP(p)
  2349. else
  2350. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2351. RemoveInstruction(hp2);
  2352. end;
  2353. end
  2354. else if (hp1.typ = ait_instruction) and
  2355. (((taicpu(p).opcode=A_MOVAPS) and
  2356. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2357. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2358. ((taicpu(p).opcode=A_MOVAPD) and
  2359. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2360. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2361. ) and
  2362. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2363. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2364. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2365. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2366. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2367. { change
  2368. movapX reg,reg2
  2369. addsX/subsX/... reg3, reg2
  2370. movapX reg2,reg
  2371. to
  2372. addsX/subsX/... reg3,reg
  2373. }
  2374. begin
  2375. TransferUsedRegs(TmpUsedRegs);
  2376. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2377. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2378. begin
  2379. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2380. debug_op2str(taicpu(p).opcode)+' '+
  2381. debug_op2str(taicpu(hp1).opcode)+' '+
  2382. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2383. { we cannot eliminate the first move if
  2384. the operations uses the same register for source and dest }
  2385. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2386. { Remember that hp1 is not necessarily the immediate
  2387. next instruction }
  2388. RemoveCurrentP(p);
  2389. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2390. RemoveInstruction(hp2);
  2391. result:=true;
  2392. end;
  2393. end
  2394. else if (hp1.typ = ait_instruction) and
  2395. (((taicpu(p).opcode=A_VMOVAPD) and
  2396. (taicpu(hp1).opcode=A_VCOMISD)) or
  2397. ((taicpu(p).opcode=A_VMOVAPS) and
  2398. ((taicpu(hp1).opcode=A_VCOMISS))
  2399. )
  2400. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2401. { change
  2402. movapX reg,reg1
  2403. vcomisX reg1,reg1
  2404. to
  2405. vcomisX reg,reg
  2406. }
  2407. begin
  2408. TransferUsedRegs(TmpUsedRegs);
  2409. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2410. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2411. begin
  2412. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2413. debug_op2str(taicpu(p).opcode)+' '+
  2414. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2415. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2416. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2417. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2418. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2419. RemoveCurrentP(p);
  2420. result:=true;
  2421. exit;
  2422. end;
  2423. end
  2424. end;
  2425. end;
  2426. end;
  2427. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2428. var
  2429. hp1 : tai;
  2430. begin
  2431. result:=false;
  2432. { replace
  2433. V<Op>X %mreg1,%mreg2,%mreg3
  2434. VMovX %mreg3,%mreg4
  2435. dealloc %mreg3
  2436. by
  2437. V<Op>X %mreg1,%mreg2,%mreg4
  2438. ?
  2439. }
  2440. if GetNextInstruction(p,hp1) and
  2441. { we mix single and double operations here because we assume that the compiler
  2442. generates vmovapd only after double operations and vmovaps only after single operations }
  2443. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2444. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2445. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2446. begin
  2447. TransferUsedRegs(TmpUsedRegs);
  2448. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2449. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2450. begin
  2451. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2452. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2453. RemoveInstruction(hp1);
  2454. result:=true;
  2455. end;
  2456. end;
  2457. end;
  2458. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2459. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2460. begin
  2461. Result := False;
  2462. { For safety reasons, only check for exact register matches }
  2463. { Check base register }
  2464. if (ref.base = AOldReg) then
  2465. begin
  2466. ref.base := ANewReg;
  2467. Result := True;
  2468. end;
  2469. { Check index register }
  2470. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2471. begin
  2472. ref.index := ANewReg;
  2473. Result := True;
  2474. end;
  2475. end;
  2476. { Replaces all references to AOldReg in an operand to ANewReg }
  2477. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2478. var
  2479. OldSupReg, NewSupReg: TSuperRegister;
  2480. OldSubReg, NewSubReg: TSubRegister;
  2481. OldRegType: TRegisterType;
  2482. ThisOper: POper;
  2483. begin
  2484. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2485. Result := False;
  2486. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2487. InternalError(2020011801);
  2488. OldSupReg := getsupreg(AOldReg);
  2489. OldSubReg := getsubreg(AOldReg);
  2490. OldRegType := getregtype(AOldReg);
  2491. NewSupReg := getsupreg(ANewReg);
  2492. NewSubReg := getsubreg(ANewReg);
  2493. if OldRegType <> getregtype(ANewReg) then
  2494. InternalError(2020011802);
  2495. if OldSubReg <> NewSubReg then
  2496. InternalError(2020011803);
  2497. case ThisOper^.typ of
  2498. top_reg:
  2499. if (
  2500. (ThisOper^.reg = AOldReg) or
  2501. (
  2502. (OldRegType = R_INTREGISTER) and
  2503. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2504. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2505. (
  2506. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2507. {$ifndef x86_64}
  2508. and (
  2509. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2510. don't have an 8-bit representation }
  2511. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2512. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2513. )
  2514. {$endif x86_64}
  2515. )
  2516. )
  2517. ) then
  2518. begin
  2519. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2520. Result := True;
  2521. end;
  2522. top_ref:
  2523. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2524. Result := True;
  2525. else
  2526. ;
  2527. end;
  2528. end;
  2529. { Replaces all references to AOldReg in an instruction to ANewReg }
  2530. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2531. const
  2532. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2533. var
  2534. OperIdx: Integer;
  2535. begin
  2536. Result := False;
  2537. for OperIdx := 0 to p.ops - 1 do
  2538. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2539. begin
  2540. { The shift and rotate instructions can only use CL }
  2541. if not (
  2542. (OperIdx = 0) and
  2543. { This second condition just helps to avoid unnecessarily
  2544. calling MatchInstruction for 10 different opcodes }
  2545. (p.oper[0]^.reg = NR_CL) and
  2546. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2547. ) then
  2548. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2549. end
  2550. else if p.oper[OperIdx]^.typ = top_ref then
  2551. { It's okay to replace registers in references that get written to }
  2552. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2553. end;
  2554. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2555. begin
  2556. Result :=
  2557. (ref^.index = NR_NO) and
  2558. (
  2559. {$ifdef x86_64}
  2560. (
  2561. (ref^.base = NR_RIP) and
  2562. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2563. ) or
  2564. {$endif x86_64}
  2565. (ref^.refaddr = addr_full) or
  2566. (ref^.base = NR_STACK_POINTER_REG) or
  2567. (ref^.base = current_procinfo.framepointer)
  2568. );
  2569. end;
  2570. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2571. var
  2572. l: asizeint;
  2573. begin
  2574. Result := False;
  2575. { Should have been checked previously }
  2576. if p.opcode <> A_LEA then
  2577. InternalError(2020072501);
  2578. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2579. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2580. not(cs_opt_size in current_settings.optimizerswitches) then
  2581. exit;
  2582. with p.oper[0]^.ref^ do
  2583. begin
  2584. if (base <> p.oper[1]^.reg) or
  2585. (index <> NR_NO) or
  2586. assigned(symbol) then
  2587. exit;
  2588. l:=offset;
  2589. if (l=1) and UseIncDec then
  2590. begin
  2591. p.opcode:=A_INC;
  2592. p.loadreg(0,p.oper[1]^.reg);
  2593. p.ops:=1;
  2594. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2595. end
  2596. else if (l=-1) and UseIncDec then
  2597. begin
  2598. p.opcode:=A_DEC;
  2599. p.loadreg(0,p.oper[1]^.reg);
  2600. p.ops:=1;
  2601. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2602. end
  2603. else
  2604. begin
  2605. if (l<0) and (l<>-2147483648) then
  2606. begin
  2607. p.opcode:=A_SUB;
  2608. p.loadConst(0,-l);
  2609. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2610. end
  2611. else
  2612. begin
  2613. p.opcode:=A_ADD;
  2614. p.loadConst(0,l);
  2615. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2616. end;
  2617. end;
  2618. end;
  2619. Result := True;
  2620. end;
  2621. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2622. var
  2623. CurrentReg, ReplaceReg: TRegister;
  2624. begin
  2625. Result := False;
  2626. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2627. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2628. case hp.opcode of
  2629. A_FSTSW, A_FNSTSW,
  2630. A_IN, A_INS, A_OUT, A_OUTS,
  2631. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2632. { These routines have explicit operands, but they are restricted in
  2633. what they can be (e.g. IN and OUT can only read from AL, AX or
  2634. EAX. }
  2635. Exit;
  2636. A_IMUL:
  2637. begin
  2638. { The 1-operand version writes to implicit registers
  2639. The 2-operand version reads from the first operator, and reads
  2640. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2641. the 3-operand version reads from a register that it doesn't write to
  2642. }
  2643. case hp.ops of
  2644. 1:
  2645. if (
  2646. (
  2647. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2648. ) or
  2649. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2650. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2651. begin
  2652. Result := True;
  2653. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2654. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2655. end;
  2656. 2:
  2657. { Only modify the first parameter }
  2658. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2659. begin
  2660. Result := True;
  2661. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2662. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2663. end;
  2664. 3:
  2665. { Only modify the second parameter }
  2666. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2667. begin
  2668. Result := True;
  2669. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2670. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2671. end;
  2672. else
  2673. InternalError(2020012901);
  2674. end;
  2675. end;
  2676. else
  2677. if (hp.ops > 0) and
  2678. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2679. begin
  2680. Result := True;
  2681. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2682. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2683. end;
  2684. end;
  2685. end;
  2686. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2687. var
  2688. hp2, hp_regalloc: tai;
  2689. p_SourceReg, p_TargetReg: TRegister;
  2690. begin
  2691. Result := False;
  2692. { Backward optimisation. If we have:
  2693. func. %reg1,%reg2
  2694. mov %reg2,%reg3
  2695. (dealloc %reg2)
  2696. Change to:
  2697. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2698. Perform similar optimisations with 1, 3 and 4-operand instructions
  2699. that only have one output.
  2700. }
  2701. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2702. begin
  2703. p_SourceReg := taicpu(p).oper[0]^.reg;
  2704. p_TargetReg := taicpu(p).oper[1]^.reg;
  2705. TransferUsedRegs(TmpUsedRegs);
  2706. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2707. GetLastInstruction(p, hp2) and
  2708. (hp2.typ = ait_instruction) and
  2709. { Have to make sure it's an instruction that only reads from
  2710. the first operands and only writes (not reads or modifies) to
  2711. the last one; in essence, a pure function such as BSR, POPCNT
  2712. or ANDN }
  2713. (
  2714. (
  2715. (taicpu(hp2).ops = 1) and
  2716. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2717. ) or
  2718. (
  2719. (taicpu(hp2).ops = 2) and
  2720. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2721. ) or
  2722. (
  2723. (taicpu(hp2).ops = 3) and
  2724. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2725. ) or
  2726. (
  2727. (taicpu(hp2).ops = 4) and
  2728. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2729. )
  2730. ) and
  2731. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2732. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2733. begin
  2734. case taicpu(hp2).opcode of
  2735. A_FSTSW, A_FNSTSW,
  2736. A_IN, A_INS, A_OUT, A_OUTS,
  2737. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2738. { These routines have explicit operands, but they are restricted in
  2739. what they can be (e.g. IN and OUT can only read from AL, AX or
  2740. EAX. }
  2741. ;
  2742. else
  2743. begin
  2744. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2745. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2746. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2747. if Assigned(hp_regalloc) then
  2748. begin
  2749. Asml.Remove(hp_regalloc);
  2750. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2751. begin
  2752. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2753. hp_regalloc.Free;
  2754. end
  2755. else
  2756. { If the register is not explicitly deallocated, it's
  2757. being reused, so move the allocation to after func. }
  2758. AsmL.InsertAfter(hp_regalloc, hp2);
  2759. end;
  2760. if not RegInInstruction(p_TargetReg, hp2) then
  2761. begin
  2762. TransferUsedRegs(TmpUsedRegs);
  2763. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2764. end;
  2765. { Actually make the changes }
  2766. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2767. RemoveCurrentp(p, hp1);
  2768. { If the Func was another MOV instruction, we might get
  2769. "mov %reg,%reg" that doesn't get removed in Pass 2
  2770. otherwise, so deal with it here (also do something
  2771. similar with lea (%reg),%reg}
  2772. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2773. begin
  2774. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2775. if p = hp2 then
  2776. RemoveCurrentp(p)
  2777. else
  2778. RemoveInstruction(hp2);
  2779. end;
  2780. Result := True;
  2781. Exit;
  2782. end;
  2783. end;
  2784. end;
  2785. end;
  2786. end;
  2787. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2788. begin
  2789. Result := False;
  2790. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2791. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2792. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2793. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2794. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2795. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2796. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2797. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2798. begin
  2799. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2800. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2801. Result := True;
  2802. Include(OptsToCheck, aoc_ForceNewIteration);
  2803. end;
  2804. end;
  2805. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2806. var
  2807. hp1, hp2, hp3, hp4: tai;
  2808. DoOptimisation, TempBool: Boolean;
  2809. {$ifdef x86_64}
  2810. NewConst: TCGInt;
  2811. {$endif x86_64}
  2812. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2813. begin
  2814. if taicpu(hp1).opcode = signed_movop then
  2815. begin
  2816. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2817. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2818. end
  2819. else
  2820. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2821. end;
  2822. function TryConstMerge(var p1, p2: tai): Boolean;
  2823. var
  2824. ThisRef: TReference;
  2825. begin
  2826. Result := False;
  2827. ThisRef := taicpu(p2).oper[1]^.ref^;
  2828. { Only permit writes to the stack, since we can guarantee alignment with that }
  2829. if (ThisRef.index = NR_NO) and
  2830. (
  2831. (ThisRef.base = NR_STACK_POINTER_REG) or
  2832. (ThisRef.base = current_procinfo.framepointer)
  2833. ) then
  2834. begin
  2835. case taicpu(p).opsize of
  2836. S_B:
  2837. begin
  2838. { Word writes must be on a 2-byte boundary }
  2839. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2840. begin
  2841. { Reduce offset of second reference to see if it is sequential with the first }
  2842. Dec(ThisRef.offset, 1);
  2843. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2844. begin
  2845. { Make sure the constants aren't represented as a
  2846. negative number, as these won't merge properly }
  2847. taicpu(p1).opsize := S_W;
  2848. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2849. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2850. RemoveInstruction(p2);
  2851. Result := True;
  2852. end;
  2853. end;
  2854. end;
  2855. S_W:
  2856. begin
  2857. { Longword writes must be on a 4-byte boundary }
  2858. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2859. begin
  2860. { Reduce offset of second reference to see if it is sequential with the first }
  2861. Dec(ThisRef.offset, 2);
  2862. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2863. begin
  2864. { Make sure the constants aren't represented as a
  2865. negative number, as these won't merge properly }
  2866. taicpu(p1).opsize := S_L;
  2867. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2868. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2869. RemoveInstruction(p2);
  2870. Result := True;
  2871. end;
  2872. end;
  2873. end;
  2874. {$ifdef x86_64}
  2875. S_L:
  2876. begin
  2877. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2878. see if the constants can be encoded this way. }
  2879. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2880. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2881. { Quadword writes must be on an 8-byte boundary }
  2882. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2883. begin
  2884. { Reduce offset of second reference to see if it is sequential with the first }
  2885. Dec(ThisRef.offset, 4);
  2886. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2887. begin
  2888. { Make sure the constants aren't represented as a
  2889. negative number, as these won't merge properly }
  2890. taicpu(p1).opsize := S_Q;
  2891. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2892. taicpu(p1).oper[0]^.val := NewConst;
  2893. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2894. RemoveInstruction(p2);
  2895. Result := True;
  2896. end;
  2897. end;
  2898. end;
  2899. {$endif x86_64}
  2900. else
  2901. ;
  2902. end;
  2903. end;
  2904. end;
  2905. var
  2906. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2907. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2908. NewSize: topsize; NewOffset: asizeint;
  2909. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2910. SourceRef, TargetRef: TReference;
  2911. MovAligned, MovUnaligned: TAsmOp;
  2912. ThisRef: TReference;
  2913. JumpTracking: TLinkedList;
  2914. begin
  2915. Result:=false;
  2916. { remove mov reg1,reg1? }
  2917. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2918. then
  2919. begin
  2920. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2921. { take care of the register (de)allocs following p }
  2922. RemoveCurrentP(p);
  2923. Result := True;
  2924. exit;
  2925. end;
  2926. { Prevent compiler warnings }
  2927. p_SourceReg := NR_NO;
  2928. p_TargetReg := NR_NO;
  2929. if taicpu(p).oper[1]^.typ = top_reg then
  2930. begin
  2931. { Saves on a large number of dereferences }
  2932. p_TargetReg := taicpu(p).oper[1]^.reg;
  2933. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2934. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_TargetReg)
  2935. else
  2936. GetNextInstruction_p := GetNextInstruction(p, hp1);
  2937. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  2938. while True do
  2939. begin
  2940. if (taicpu(hp1).opcode = A_AND) and
  2941. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2942. begin
  2943. { A change has occurred, just not in p }
  2944. Include(OptsToCheck, aoc_ForceNewIteration);
  2945. if MatchOperand(taicpu(hp1).oper[1]^, p_TargetReg) then
  2946. begin
  2947. case taicpu(p).opsize of
  2948. S_L:
  2949. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2950. begin
  2951. { Optimize out:
  2952. mov x, %reg
  2953. and ffffffffh, %reg
  2954. }
  2955. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2956. RemoveInstruction(hp1);
  2957. Result:=true;
  2958. exit;
  2959. end;
  2960. S_Q: { TODO: Confirm if this is even possible }
  2961. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2962. begin
  2963. { Optimize out:
  2964. mov x, %reg
  2965. and ffffffffffffffffh, %reg
  2966. }
  2967. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2968. RemoveInstruction(hp1);
  2969. Result:=true;
  2970. exit;
  2971. end;
  2972. else
  2973. ;
  2974. end;
  2975. if (
  2976. { Make sure that if a reference is used, its registers
  2977. are not modified in between }
  2978. (
  2979. (taicpu(p).oper[0]^.typ = top_reg) and
  2980. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2981. ) or
  2982. (
  2983. (taicpu(p).oper[0]^.typ = top_ref) and
  2984. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  2985. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  2986. )
  2987. ) and
  2988. GetNextInstruction(hp1,hp2) and
  2989. MatchInstruction(hp2,A_TEST,[]) and
  2990. (
  2991. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2992. (
  2993. { If the register being tested is smaller than the one
  2994. that received a bitwise AND, permit it if the constant
  2995. fits into the smaller size }
  2996. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2997. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2998. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2999. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3000. (
  3001. (
  3002. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3003. (taicpu(hp1).oper[0]^.val <= $FF)
  3004. ) or
  3005. (
  3006. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3007. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3008. {$ifdef x86_64}
  3009. ) or
  3010. (
  3011. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3012. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3013. {$endif x86_64}
  3014. )
  3015. )
  3016. )
  3017. ) and
  3018. (
  3019. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3020. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3021. ) and
  3022. GetNextInstruction(hp2,hp3) and
  3023. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3024. (taicpu(hp3).condition in [C_E,C_NE]) then
  3025. begin
  3026. TransferUsedRegs(TmpUsedRegs);
  3027. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3028. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3029. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3030. begin
  3031. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3032. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3033. taicpu(hp1).opcode:=A_TEST;
  3034. { Shrink the TEST instruction down to the smallest possible size }
  3035. case taicpu(hp1).oper[0]^.val of
  3036. 0..255:
  3037. if (taicpu(hp1).opsize <> S_B)
  3038. {$ifndef x86_64}
  3039. and (
  3040. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3041. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3042. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3043. )
  3044. {$endif x86_64}
  3045. then
  3046. begin
  3047. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3048. { Only print debug message if the TEST instruction
  3049. is a different size before and after }
  3050. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3051. taicpu(hp1).opsize := S_B;
  3052. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3053. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3054. end;
  3055. 256..65535:
  3056. if (taicpu(hp1).opsize <> S_W) then
  3057. begin
  3058. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3059. { Only print debug message if the TEST instruction
  3060. is a different size before and after }
  3061. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3062. taicpu(hp1).opsize := S_W;
  3063. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3064. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3065. end;
  3066. {$ifdef x86_64}
  3067. 65536..$7FFFFFFF:
  3068. if (taicpu(hp1).opsize <> S_L) then
  3069. begin
  3070. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3071. { Only print debug message if the TEST instruction
  3072. is a different size before and after }
  3073. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3074. taicpu(hp1).opsize := S_L;
  3075. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3076. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3077. end;
  3078. {$endif x86_64}
  3079. else
  3080. ;
  3081. end;
  3082. RemoveInstruction(hp2);
  3083. RemoveCurrentP(p);
  3084. Result:=true;
  3085. exit;
  3086. end;
  3087. end;
  3088. end;
  3089. if IsMOVZXAcceptable and
  3090. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3091. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3092. (getsupreg(p_TargetReg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3093. then
  3094. begin
  3095. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3096. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3097. case taicpu(p).opsize of
  3098. S_B:
  3099. if (taicpu(hp1).oper[0]^.val = $ff) then
  3100. begin
  3101. { Convert:
  3102. movb x, %regl movb x, %regl
  3103. andw ffh, %regw andl ffh, %regd
  3104. To:
  3105. movzbw x, %regd movzbl x, %regd
  3106. (Identical registers, just different sizes)
  3107. }
  3108. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3109. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3110. case taicpu(hp1).opsize of
  3111. S_W: NewSize := S_BW;
  3112. S_L: NewSize := S_BL;
  3113. {$ifdef x86_64}
  3114. S_Q: NewSize := S_BQ;
  3115. {$endif x86_64}
  3116. else
  3117. InternalError(2018011510);
  3118. end;
  3119. end
  3120. else
  3121. NewSize := S_NO;
  3122. S_W:
  3123. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3124. begin
  3125. { Convert:
  3126. movw x, %regw
  3127. andl ffffh, %regd
  3128. To:
  3129. movzwl x, %regd
  3130. (Identical registers, just different sizes)
  3131. }
  3132. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3133. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3134. case taicpu(hp1).opsize of
  3135. S_L: NewSize := S_WL;
  3136. {$ifdef x86_64}
  3137. S_Q: NewSize := S_WQ;
  3138. {$endif x86_64}
  3139. else
  3140. InternalError(2018011511);
  3141. end;
  3142. end
  3143. else
  3144. NewSize := S_NO;
  3145. else
  3146. NewSize := S_NO;
  3147. end;
  3148. if NewSize <> S_NO then
  3149. begin
  3150. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3151. { The actual optimization }
  3152. taicpu(p).opcode := A_MOVZX;
  3153. taicpu(p).changeopsize(NewSize);
  3154. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3155. { Make sure we deal with any reference counts that were increased }
  3156. if taicpu(hp1).oper[1]^.typ = top_ref then
  3157. begin
  3158. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3159. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3160. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3161. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3162. end;
  3163. { Safeguard if "and" is followed by a conditional command }
  3164. TransferUsedRegs(TmpUsedRegs);
  3165. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3166. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3167. begin
  3168. { At this point, the "and" command is effectively equivalent to
  3169. "test %reg,%reg". This will be handled separately by the
  3170. Peephole Optimizer. [Kit] }
  3171. DebugMsg(SPeepholeOptimization + PreMessage +
  3172. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3173. end
  3174. else
  3175. begin
  3176. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3177. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3178. RemoveInstruction(hp1);
  3179. end;
  3180. Result := True;
  3181. Exit;
  3182. { Go through DeepMOVOpt again (jump to "while True do") }
  3183. Continue;
  3184. end;
  3185. end;
  3186. end;
  3187. if taicpu(p).oper[0]^.typ = top_reg then
  3188. begin
  3189. p_SourceReg := taicpu(p).oper[0]^.reg;
  3190. { Look for:
  3191. mov %reg1,%reg2
  3192. ??? %reg2,r/m
  3193. Change to:
  3194. mov %reg1,%reg2
  3195. ??? %reg1,r/m
  3196. }
  3197. if RegReadByInstruction(p_TargetReg, hp1) and
  3198. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3199. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3200. begin
  3201. { A change has occurred, just not in p }
  3202. Include(OptsToCheck, aoc_ForceNewIteration);
  3203. TransferUsedRegs(TmpUsedRegs);
  3204. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3205. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3206. { Just in case something didn't get modified (e.g. an
  3207. implicit register) }
  3208. not RegReadByInstruction(p_TargetReg, hp1) then
  3209. begin
  3210. { We can remove the original MOV }
  3211. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3212. RemoveCurrentP(p);
  3213. { UsedRegs got updated by RemoveCurrentp }
  3214. Result := True;
  3215. Exit;
  3216. end;
  3217. { If we know a MOV instruction has become a null operation, we might as well
  3218. get rid of it now to save time. }
  3219. if (taicpu(hp1).opcode = A_MOV) and
  3220. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3221. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3222. { Just being a register is enough to confirm it's a null operation }
  3223. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3224. begin
  3225. Result := True;
  3226. { Speed-up to reduce a pipeline stall... if we had something like...
  3227. movl %eax,%edx
  3228. movw %dx,%ax
  3229. ... the second instruction would change to movw %ax,%ax, but
  3230. given that it is now %ax that's active rather than %eax,
  3231. penalties might occur due to a partial register write, so instead,
  3232. change it to a MOVZX instruction when optimising for speed.
  3233. }
  3234. if not (cs_opt_size in current_settings.optimizerswitches) and
  3235. IsMOVZXAcceptable and
  3236. (taicpu(hp1).opsize < taicpu(p).opsize)
  3237. {$ifdef x86_64}
  3238. { operations already implicitly set the upper 64 bits to zero }
  3239. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3240. {$endif x86_64}
  3241. then
  3242. begin
  3243. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3244. case taicpu(p).opsize of
  3245. S_W:
  3246. if taicpu(hp1).opsize = S_B then
  3247. taicpu(hp1).opsize := S_BL
  3248. else
  3249. InternalError(2020012911);
  3250. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3251. case taicpu(hp1).opsize of
  3252. S_B:
  3253. taicpu(hp1).opsize := S_BL;
  3254. S_W:
  3255. taicpu(hp1).opsize := S_WL;
  3256. else
  3257. InternalError(2020012912);
  3258. end;
  3259. else
  3260. InternalError(2020012910);
  3261. end;
  3262. taicpu(hp1).opcode := A_MOVZX;
  3263. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3264. end
  3265. else
  3266. begin
  3267. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3268. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3269. RemoveInstruction(hp1);
  3270. { The instruction after what was hp1 is now the immediate next instruction,
  3271. so we can continue to make optimisations if it's present }
  3272. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3273. Exit;
  3274. hp1 := hp2;
  3275. end;
  3276. end;
  3277. end;
  3278. {$ifdef x86_64}
  3279. { Change:
  3280. movl %reg1l,%reg2l
  3281. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3282. To:
  3283. movl %reg1l,%reg2l
  3284. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3285. If %reg1 = %reg3, convert to:
  3286. movl %reg1l,%reg2l
  3287. andl %reg1l,%reg1l
  3288. }
  3289. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3290. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3291. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3292. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg) then
  3293. begin
  3294. TransferUsedRegs(TmpUsedRegs);
  3295. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3296. taicpu(hp1).opsize := S_L;
  3297. taicpu(hp1).loadreg(0, p_SourceReg);
  3298. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3299. AllocRegBetween(p_SourceReg, p, hp1, UsedRegs);
  3300. if (p_SourceReg = taicpu(hp1).oper[1]^.reg) then
  3301. begin
  3302. { %reg1 = %reg3 }
  3303. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3304. taicpu(hp1).opcode := A_AND;
  3305. end
  3306. else
  3307. begin
  3308. { %reg1 <> %reg3 }
  3309. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3310. end;
  3311. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3312. begin
  3313. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3314. RemoveCurrentP(p);
  3315. Result := True;
  3316. Exit;
  3317. end
  3318. else
  3319. begin
  3320. { Initial instruction wasn't actually changed }
  3321. Include(OptsToCheck, aoc_ForceNewIteration);
  3322. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3323. appears below since %reg1 has technically changed }
  3324. if taicpu(hp1).opcode = A_AND then
  3325. Exit;
  3326. end;
  3327. end;
  3328. {$endif x86_64}
  3329. end
  3330. else if taicpu(p).oper[0]^.typ = top_const then
  3331. begin
  3332. if (taicpu(hp1).opcode = A_OR) and
  3333. (taicpu(p).oper[1]^.typ = top_reg) and
  3334. MatchOperand(taicpu(p).oper[0]^, 0) and
  3335. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3336. begin
  3337. { mov 0, %reg
  3338. or ###,%reg
  3339. Change to (only if the flags are not used):
  3340. mov ###,%reg
  3341. }
  3342. TransferUsedRegs(TmpUsedRegs);
  3343. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3344. DoOptimisation := True;
  3345. { Even if the flags are used, we might be able to do the optimisation
  3346. if the conditions are predictable }
  3347. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3348. begin
  3349. { Only perform if ### = %reg (the same register) or equal to 0,
  3350. so %reg is guaranteed to still have a value of zero }
  3351. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3352. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3353. begin
  3354. hp2 := hp1;
  3355. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3356. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3357. GetNextInstruction(hp2, hp3) do
  3358. begin
  3359. { Don't continue modifying if the flags state is getting changed }
  3360. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3361. Break;
  3362. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3363. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3364. begin
  3365. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3366. begin
  3367. { Condition is always true }
  3368. case taicpu(hp3).opcode of
  3369. A_Jcc:
  3370. begin
  3371. { Check for jump shortcuts before we destroy the condition }
  3372. hp4 := hp3;
  3373. DoJumpOptimizations(hp3, TempBool);
  3374. { Make sure hp3 hasn't changed }
  3375. if (hp4 = hp3) then
  3376. begin
  3377. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3378. MakeUnconditional(taicpu(hp3));
  3379. end;
  3380. Result := True;
  3381. end;
  3382. A_CMOVcc:
  3383. begin
  3384. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3385. taicpu(hp3).opcode := A_MOV;
  3386. taicpu(hp3).condition := C_None;
  3387. Result := True;
  3388. end;
  3389. A_SETcc:
  3390. begin
  3391. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3392. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3393. taicpu(hp3).opcode := A_MOV;
  3394. taicpu(hp3).ops := 2;
  3395. taicpu(hp3).condition := C_None;
  3396. taicpu(hp3).opsize := S_B;
  3397. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3398. taicpu(hp3).loadconst(0, 1);
  3399. Result := True;
  3400. end;
  3401. else
  3402. InternalError(2021090701);
  3403. end;
  3404. end
  3405. 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
  3406. begin
  3407. { Condition is always false }
  3408. case taicpu(hp3).opcode of
  3409. A_Jcc:
  3410. begin
  3411. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3412. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3413. RemoveInstruction(hp3);
  3414. Result := True;
  3415. { Since hp3 was deleted, hp2 must not be updated }
  3416. Continue;
  3417. end;
  3418. A_CMOVcc:
  3419. begin
  3420. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3421. RemoveInstruction(hp3);
  3422. Result := True;
  3423. { Since hp3 was deleted, hp2 must not be updated }
  3424. Continue;
  3425. end;
  3426. A_SETcc:
  3427. begin
  3428. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3429. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3430. taicpu(hp3).opcode := A_MOV;
  3431. taicpu(hp3).ops := 2;
  3432. taicpu(hp3).condition := C_None;
  3433. taicpu(hp3).opsize := S_B;
  3434. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3435. taicpu(hp3).loadconst(0, 0);
  3436. Result := True;
  3437. end;
  3438. else
  3439. InternalError(2021090702);
  3440. end;
  3441. end
  3442. else
  3443. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3444. DoOptimisation := False;
  3445. end;
  3446. hp2 := hp3;
  3447. end;
  3448. if DoOptimisation then
  3449. begin
  3450. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3451. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3452. { Flags are still in use - don't optimise }
  3453. DoOptimisation := False;
  3454. end;
  3455. end
  3456. else
  3457. DoOptimisation := False;
  3458. end;
  3459. if DoOptimisation then
  3460. begin
  3461. {$ifdef x86_64}
  3462. { OR only supports 32-bit sign-extended constants for 64-bit
  3463. instructions, so compensate for this if the constant is
  3464. encoded as a value greater than or equal to 2^31 }
  3465. if (taicpu(hp1).opsize = S_Q) and
  3466. (taicpu(hp1).oper[0]^.typ = top_const) and
  3467. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3468. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3469. {$endif x86_64}
  3470. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3471. taicpu(hp1).opcode := A_MOV;
  3472. RemoveCurrentP(p);
  3473. Result := True;
  3474. Exit;
  3475. end;
  3476. end;
  3477. end
  3478. else if
  3479. { oper[0] is a reference }
  3480. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) then
  3481. begin
  3482. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  3483. begin
  3484. if ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3485. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3486. ) or
  3487. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3488. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3489. )
  3490. ) and
  3491. not RegModifiedBetween(Taicpu(hp1).oper[1]^.reg, p, hp1) then
  3492. { mov ref,reg1
  3493. lea (reg1,reg2),reg2
  3494. to
  3495. add ref,reg2 }
  3496. begin
  3497. TransferUsedRegs(TmpUsedRegs);
  3498. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3499. { If the flags register is in use, don't change the instruction to an
  3500. ADD otherwise this will scramble the flags. [Kit] }
  3501. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3502. { reg1 may not be used afterwards }
  3503. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3504. begin
  3505. Taicpu(hp1).opcode:=A_ADD;
  3506. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3507. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3508. RemoveCurrentp(p);
  3509. result:=true;
  3510. exit;
  3511. end;
  3512. end;
  3513. { If the LEA instruction can be converted into an arithmetic instruction,
  3514. it may be possible to then fold it in the next optimisation. }
  3515. if ConvertLEA(taicpu(hp1)) then
  3516. Include(OptsToCheck, aoc_ForceNewIteration);
  3517. end;
  3518. {
  3519. mov ref,reg0
  3520. <op> reg0,reg1
  3521. dealloc reg0
  3522. to
  3523. <op> ref,reg1
  3524. }
  3525. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3526. (taicpu(hp1).oper[0]^.reg = p_TargetReg) and
  3527. 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
  3528. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, p_TargetReg) and
  3529. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3530. begin
  3531. TransferUsedRegs(TmpUsedRegs);
  3532. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3533. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3534. begin
  3535. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  3536. { loadref increases the reference count, so decrement it again }
  3537. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3538. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3539. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3540. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3541. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3542. { See if we can remove the allocation of reg0 }
  3543. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3544. TryRemoveRegAlloc(p_TargetReg, p, hp1);
  3545. RemoveCurrentp(p);
  3546. Result:=true;
  3547. exit;
  3548. end;
  3549. end;
  3550. end;
  3551. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3552. overwrites the original destination register. e.g.
  3553. movl ###,%reg2d
  3554. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3555. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3556. }
  3557. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3558. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3559. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3560. begin
  3561. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3562. begin
  3563. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3564. case taicpu(p).oper[0]^.typ of
  3565. top_const:
  3566. { We have something like:
  3567. movb $x, %regb
  3568. movzbl %regb,%regd
  3569. Change to:
  3570. movl $x, %regd
  3571. }
  3572. begin
  3573. case taicpu(hp1).opsize of
  3574. S_BW:
  3575. begin
  3576. convert_mov_value(A_MOVSX, $FF);
  3577. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3578. taicpu(p).opsize := S_W;
  3579. end;
  3580. S_BL:
  3581. begin
  3582. convert_mov_value(A_MOVSX, $FF);
  3583. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3584. taicpu(p).opsize := S_L;
  3585. end;
  3586. S_WL:
  3587. begin
  3588. convert_mov_value(A_MOVSX, $FFFF);
  3589. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3590. taicpu(p).opsize := S_L;
  3591. end;
  3592. {$ifdef x86_64}
  3593. S_BQ:
  3594. begin
  3595. convert_mov_value(A_MOVSX, $FF);
  3596. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3597. taicpu(p).opsize := S_Q;
  3598. end;
  3599. S_WQ:
  3600. begin
  3601. convert_mov_value(A_MOVSX, $FFFF);
  3602. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3603. taicpu(p).opsize := S_Q;
  3604. end;
  3605. S_LQ:
  3606. begin
  3607. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3608. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3609. taicpu(p).opsize := S_Q;
  3610. end;
  3611. {$endif x86_64}
  3612. else
  3613. { If hp1 was a MOV instruction, it should have been
  3614. optimised already }
  3615. InternalError(2020021001);
  3616. end;
  3617. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3618. RemoveInstruction(hp1);
  3619. Result := True;
  3620. Exit;
  3621. end;
  3622. top_ref:
  3623. begin
  3624. { We have something like:
  3625. movb mem, %regb
  3626. movzbl %regb,%regd
  3627. Change to:
  3628. movzbl mem, %regd
  3629. }
  3630. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3631. begin
  3632. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3633. taicpu(p).opcode := taicpu(hp1).opcode;
  3634. taicpu(p).opsize := taicpu(hp1).opsize;
  3635. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3636. RemoveInstruction(hp1);
  3637. Result := True;
  3638. Exit;
  3639. end;
  3640. end;
  3641. else
  3642. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3643. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3644. Exit;
  3645. end;
  3646. end
  3647. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3648. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3649. optimised }
  3650. else
  3651. begin
  3652. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3653. RemoveCurrentP(p);
  3654. Result := True;
  3655. Exit;
  3656. end;
  3657. end;
  3658. if (taicpu(hp1).opcode = A_MOV) and
  3659. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3660. begin
  3661. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3662. TransferUsedRegs(TmpUsedRegs);
  3663. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3664. { we have
  3665. mov x, %treg
  3666. mov %treg, y
  3667. }
  3668. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3669. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3670. begin
  3671. { we've got
  3672. mov x, %treg
  3673. mov %treg, y
  3674. with %treg is not used after }
  3675. case taicpu(p).oper[0]^.typ Of
  3676. { top_reg is covered by DeepMOVOpt }
  3677. top_const:
  3678. begin
  3679. { change
  3680. mov const, %treg
  3681. mov %treg, y
  3682. to
  3683. mov const, y
  3684. }
  3685. {$ifdef x86_64}
  3686. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3687. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3688. {$endif x86_64}
  3689. begin
  3690. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3691. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3692. RemoveCurrentP(p);
  3693. Result := True;
  3694. Exit;
  3695. end;
  3696. end;
  3697. top_ref:
  3698. case taicpu(hp1).oper[1]^.typ of
  3699. top_reg:
  3700. { change
  3701. mov mem, %treg
  3702. mov %treg, %reg
  3703. to
  3704. mov mem, %reg"
  3705. }
  3706. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3707. begin
  3708. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3709. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3710. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3711. RemoveInstruction(hp1);
  3712. Result := True;
  3713. Exit;
  3714. end
  3715. else if
  3716. { Make sure that if a reference is used, its
  3717. registers are not modified in between }
  3718. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3719. begin
  3720. 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
  3721. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3722. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3723. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3724. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3725. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3726. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3727. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3728. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3729. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3730. RemoveCurrentP(p);
  3731. Result := True;
  3732. Exit;
  3733. end;
  3734. top_ref:
  3735. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3736. begin
  3737. {$ifdef x86_64}
  3738. { Look for the following to simplify:
  3739. mov x(mem1), %reg
  3740. mov %reg, y(mem2)
  3741. mov x+8(mem1), %reg
  3742. mov %reg, y+8(mem2)
  3743. Change to:
  3744. movdqu x(mem1), %xmmreg
  3745. movdqu %xmmreg, y(mem2)
  3746. ...but only as long as the memory blocks don't overlap
  3747. }
  3748. SourceRef := taicpu(p).oper[0]^.ref^;
  3749. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3750. if (taicpu(p).opsize = S_Q) and
  3751. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3752. GetNextInstruction(hp1, hp2) and
  3753. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3754. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3755. begin
  3756. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3757. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3758. Inc(SourceRef.offset, 8);
  3759. if UseAVX then
  3760. begin
  3761. MovAligned := A_VMOVDQA;
  3762. MovUnaligned := A_VMOVDQU;
  3763. end
  3764. else
  3765. begin
  3766. MovAligned := A_MOVDQA;
  3767. MovUnaligned := A_MOVDQU;
  3768. end;
  3769. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3770. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3771. begin
  3772. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3773. Inc(TargetRef.offset, 8);
  3774. if GetNextInstruction(hp2, hp3) and
  3775. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3776. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3777. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3778. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3779. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3780. begin
  3781. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3782. if NewMMReg <> NR_NO then
  3783. begin
  3784. { Remember that the offsets are 8 ahead }
  3785. if ((SourceRef.offset mod 16) = 8) and
  3786. (
  3787. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3788. (SourceRef.base = current_procinfo.framepointer) or
  3789. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3790. ) then
  3791. taicpu(p).opcode := MovAligned
  3792. else
  3793. taicpu(p).opcode := MovUnaligned;
  3794. taicpu(p).opsize := S_XMM;
  3795. taicpu(p).oper[1]^.reg := NewMMReg;
  3796. if ((TargetRef.offset mod 16) = 8) and
  3797. (
  3798. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3799. (TargetRef.base = current_procinfo.framepointer) or
  3800. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3801. ) then
  3802. taicpu(hp1).opcode := MovAligned
  3803. else
  3804. taicpu(hp1).opcode := MovUnaligned;
  3805. taicpu(hp1).opsize := S_XMM;
  3806. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3807. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3808. RemoveInstruction(hp2);
  3809. RemoveInstruction(hp3);
  3810. Result := True;
  3811. Exit;
  3812. end;
  3813. end;
  3814. end
  3815. else
  3816. begin
  3817. { See if the next references are 8 less rather than 8 greater }
  3818. Dec(SourceRef.offset, 16); { -8 the other way }
  3819. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3820. begin
  3821. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3822. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3823. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3824. GetNextInstruction(hp2, hp3) and
  3825. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3826. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3827. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3828. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3829. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3830. begin
  3831. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3832. if NewMMReg <> NR_NO then
  3833. begin
  3834. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3835. if ((SourceRef.offset mod 16) = 0) and
  3836. (
  3837. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3838. (SourceRef.base = current_procinfo.framepointer) or
  3839. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3840. ) then
  3841. taicpu(hp2).opcode := MovAligned
  3842. else
  3843. taicpu(hp2).opcode := MovUnaligned;
  3844. taicpu(hp2).opsize := S_XMM;
  3845. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3846. if ((TargetRef.offset mod 16) = 0) and
  3847. (
  3848. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3849. (TargetRef.base = current_procinfo.framepointer) or
  3850. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3851. ) then
  3852. taicpu(hp3).opcode := MovAligned
  3853. else
  3854. taicpu(hp3).opcode := MovUnaligned;
  3855. taicpu(hp3).opsize := S_XMM;
  3856. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3857. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3858. RemoveInstruction(hp1);
  3859. RemoveCurrentP(p);
  3860. Result := True;
  3861. Exit;
  3862. end;
  3863. end;
  3864. end;
  3865. end;
  3866. end;
  3867. {$endif x86_64}
  3868. end;
  3869. else
  3870. { The write target should be a reg or a ref }
  3871. InternalError(2021091601);
  3872. end;
  3873. else
  3874. ;
  3875. end;
  3876. end
  3877. else if (taicpu(p).oper[0]^.typ = top_const) and
  3878. { %treg is used afterwards, but all eventualities other
  3879. than the first MOV instruction being a constant are
  3880. covered by DeepMOVOpt, so only check for that }
  3881. (
  3882. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3883. not (cs_opt_size in current_settings.optimizerswitches) or
  3884. (taicpu(hp1).opsize = S_B)
  3885. ) and
  3886. (
  3887. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3888. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3889. ) then
  3890. begin
  3891. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3892. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3893. Include(OptsToCheck, aoc_ForceNewIteration);
  3894. end;
  3895. end;
  3896. Break;
  3897. end;
  3898. end;
  3899. if taicpu(p).oper[0]^.typ = top_reg then
  3900. begin
  3901. { oper[1] is a reference }
  3902. { Saves on a large number of dereferences }
  3903. p_SourceReg := taicpu(p).oper[0]^.reg;
  3904. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  3905. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_SourceReg)
  3906. else
  3907. GetNextInstruction_p := GetNextInstruction(p, hp1);
  3908. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  3909. begin
  3910. if taicpu(p).oper[1]^.typ = top_reg then
  3911. begin
  3912. p_TargetReg := taicpu(p).oper[1]^.reg;
  3913. { Change:
  3914. movl %reg1,%reg2
  3915. ...
  3916. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3917. ...
  3918. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3919. To:
  3920. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3921. ...
  3922. movl x(%reg1),%reg1
  3923. ...
  3924. movl %reg1,%regX
  3925. }
  3926. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  3927. (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3928. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3929. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3930. not RegModifiedBetween(p_TargetReg, p, hp1) and
  3931. GetNextInstructionUsingReg(hp1, hp2, p_TargetReg) and
  3932. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3933. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3934. not RegModifiedBetween(p_SourceReg, hp1, hp2) then
  3935. begin
  3936. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3937. if RegInRef(p_TargetReg, SourceRef) and
  3938. { If %reg1 also appears in the second reference, then it will
  3939. not refer to the same memory block as the first reference }
  3940. not RegInRef(p_SourceReg, SourceRef) then
  3941. begin
  3942. { Check to see if the references match if %reg2 is changed to %reg1 }
  3943. if SourceRef.base = p_TargetReg then
  3944. SourceRef.base := p_SourceReg;
  3945. if SourceRef.index = p_TargetReg then
  3946. SourceRef.index := p_SourceReg;
  3947. { RefsEqual also checks to ensure both references are non-volatile }
  3948. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3949. begin
  3950. taicpu(hp2).loadreg(0, p_SourceReg);
  3951. TransferUsedRegs(TmpUsedRegs);
  3952. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3953. { Make sure the register is allocated between these instructions
  3954. even though it doesn't change value, since it may cause
  3955. optimisations on a later pass to behave incorrectly. (Fixes #41155) }
  3956. AllocRegBetween(p_SourceReg, hp1, hp2, TmpUsedRegs);
  3957. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3958. Result := True;
  3959. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3960. begin
  3961. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3962. RemoveCurrentP(p);
  3963. Exit;
  3964. end
  3965. else
  3966. begin
  3967. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3968. begin
  3969. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3970. RemoveCurrentP(p);
  3971. Exit;
  3972. end;
  3973. end;
  3974. { If we reach this point, p and hp1 weren't actually modified,
  3975. so we can do a bit more work on this pass }
  3976. end;
  3977. end;
  3978. end;
  3979. end;
  3980. end;
  3981. end;
  3982. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  3983. { All the next optimisations require a next instruction }
  3984. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  3985. Exit;
  3986. { Next instruction is also a MOV ? }
  3987. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3988. begin
  3989. if MatchOpType(taicpu(p), top_const, top_ref) and
  3990. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3991. TryConstMerge(p, hp1) then
  3992. begin
  3993. Result := True;
  3994. { In case we have four byte writes in a row, check for 2 more
  3995. right now so we don't have to wait for another iteration of
  3996. pass 1
  3997. }
  3998. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3999. case taicpu(p).opsize of
  4000. S_W:
  4001. begin
  4002. if GetNextInstruction(p, hp1) and
  4003. MatchInstruction(hp1, A_MOV, [S_B]) and
  4004. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4005. GetNextInstruction(hp1, hp2) and
  4006. MatchInstruction(hp2, A_MOV, [S_B]) and
  4007. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4008. { Try to merge the two bytes }
  4009. TryConstMerge(hp1, hp2) then
  4010. { Now try to merge the two words (hp2 will get deleted) }
  4011. TryConstMerge(p, hp1);
  4012. end;
  4013. S_L:
  4014. begin
  4015. { Though this only really benefits x86_64 and not i386, it
  4016. gets a potential optimisation done faster and hence
  4017. reduces the number of times OptPass1MOV is entered }
  4018. if GetNextInstruction(p, hp1) and
  4019. MatchInstruction(hp1, A_MOV, [S_W]) and
  4020. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4021. GetNextInstruction(hp1, hp2) and
  4022. MatchInstruction(hp2, A_MOV, [S_W]) and
  4023. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4024. { Try to merge the two words }
  4025. TryConstMerge(hp1, hp2) then
  4026. { This will always fail on i386, so don't bother
  4027. calling it unless we're doing x86_64 }
  4028. {$ifdef x86_64}
  4029. { Now try to merge the two longwords (hp2 will get deleted) }
  4030. TryConstMerge(p, hp1)
  4031. {$endif x86_64}
  4032. ;
  4033. end;
  4034. else
  4035. ;
  4036. end;
  4037. Exit;
  4038. end;
  4039. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4040. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4041. { mov reg1, mem1 or mov mem1, reg1
  4042. mov mem2, reg2 mov reg2, mem2}
  4043. begin
  4044. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4045. { mov reg1, mem1 or mov mem1, reg1
  4046. mov mem2, reg1 mov reg2, mem1}
  4047. begin
  4048. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4049. { Removes the second statement from
  4050. mov reg1, mem1/reg2
  4051. mov mem1/reg2, reg1 }
  4052. begin
  4053. if taicpu(p).oper[0]^.typ=top_reg then
  4054. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4055. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  4056. RemoveInstruction(hp1);
  4057. Result:=true;
  4058. exit;
  4059. end
  4060. else
  4061. begin
  4062. TransferUsedRegs(TmpUsedRegs);
  4063. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4064. if (taicpu(p).oper[1]^.typ = top_ref) and
  4065. { mov reg1, mem1
  4066. mov mem2, reg1 }
  4067. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4068. GetNextInstruction(hp1, hp2) and
  4069. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4070. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4071. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4072. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4073. { change to
  4074. mov reg1, mem1 mov reg1, mem1
  4075. mov mem2, reg1 cmp reg1, mem2
  4076. cmp mem1, reg1
  4077. }
  4078. begin
  4079. RemoveInstruction(hp2);
  4080. taicpu(hp1).opcode := A_CMP;
  4081. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4082. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4083. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4084. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4085. end;
  4086. end;
  4087. end
  4088. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4089. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4090. begin
  4091. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4092. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4093. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4094. end
  4095. else
  4096. begin
  4097. TransferUsedRegs(TmpUsedRegs);
  4098. if GetNextInstruction(hp1, hp2) and
  4099. MatchOpType(taicpu(p),top_ref,top_reg) and
  4100. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4101. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4102. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4103. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4104. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4105. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4106. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4107. { mov mem1, %reg1
  4108. mov %reg1, mem2
  4109. mov mem2, reg2
  4110. to:
  4111. mov mem1, reg2
  4112. mov reg2, mem2}
  4113. begin
  4114. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4115. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4116. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4117. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4118. RemoveInstruction(hp2);
  4119. Result := True;
  4120. end
  4121. {$ifdef i386}
  4122. { this is enabled for i386 only, as the rules to create the reg sets below
  4123. are too complicated for x86-64, so this makes this code too error prone
  4124. on x86-64
  4125. }
  4126. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4127. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4128. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4129. { mov mem1, reg1 mov mem1, reg1
  4130. mov reg1, mem2 mov reg1, mem2
  4131. mov mem2, reg2 mov mem2, reg1
  4132. to: to:
  4133. mov mem1, reg1 mov mem1, reg1
  4134. mov mem1, reg2 mov reg1, mem2
  4135. mov reg1, mem2
  4136. or (if mem1 depends on reg1
  4137. and/or if mem2 depends on reg2)
  4138. to:
  4139. mov mem1, reg1
  4140. mov reg1, mem2
  4141. mov reg1, reg2
  4142. }
  4143. begin
  4144. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4145. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4146. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4147. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4148. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4149. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4150. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4151. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4152. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4153. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4154. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4155. end
  4156. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4157. begin
  4158. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4159. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4160. end
  4161. else
  4162. begin
  4163. RemoveInstruction(hp2);
  4164. end
  4165. {$endif i386}
  4166. ;
  4167. end;
  4168. end
  4169. { movl [mem1],reg1
  4170. movl [mem1],reg2
  4171. to
  4172. movl [mem1],reg1
  4173. movl reg1,reg2
  4174. }
  4175. else if not CheckMovMov2MovMov2(p, hp1) and
  4176. { movl const1,[mem1]
  4177. movl [mem1],reg1
  4178. to
  4179. movl const1,reg1
  4180. movl reg1,[mem1]
  4181. }
  4182. MatchOpType(Taicpu(p),top_const,top_ref) and
  4183. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4184. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4185. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4186. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4187. begin
  4188. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4189. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4190. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4191. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4192. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4193. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4194. Result:=true;
  4195. exit;
  4196. end;
  4197. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4198. end;
  4199. { search further than the next instruction for a mov (as long as it's not a jump) }
  4200. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4201. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4202. (taicpu(p).oper[1]^.typ = top_reg) and
  4203. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4204. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4205. begin
  4206. { we work with hp2 here, so hp1 can be still used later on when
  4207. checking for GetNextInstruction_p }
  4208. hp3 := hp1;
  4209. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4210. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4211. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4212. TransferUsedRegs(TmpUsedRegs);
  4213. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4214. if NotFirstIteration then
  4215. JumpTracking := TLinkedList.Create
  4216. else
  4217. JumpTracking := nil;
  4218. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4219. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4220. (hp2.typ=ait_instruction) do
  4221. begin
  4222. case taicpu(hp2).opcode of
  4223. A_POP:
  4224. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4225. begin
  4226. if not CrossJump and
  4227. not RegUsedBetween(p_TargetReg, p, hp2) then
  4228. begin
  4229. { We can remove the original MOV since the register
  4230. wasn't used between it and its popping from the stack }
  4231. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4232. RemoveCurrentp(p, hp1);
  4233. Result := True;
  4234. JumpTracking.Free;
  4235. Exit;
  4236. end;
  4237. { Can't go any further }
  4238. Break;
  4239. end;
  4240. A_MOV:
  4241. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4242. ((taicpu(p).oper[0]^.typ=top_const) or
  4243. ((taicpu(p).oper[0]^.typ=top_reg) and
  4244. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4245. )
  4246. ) then
  4247. begin
  4248. { we have
  4249. mov x, %treg
  4250. mov %treg, y
  4251. }
  4252. { We don't need to call UpdateUsedRegs for every instruction between
  4253. p and hp2 because the register we're concerned about will not
  4254. become deallocated (otherwise GetNextInstructionUsingReg would
  4255. have stopped at an earlier instruction). [Kit] }
  4256. TempRegUsed :=
  4257. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4258. RegReadByInstruction(p_TargetReg, hp3) or
  4259. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4260. case taicpu(p).oper[0]^.typ Of
  4261. top_reg:
  4262. begin
  4263. { change
  4264. mov %reg, %treg
  4265. mov %treg, y
  4266. to
  4267. mov %reg, y
  4268. }
  4269. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4270. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4271. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4272. begin
  4273. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4274. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4275. if TempRegUsed then
  4276. begin
  4277. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4278. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4279. { Set the start of the next GetNextInstructionUsingRegCond search
  4280. to start at the entry right before hp2 (which is about to be removed) }
  4281. hp3 := tai(hp2.Previous);
  4282. RemoveInstruction(hp2);
  4283. Include(OptsToCheck, aoc_ForceNewIteration);
  4284. { See if there's more we can optimise }
  4285. Continue;
  4286. end
  4287. else
  4288. begin
  4289. RemoveInstruction(hp2);
  4290. { We can remove the original MOV too }
  4291. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4292. RemoveCurrentP(p, hp1);
  4293. Result:=true;
  4294. JumpTracking.Free;
  4295. Exit;
  4296. end;
  4297. end
  4298. else
  4299. begin
  4300. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4301. taicpu(hp2).loadReg(0, p_SourceReg);
  4302. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4303. { Check to see if the register also appears in the reference }
  4304. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4305. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4306. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4307. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4308. begin
  4309. { Don't remove the first instruction if the temporary register is in use }
  4310. if not TempRegUsed then
  4311. begin
  4312. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4313. RemoveCurrentP(p, hp1);
  4314. Result:=true;
  4315. JumpTracking.Free;
  4316. Exit;
  4317. end;
  4318. { No need to set Result to True here. If there's another instruction later
  4319. on that can be optimised, it will be detected when the main Pass 1 loop
  4320. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4321. hp3 := hp2;
  4322. Continue;
  4323. end;
  4324. end;
  4325. end;
  4326. top_const:
  4327. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4328. begin
  4329. { change
  4330. mov const, %treg
  4331. mov %treg, y
  4332. to
  4333. mov const, y
  4334. }
  4335. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4336. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4337. begin
  4338. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4339. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4340. if TempRegUsed then
  4341. begin
  4342. { Don't remove the first instruction if the temporary register is in use }
  4343. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4344. { No need to set Result to True. If there's another instruction later on
  4345. that can be optimised, it will be detected when the main Pass 1 loop
  4346. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4347. end
  4348. else
  4349. begin
  4350. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4351. RemoveCurrentP(p, hp1);
  4352. Result:=true;
  4353. Exit;
  4354. end;
  4355. end;
  4356. end;
  4357. else
  4358. Internalerror(2019103001);
  4359. end;
  4360. end
  4361. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4362. begin
  4363. if not CrossJump and
  4364. not RegUsedBetween(p_TargetReg, p, hp2) and
  4365. not RegReadByInstruction(p_TargetReg, hp2) then
  4366. begin
  4367. { Register is not used before it is overwritten }
  4368. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4369. RemoveCurrentp(p, hp1);
  4370. Result := True;
  4371. Exit;
  4372. end;
  4373. if (taicpu(p).oper[0]^.typ = top_const) and
  4374. (taicpu(hp2).oper[0]^.typ = top_const) then
  4375. begin
  4376. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4377. begin
  4378. { Same value - register hasn't changed }
  4379. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4380. RemoveInstruction(hp2);
  4381. Include(OptsToCheck, aoc_ForceNewIteration);
  4382. { See if there's more we can optimise }
  4383. Continue;
  4384. end;
  4385. end;
  4386. {$ifdef x86_64}
  4387. end
  4388. { Change:
  4389. movl %reg1l,%reg2l
  4390. ...
  4391. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4392. To:
  4393. movl %reg1l,%reg2l
  4394. ...
  4395. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4396. If %reg1 = %reg3, convert to:
  4397. movl %reg1l,%reg2l
  4398. ...
  4399. andl %reg1l,%reg1l
  4400. }
  4401. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4402. (taicpu(p).oper[0]^.typ = top_reg) and
  4403. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4404. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4405. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4406. begin
  4407. TempRegUsed :=
  4408. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4409. RegReadByInstruction(p_TargetReg, hp3) or
  4410. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4411. taicpu(hp2).opsize := S_L;
  4412. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4413. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4414. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4415. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4416. begin
  4417. { %reg1 = %reg3 }
  4418. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4419. taicpu(hp2).opcode := A_AND;
  4420. end
  4421. else
  4422. begin
  4423. { %reg1 <> %reg3 }
  4424. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4425. end;
  4426. if not TempRegUsed then
  4427. begin
  4428. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4429. RemoveCurrentP(p, hp1);
  4430. Result := True;
  4431. Exit;
  4432. end
  4433. else
  4434. begin
  4435. { Initial instruction wasn't actually changed }
  4436. Include(OptsToCheck, aoc_ForceNewIteration);
  4437. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4438. appears below since %reg1 has technically changed }
  4439. if taicpu(hp2).opcode = A_AND then
  4440. Break;
  4441. end;
  4442. {$endif x86_64}
  4443. end
  4444. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4445. GetNextInstruction(hp2, hp4) and
  4446. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4447. { Optimise the following first:
  4448. movl [mem1],reg1
  4449. movl [mem1],reg2
  4450. to
  4451. movl [mem1],reg1
  4452. movl reg1,reg2
  4453. If [mem1] contains the target register and reg1 is the
  4454. the source register, this optimisation will get missed
  4455. and produce less efficient code later on.
  4456. }
  4457. if CheckMovMov2MovMov2(hp2, hp4) then
  4458. { Initial instruction wasn't actually changed }
  4459. Include(OptsToCheck, aoc_ForceNewIteration);
  4460. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4461. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4462. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4463. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4464. begin
  4465. {
  4466. Change from:
  4467. mov ###, %reg
  4468. ...
  4469. movs/z %reg,%reg (Same register, just different sizes)
  4470. To:
  4471. movs/z ###, %reg (Longer version)
  4472. ...
  4473. (remove)
  4474. }
  4475. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4476. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4477. { Keep the first instruction as mov if ### is a constant }
  4478. if taicpu(p).oper[0]^.typ = top_const then
  4479. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4480. else
  4481. begin
  4482. taicpu(p).opcode := taicpu(hp2).opcode;
  4483. taicpu(p).opsize := taicpu(hp2).opsize;
  4484. end;
  4485. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4486. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4487. RemoveInstruction(hp2);
  4488. Result := True;
  4489. JumpTracking.Free;
  4490. Exit;
  4491. end;
  4492. else
  4493. { Move down to the if-block below };
  4494. end;
  4495. { Also catches MOV/S/Z instructions that aren't modified }
  4496. if taicpu(p).oper[0]^.typ = top_reg then
  4497. begin
  4498. p_SourceReg := taicpu(p).oper[0]^.reg;
  4499. if
  4500. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4501. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4502. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4503. begin
  4504. Result := True;
  4505. { Just in case something didn't get modified (e.g. an
  4506. implicit register). Also, if it does read from this
  4507. register, then there's no longer an advantage to
  4508. changing the register on subsequent instructions.}
  4509. if not RegReadByInstruction(p_TargetReg, hp2) then
  4510. begin
  4511. { If a conditional jump was crossed, do not delete
  4512. the original MOV no matter what }
  4513. if not CrossJump and
  4514. { RegEndOfLife returns True if the register is
  4515. deallocated before the next instruction or has
  4516. been loaded with a new value }
  4517. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4518. begin
  4519. { We can remove the original MOV }
  4520. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4521. RemoveCurrentp(p, hp1);
  4522. JumpTracking.Free;
  4523. Result := True;
  4524. Exit;
  4525. end;
  4526. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4527. begin
  4528. { See if there's more we can optimise }
  4529. hp3 := hp2;
  4530. Continue;
  4531. end;
  4532. end;
  4533. end;
  4534. end;
  4535. { Break out of the while loop under normal circumstances }
  4536. Break;
  4537. end;
  4538. JumpTracking.Free;
  4539. end;
  4540. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4541. (taicpu(p).oper[1]^.typ = top_reg) and
  4542. (taicpu(p).opsize = S_L) and
  4543. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4544. (hp2.typ = ait_instruction) and
  4545. (taicpu(hp2).opcode = A_AND) and
  4546. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4547. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4548. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4549. ) then
  4550. begin
  4551. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4552. begin
  4553. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4554. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4555. begin
  4556. { Optimize out:
  4557. mov x, %reg
  4558. and ffffffffh, %reg
  4559. }
  4560. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4561. RemoveInstruction(hp2);
  4562. Result:=true;
  4563. exit;
  4564. end;
  4565. end;
  4566. end;
  4567. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4568. x >= RetOffset) as it doesn't do anything (it writes either to a
  4569. parameter or to the temporary storage room for the function
  4570. result)
  4571. }
  4572. if IsExitCode(hp1) and
  4573. (taicpu(p).oper[1]^.typ = top_ref) and
  4574. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4575. (
  4576. (
  4577. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4578. not (
  4579. assigned(current_procinfo.procdef.funcretsym) and
  4580. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4581. )
  4582. ) or
  4583. { Also discard writes to the stack that are below the base pointer,
  4584. as this is temporary storage rather than a function result on the
  4585. stack, say. }
  4586. (
  4587. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4588. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4589. )
  4590. ) then
  4591. begin
  4592. RemoveCurrentp(p, hp1);
  4593. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4594. RemoveLastDeallocForFuncRes(p);
  4595. Result:=true;
  4596. exit;
  4597. end;
  4598. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4599. begin
  4600. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4601. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4602. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4603. begin
  4604. { change
  4605. mov reg1, mem1
  4606. test/cmp x, mem1
  4607. to
  4608. mov reg1, mem1
  4609. test/cmp x, reg1
  4610. }
  4611. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4612. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4613. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4614. Result := True;
  4615. Exit;
  4616. end;
  4617. if DoMovCmpMemOpt(p, hp1) then
  4618. begin
  4619. Result := True;
  4620. Exit;
  4621. end;
  4622. end;
  4623. if (taicpu(p).oper[1]^.typ = top_reg) and
  4624. (hp1.typ = ait_instruction) and
  4625. GetNextInstruction(hp1, hp2) and
  4626. MatchInstruction(hp2,A_MOV,[]) and
  4627. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4628. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4629. (
  4630. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4631. {$ifdef x86_64}
  4632. or
  4633. (
  4634. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4635. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4636. )
  4637. {$endif x86_64}
  4638. ) then
  4639. begin
  4640. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4641. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4642. { change movsX/movzX reg/ref, reg2
  4643. add/sub/or/... reg3/$const, reg2
  4644. mov reg2 reg/ref
  4645. dealloc reg2
  4646. to
  4647. add/sub/or/... reg3/$const, reg/ref }
  4648. begin
  4649. TransferUsedRegs(TmpUsedRegs);
  4650. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4651. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4652. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4653. begin
  4654. { by example:
  4655. movswl %si,%eax movswl %si,%eax p
  4656. decl %eax addl %edx,%eax hp1
  4657. movw %ax,%si movw %ax,%si hp2
  4658. ->
  4659. movswl %si,%eax movswl %si,%eax p
  4660. decw %eax addw %edx,%eax hp1
  4661. movw %ax,%si movw %ax,%si hp2
  4662. }
  4663. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4664. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4665. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4666. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4667. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4668. {
  4669. ->
  4670. movswl %si,%eax movswl %si,%eax p
  4671. decw %si addw %dx,%si hp1
  4672. movw %ax,%si movw %ax,%si hp2
  4673. }
  4674. case taicpu(hp1).ops of
  4675. 1:
  4676. begin
  4677. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4678. if taicpu(hp1).oper[0]^.typ=top_reg then
  4679. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4680. end;
  4681. 2:
  4682. begin
  4683. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4684. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4685. (taicpu(hp1).opcode<>A_SHL) and
  4686. (taicpu(hp1).opcode<>A_SHR) and
  4687. (taicpu(hp1).opcode<>A_SAR) then
  4688. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4689. end;
  4690. else
  4691. internalerror(2008042701);
  4692. end;
  4693. {
  4694. ->
  4695. decw %si addw %dx,%si p
  4696. }
  4697. RemoveInstruction(hp2);
  4698. RemoveCurrentP(p, hp1);
  4699. Result:=True;
  4700. Exit;
  4701. end;
  4702. end;
  4703. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4704. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4705. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4706. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4707. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4708. )
  4709. {$ifdef i386}
  4710. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4711. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4712. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4713. {$endif i386}
  4714. then
  4715. { change movsX/movzX reg/ref, reg2
  4716. add/sub/or/... regX/$const, reg2
  4717. mov reg2, reg3
  4718. dealloc reg2
  4719. to
  4720. movsX/movzX reg/ref, reg3
  4721. add/sub/or/... reg3/$const, reg3
  4722. }
  4723. begin
  4724. TransferUsedRegs(TmpUsedRegs);
  4725. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4726. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4727. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4728. begin
  4729. { by example:
  4730. movswl %si,%eax movswl %si,%eax p
  4731. decl %eax addl %edx,%eax hp1
  4732. movw %ax,%si movw %ax,%si hp2
  4733. ->
  4734. movswl %si,%eax movswl %si,%eax p
  4735. decw %eax addw %edx,%eax hp1
  4736. movw %ax,%si movw %ax,%si hp2
  4737. }
  4738. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4739. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4740. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4741. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4742. { limit size of constants as well to avoid assembler errors, but
  4743. check opsize to avoid overflow when left shifting the 1 }
  4744. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4745. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4746. {$ifdef x86_64}
  4747. { Be careful of, for example:
  4748. movl %reg1,%reg2
  4749. addl %reg3,%reg2
  4750. movq %reg2,%reg4
  4751. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4752. }
  4753. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4754. begin
  4755. taicpu(hp2).changeopsize(S_L);
  4756. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4757. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4758. end;
  4759. {$endif x86_64}
  4760. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4761. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4762. if taicpu(p).oper[0]^.typ=top_reg then
  4763. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4764. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4765. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4766. {
  4767. ->
  4768. movswl %si,%eax movswl %si,%eax p
  4769. decw %si addw %dx,%si hp1
  4770. movw %ax,%si movw %ax,%si hp2
  4771. }
  4772. case taicpu(hp1).ops of
  4773. 1:
  4774. begin
  4775. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4776. if taicpu(hp1).oper[0]^.typ=top_reg then
  4777. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4778. end;
  4779. 2:
  4780. begin
  4781. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4782. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4783. (taicpu(hp1).opcode<>A_SHL) and
  4784. (taicpu(hp1).opcode<>A_SHR) and
  4785. (taicpu(hp1).opcode<>A_SAR) then
  4786. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4787. end;
  4788. else
  4789. internalerror(2018111801);
  4790. end;
  4791. {
  4792. ->
  4793. decw %si addw %dx,%si p
  4794. }
  4795. RemoveInstruction(hp2);
  4796. end;
  4797. end;
  4798. end;
  4799. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4800. GetNextInstruction(hp1, hp2) and
  4801. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4802. MatchOperand(Taicpu(p).oper[0]^,0) and
  4803. (Taicpu(p).oper[1]^.typ = top_reg) and
  4804. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4805. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4806. { mov reg1,0
  4807. bts reg1,operand1 --> mov reg1,operand2
  4808. or reg1,operand2 bts reg1,operand1}
  4809. begin
  4810. Taicpu(hp2).opcode:=A_MOV;
  4811. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4812. asml.remove(hp1);
  4813. insertllitem(hp2,hp2.next,hp1);
  4814. RemoveCurrentp(p, hp1);
  4815. Result:=true;
  4816. exit;
  4817. end;
  4818. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4819. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4820. GetNextInstruction(hp1, hp2) and
  4821. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4822. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4823. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4824. { change
  4825. mov reg1,reg2
  4826. sub reg3,reg2
  4827. cmp reg3,reg1
  4828. into
  4829. mov reg1,reg2
  4830. sub reg3,reg2
  4831. }
  4832. begin
  4833. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4834. RemoveInstruction(hp2);
  4835. Result:=true;
  4836. exit;
  4837. end;
  4838. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4839. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4840. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4841. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4842. begin
  4843. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4844. {$ifdef x86_64}
  4845. { Convert:
  4846. movq x(ref),%reg64
  4847. shrq y,%reg64
  4848. To:
  4849. movl x+4(ref),%reg32
  4850. shrl y-32,%reg32 (Remove if y = 32)
  4851. }
  4852. if (taicpu(p).opsize = S_Q) and
  4853. (taicpu(hp1).opcode = A_SHR) and
  4854. (taicpu(hp1).oper[0]^.val >= 32) then
  4855. begin
  4856. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4857. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4858. { Convert to 32-bit }
  4859. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4860. taicpu(p).opsize := S_L;
  4861. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4862. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4863. if (taicpu(hp1).oper[0]^.val = 32) then
  4864. begin
  4865. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4866. RemoveInstruction(hp1);
  4867. end
  4868. else
  4869. begin
  4870. { This will potentially open up more arithmetic operations since
  4871. the peephole optimizer now has a big hint that only the lower
  4872. 32 bits are currently in use (and opcodes are smaller in size) }
  4873. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4874. taicpu(hp1).opsize := S_L;
  4875. Dec(taicpu(hp1).oper[0]^.val, 32);
  4876. DebugMsg(SPeepholeOptimization + PreMessage +
  4877. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4878. end;
  4879. Result := True;
  4880. Exit;
  4881. end;
  4882. {$endif x86_64}
  4883. { Convert:
  4884. movl x(ref),%reg
  4885. shrl $24,%reg
  4886. To:
  4887. movzbl x+3(ref),%reg
  4888. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4889. Also accept sar instead of shr, but convert to movsx instead of movzx
  4890. }
  4891. if taicpu(hp1).opcode = A_SHR then
  4892. MovUnaligned := A_MOVZX
  4893. else
  4894. MovUnaligned := A_MOVSX;
  4895. NewSize := S_NO;
  4896. NewOffset := 0;
  4897. case taicpu(p).opsize of
  4898. S_B:
  4899. { No valid combinations };
  4900. S_W:
  4901. if (taicpu(hp1).oper[0]^.val = 8) then
  4902. begin
  4903. NewSize := S_BW;
  4904. NewOffset := 1;
  4905. end;
  4906. S_L:
  4907. case taicpu(hp1).oper[0]^.val of
  4908. 16:
  4909. begin
  4910. NewSize := S_WL;
  4911. NewOffset := 2;
  4912. end;
  4913. 24:
  4914. begin
  4915. NewSize := S_BL;
  4916. NewOffset := 3;
  4917. end;
  4918. else
  4919. ;
  4920. end;
  4921. {$ifdef x86_64}
  4922. S_Q:
  4923. case taicpu(hp1).oper[0]^.val of
  4924. 32:
  4925. begin
  4926. if taicpu(hp1).opcode = A_SAR then
  4927. begin
  4928. { 32-bit to 64-bit is a distinct instruction }
  4929. MovUnaligned := A_MOVSXD;
  4930. NewSize := S_LQ;
  4931. NewOffset := 4;
  4932. end
  4933. else
  4934. { Should have been handled by MovShr2Mov above }
  4935. InternalError(2022081811);
  4936. end;
  4937. 48:
  4938. begin
  4939. NewSize := S_WQ;
  4940. NewOffset := 6;
  4941. end;
  4942. 56:
  4943. begin
  4944. NewSize := S_BQ;
  4945. NewOffset := 7;
  4946. end;
  4947. else
  4948. ;
  4949. end;
  4950. {$endif x86_64}
  4951. else
  4952. InternalError(2022081810);
  4953. end;
  4954. if (NewSize <> S_NO) and
  4955. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4956. begin
  4957. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4958. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4959. debug_op2str(MovUnaligned);
  4960. {$ifdef x86_64}
  4961. if MovUnaligned <> A_MOVSXD then
  4962. { Don't add size suffix for MOVSXD }
  4963. {$endif x86_64}
  4964. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4965. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4966. taicpu(p).opcode := MovUnaligned;
  4967. taicpu(p).opsize := NewSize;
  4968. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4969. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4970. RemoveInstruction(hp1);
  4971. Result := True;
  4972. Exit;
  4973. end;
  4974. end;
  4975. { Backward optimisation shared with OptPass2MOV }
  4976. if FuncMov2Func(p, hp1) then
  4977. begin
  4978. Result := True;
  4979. Exit;
  4980. end;
  4981. end;
  4982. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4983. var
  4984. hp1 : tai;
  4985. begin
  4986. Result:=false;
  4987. if taicpu(p).ops <> 2 then
  4988. exit;
  4989. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4990. GetNextInstruction(p,hp1) then
  4991. begin
  4992. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4993. (taicpu(hp1).ops = 2) then
  4994. begin
  4995. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4996. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4997. { movXX reg1, mem1 or movXX mem1, reg1
  4998. movXX mem2, reg2 movXX reg2, mem2}
  4999. begin
  5000. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  5001. { movXX reg1, mem1 or movXX mem1, reg1
  5002. movXX mem2, reg1 movXX reg2, mem1}
  5003. begin
  5004. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5005. begin
  5006. { Removes the second statement from
  5007. movXX reg1, mem1/reg2
  5008. movXX mem1/reg2, reg1
  5009. }
  5010. if taicpu(p).oper[0]^.typ=top_reg then
  5011. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  5012. { Removes the second statement from
  5013. movXX mem1/reg1, reg2
  5014. movXX reg2, mem1/reg1
  5015. }
  5016. if (taicpu(p).oper[1]^.typ=top_reg) and
  5017. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  5018. begin
  5019. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  5020. RemoveInstruction(hp1);
  5021. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5022. Result:=true;
  5023. exit;
  5024. end
  5025. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5026. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5027. begin
  5028. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5029. RemoveInstruction(hp1);
  5030. Result:=true;
  5031. exit;
  5032. end;
  5033. end
  5034. end;
  5035. end;
  5036. end;
  5037. end;
  5038. end;
  5039. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5040. var
  5041. hp1 : tai;
  5042. begin
  5043. result:=false;
  5044. { replace
  5045. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5046. MovX %mreg2,%mreg1
  5047. dealloc %mreg2
  5048. by
  5049. <Op>X %mreg2,%mreg1
  5050. ?
  5051. }
  5052. if GetNextInstruction(p,hp1) and
  5053. { we mix single and double opperations here because we assume that the compiler
  5054. generates vmovapd only after double operations and vmovaps only after single operations }
  5055. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5056. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5057. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5058. (taicpu(p).oper[0]^.typ=top_reg) then
  5059. begin
  5060. TransferUsedRegs(TmpUsedRegs);
  5061. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5062. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5063. begin
  5064. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5065. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5066. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5067. RemoveInstruction(hp1);
  5068. result:=true;
  5069. end;
  5070. end;
  5071. end;
  5072. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5073. var
  5074. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5075. JumpLabel, JumpLabel_dist: TAsmLabel;
  5076. FirstValue, SecondValue: TCGInt;
  5077. function OptimizeJump(var InputP: tai): Boolean;
  5078. var
  5079. TempBool: Boolean;
  5080. begin
  5081. Result := False;
  5082. TempBool := True;
  5083. if DoJumpOptimizations(InputP, TempBool) or
  5084. not TempBool then
  5085. begin
  5086. Result := True;
  5087. if Assigned(InputP) then
  5088. begin
  5089. { CollapseZeroDistJump will be set to the label or an align
  5090. before it after the jump if it optimises, whether or not
  5091. the label is live or dead }
  5092. if (InputP.typ = ait_align) or
  5093. (
  5094. (InputP.typ = ait_label) and
  5095. not (tai_label(InputP).labsym.is_used)
  5096. ) then
  5097. GetNextInstruction(InputP, InputP);
  5098. end;
  5099. Exit;
  5100. end;
  5101. end;
  5102. begin
  5103. Result := False;
  5104. if (taicpu(p).oper[0]^.typ = top_const) and
  5105. (taicpu(p).oper[0]^.val <> -1) then
  5106. begin
  5107. { Convert unsigned maximum constants to -1 to aid optimisation }
  5108. case taicpu(p).opsize of
  5109. S_B:
  5110. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5111. begin
  5112. taicpu(p).oper[0]^.val := -1;
  5113. Result := True;
  5114. Exit;
  5115. end;
  5116. S_W:
  5117. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5118. begin
  5119. taicpu(p).oper[0]^.val := -1;
  5120. Result := True;
  5121. Exit;
  5122. end;
  5123. S_L:
  5124. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5125. begin
  5126. taicpu(p).oper[0]^.val := -1;
  5127. Result := True;
  5128. Exit;
  5129. end;
  5130. {$ifdef x86_64}
  5131. S_Q:
  5132. { Storing anything greater than $7FFFFFFF is not possible so do
  5133. nothing };
  5134. {$endif x86_64}
  5135. else
  5136. InternalError(2021121001);
  5137. end;
  5138. end;
  5139. if GetNextInstruction(p, hp1) and
  5140. TrySwapMovCmp(p, hp1) then
  5141. begin
  5142. Result := True;
  5143. Exit;
  5144. end;
  5145. p_label := nil;
  5146. JumpLabel := nil;
  5147. if MatchInstruction(hp1, A_Jcc, []) then
  5148. begin
  5149. if OptimizeJump(hp1) then
  5150. begin
  5151. Result := True;
  5152. if Assigned(hp1) then
  5153. begin
  5154. { CollapseZeroDistJump will be set to the label or an align
  5155. before it after the jump if it optimises, whether or not
  5156. the label is live or dead }
  5157. if (hp1.typ = ait_align) or
  5158. (
  5159. (hp1.typ = ait_label) and
  5160. not (tai_label(hp1).labsym.is_used)
  5161. ) then
  5162. GetNextInstruction(hp1, hp1);
  5163. end;
  5164. TransferUsedRegs(TmpUsedRegs);
  5165. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5166. if not Assigned(hp1) or
  5167. (
  5168. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5169. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5170. ) then
  5171. begin
  5172. { No more conditional jumps; conditional statement is no longer required }
  5173. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5174. RemoveCurrentP(p);
  5175. end;
  5176. Exit;
  5177. end;
  5178. if IsJumpToLabel(taicpu(hp1)) then
  5179. begin
  5180. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5181. if Assigned(JumpLabel) then
  5182. p_label := getlabelwithsym(JumpLabel);
  5183. end;
  5184. end;
  5185. { Search for:
  5186. test $x,(reg/ref)
  5187. jne @lbl1
  5188. test $y,(reg/ref) (same register or reference)
  5189. jne @lbl1
  5190. Change to:
  5191. test $(x or y),(reg/ref)
  5192. jne @lbl1
  5193. (Note, this doesn't work with je instead of jne)
  5194. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5195. Also search for:
  5196. test $x,(reg/ref)
  5197. je @lbl1
  5198. ...
  5199. test $y,(reg/ref)
  5200. je/jne @lbl2
  5201. If (x or y) = x, then the second jump is deterministic
  5202. }
  5203. if (
  5204. (
  5205. (taicpu(p).oper[0]^.typ = top_const) or
  5206. (
  5207. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5208. (taicpu(p).oper[0]^.typ = top_reg) and
  5209. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5210. )
  5211. ) and
  5212. MatchInstruction(hp1, A_JCC, [])
  5213. ) then
  5214. begin
  5215. if (taicpu(p).oper[0]^.typ = top_reg) and
  5216. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5217. FirstValue := -1
  5218. else
  5219. FirstValue := taicpu(p).oper[0]^.val;
  5220. { If we have several test/jne's in a row, it might be the case that
  5221. the second label doesn't go to the same location, but the one
  5222. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5223. so accommodate for this with a while loop.
  5224. }
  5225. hp1_last := hp1;
  5226. while (
  5227. (
  5228. (taicpu(p).oper[1]^.typ = top_reg) and
  5229. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5230. ) or GetNextInstruction(hp1_last, p_dist)
  5231. ) and (p_dist.typ = ait_instruction) do
  5232. begin
  5233. if (
  5234. (
  5235. (taicpu(p_dist).opcode = A_TEST) and
  5236. (
  5237. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5238. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5239. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5240. )
  5241. ) or
  5242. (
  5243. { cmp 0,%reg = test %reg,%reg }
  5244. (taicpu(p_dist).opcode = A_CMP) and
  5245. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5246. )
  5247. ) and
  5248. { Make sure the destination operands are actually the same }
  5249. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5250. GetNextInstruction(p_dist, hp1_dist) and
  5251. MatchInstruction(hp1_dist, A_JCC, []) then
  5252. begin
  5253. if OptimizeJump(hp1_dist) then
  5254. begin
  5255. Result := True;
  5256. Exit;
  5257. end;
  5258. if
  5259. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5260. (
  5261. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5262. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5263. ) then
  5264. SecondValue := -1
  5265. else
  5266. SecondValue := taicpu(p_dist).oper[0]^.val;
  5267. { If both of the TEST constants are identical, delete the
  5268. second TEST that is unnecessary (be careful though, just
  5269. in case the flags are modified in between) }
  5270. if (FirstValue = SecondValue) then
  5271. begin
  5272. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5273. begin
  5274. { Since the second jump's condition is a subset of the first, we
  5275. know it will never branch because the first jump dominates it.
  5276. Get it out of the way now rather than wait for the jump
  5277. optimisations for a speed boost. }
  5278. if IsJumpToLabel(taicpu(hp1_dist)) then
  5279. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5280. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5281. RemoveInstruction(hp1_dist);
  5282. Result := True;
  5283. end
  5284. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5285. begin
  5286. { If the inverse of the first condition is a subset of the second,
  5287. the second one will definitely branch if the first one doesn't }
  5288. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5289. { We can remove the TEST instruction too }
  5290. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5291. RemoveInstruction(p_dist);
  5292. MakeUnconditional(taicpu(hp1_dist));
  5293. RemoveDeadCodeAfterJump(hp1_dist);
  5294. { Since the jump is now unconditional, we can't
  5295. continue any further with this particular
  5296. optimisation. The original TEST is still intact
  5297. though, so there might be something else we can
  5298. do }
  5299. Include(OptsToCheck, aoc_ForceNewIteration);
  5300. Break;
  5301. end;
  5302. if Result or
  5303. { If a jump wasn't removed or made unconditional, only
  5304. remove the identical TEST instruction if the flags
  5305. weren't modified }
  5306. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5307. begin
  5308. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5309. RemoveInstruction(p_dist);
  5310. { If the jump was removed or made unconditional, we
  5311. don't need to allocate NR_DEFAULTFLAGS over the
  5312. entire range }
  5313. if not Result then
  5314. begin
  5315. { Mark the flags as 'in use' over the entire range }
  5316. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5317. { Speed gain - continue search from the Jcc instruction }
  5318. hp1_last := hp1_dist;
  5319. { Only the TEST instruction was removed, and the
  5320. original was unchanged, so we can safely do
  5321. another iteration of the while loop }
  5322. Include(OptsToCheck, aoc_ForceNewIteration);
  5323. Continue;
  5324. end;
  5325. Exit;
  5326. end;
  5327. end;
  5328. hp1_last := nil;
  5329. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5330. (
  5331. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5332. { Always adjacent under -O2 and under }
  5333. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5334. (
  5335. GetNextInstruction(hp1, hp1_last) and
  5336. (hp1_last = p_dist)
  5337. )
  5338. ) and
  5339. (
  5340. (
  5341. { Test the following variant:
  5342. test $x,(reg/ref)
  5343. jne @lbl1
  5344. test $y,(reg/ref)
  5345. je @lbl2
  5346. @lbl1:
  5347. Becomes:
  5348. test $(x or y),(reg/ref)
  5349. je @lbl2
  5350. @lbl1: (may become a dead label)
  5351. }
  5352. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5353. GetNextInstruction(hp1_dist, hp1_last) and
  5354. (hp1_last = p_label)
  5355. ) or
  5356. (
  5357. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5358. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5359. then the second jump will never branch, so it can also be
  5360. removed regardless of where it goes }
  5361. (
  5362. (FirstValue = -1) or
  5363. (SecondValue = -1) or
  5364. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5365. )
  5366. )
  5367. ) then
  5368. begin
  5369. { Same jump location... can be a register since nothing's changed }
  5370. { If any of the entries are equivalent to test %reg,%reg, then the
  5371. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5372. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5373. if (hp1_last = p_label) then
  5374. begin
  5375. { Variant }
  5376. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5377. RemoveInstruction(p_dist);
  5378. if Assigned(JumpLabel) then
  5379. JumpLabel.decrefs;
  5380. RemoveInstruction(hp1);
  5381. end
  5382. else
  5383. begin
  5384. { Only remove the second test if no jumps or other conditional instructions follow }
  5385. TransferUsedRegs(TmpUsedRegs);
  5386. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5387. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5388. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5389. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5390. begin
  5391. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5392. RemoveInstruction(p_dist);
  5393. { Remove the first jump, not the second, to keep
  5394. any register deallocations between the second
  5395. TEST/JNE pair in the same place. Aids future
  5396. optimisation. }
  5397. if Assigned(JumpLabel) then
  5398. JumpLabel.decrefs;
  5399. RemoveInstruction(hp1);
  5400. end
  5401. else
  5402. begin
  5403. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5404. if IsJumpToLabel(taicpu(hp1_dist)) then
  5405. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5406. { Remove second jump in this instance }
  5407. RemoveInstruction(hp1_dist);
  5408. end;
  5409. end;
  5410. Result := True;
  5411. Exit;
  5412. end;
  5413. end;
  5414. if { If -O2 and under, it may stop on any old instruction }
  5415. (cs_opt_level3 in current_settings.optimizerswitches) and
  5416. (taicpu(p).oper[1]^.typ = top_reg) and
  5417. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5418. begin
  5419. hp1_last := p_dist;
  5420. Continue;
  5421. end;
  5422. Break;
  5423. end;
  5424. end;
  5425. { Search for:
  5426. test %reg,%reg
  5427. j(c1) @lbl1
  5428. ...
  5429. @lbl:
  5430. test %reg,%reg (same register)
  5431. j(c2) @lbl2
  5432. If c2 is a subset of c1, change to:
  5433. test %reg,%reg
  5434. j(c1) @lbl2
  5435. (@lbl1 may become a dead label as a result)
  5436. }
  5437. if (taicpu(p).oper[1]^.typ = top_reg) and
  5438. (taicpu(p).oper[0]^.typ = top_reg) and
  5439. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5440. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5441. Assigned(p_label) and
  5442. GetNextInstruction(p_label, p_dist) and
  5443. MatchInstruction(p_dist, A_TEST, []) and
  5444. { It's fine if the second test uses smaller sub-registers }
  5445. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5446. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5447. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5448. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5449. GetNextInstruction(p_dist, hp1_dist) and
  5450. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5451. begin
  5452. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5453. if JumpLabel = JumpLabel_dist then
  5454. { This is an infinite loop }
  5455. Exit;
  5456. { Best optimisation when the first condition is a subset (or equal) of the second }
  5457. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5458. begin
  5459. { Any registers used here will already be allocated }
  5460. if Assigned(JumpLabel) then
  5461. JumpLabel.DecRefs;
  5462. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5463. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5464. Result := True;
  5465. Exit;
  5466. end;
  5467. end;
  5468. end;
  5469. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5470. var
  5471. hp1, hp2: tai;
  5472. ActiveReg: TRegister;
  5473. OldOffset: asizeint;
  5474. ThisConst: TCGInt;
  5475. function RegDeallocated: Boolean;
  5476. begin
  5477. TransferUsedRegs(TmpUsedRegs);
  5478. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5479. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5480. end;
  5481. begin
  5482. result:=false;
  5483. hp1 := nil;
  5484. { replace
  5485. addX const,%reg1
  5486. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5487. dealloc %reg1
  5488. by
  5489. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5490. }
  5491. if MatchOpType(taicpu(p),top_const,top_reg) then
  5492. begin
  5493. ActiveReg := taicpu(p).oper[1]^.reg;
  5494. { Ensures the entire register was updated }
  5495. if (taicpu(p).opsize >= S_L) and
  5496. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5497. MatchInstruction(hp1,A_LEA,[]) and
  5498. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5499. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5500. (
  5501. { Cover the case where the register in the reference is also the destination register }
  5502. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5503. (
  5504. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5505. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5506. RegDeallocated
  5507. )
  5508. ) then
  5509. begin
  5510. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5511. {$push}
  5512. {$R-}{$Q-}
  5513. { Explicitly disable overflow checking for these offset calculation
  5514. as those do not matter for the final result }
  5515. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5516. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5517. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5518. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5519. {$pop}
  5520. {$ifdef x86_64}
  5521. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5522. begin
  5523. { Overflow; abort }
  5524. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5525. end
  5526. else
  5527. {$endif x86_64}
  5528. begin
  5529. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5530. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5531. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5532. RemoveCurrentP(p, hp1)
  5533. else
  5534. RemoveCurrentP(p);
  5535. result:=true;
  5536. Exit;
  5537. end;
  5538. end;
  5539. if (
  5540. { Save calling GetNextInstructionUsingReg again }
  5541. Assigned(hp1) or
  5542. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5543. ) and
  5544. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5545. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5546. begin
  5547. if taicpu(hp1).oper[0]^.typ = top_const then
  5548. begin
  5549. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5550. if taicpu(hp1).opcode = A_ADD then
  5551. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5552. else
  5553. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5554. Result := True;
  5555. { Handle any overflows }
  5556. case taicpu(p).opsize of
  5557. S_B:
  5558. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5559. S_W:
  5560. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5561. S_L:
  5562. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5563. {$ifdef x86_64}
  5564. S_Q:
  5565. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5566. { Overflow; abort }
  5567. Result := False
  5568. else
  5569. taicpu(p).oper[0]^.val := ThisConst;
  5570. {$endif x86_64}
  5571. else
  5572. InternalError(2021102610);
  5573. end;
  5574. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5575. if Result then
  5576. begin
  5577. if (taicpu(p).oper[0]^.val < 0) and
  5578. (
  5579. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5580. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5581. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5582. ) then
  5583. begin
  5584. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5585. taicpu(p).opcode := A_SUB;
  5586. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5587. end
  5588. else
  5589. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5590. RemoveInstruction(hp1);
  5591. end;
  5592. end
  5593. else
  5594. begin
  5595. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5596. TransferUsedRegs(TmpUsedRegs);
  5597. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5598. hp2 := p;
  5599. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5600. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5601. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5602. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5603. begin
  5604. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5605. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5606. Asml.Remove(p);
  5607. Asml.InsertAfter(p, hp1);
  5608. p := hp1;
  5609. Result := True;
  5610. Exit;
  5611. end;
  5612. end;
  5613. end;
  5614. if DoArithCombineOpt(p) then
  5615. Result:=true;
  5616. end;
  5617. end;
  5618. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5619. var
  5620. hp1, hp2: tai;
  5621. ref: Integer;
  5622. saveref: treference;
  5623. offsetcalc: Int64;
  5624. TempReg: TRegister;
  5625. Multiple: TCGInt;
  5626. Adjacent, IntermediateRegDiscarded: Boolean;
  5627. begin
  5628. Result:=false;
  5629. { play save and throw an error if LEA uses a seg register prefix,
  5630. this is most likely an error somewhere else }
  5631. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5632. internalerror(2022022001);
  5633. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5634. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5635. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5636. (
  5637. { do not mess with leas accessing the stack pointer
  5638. unless it's a null operation }
  5639. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5640. (
  5641. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5642. (taicpu(p).oper[0]^.ref^.offset = 0)
  5643. )
  5644. ) and
  5645. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5646. begin
  5647. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5648. begin
  5649. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5650. begin
  5651. taicpu(p).opcode := A_MOV;
  5652. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5653. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5654. end
  5655. else
  5656. begin
  5657. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5658. RemoveCurrentP(p);
  5659. end;
  5660. Result:=true;
  5661. exit;
  5662. end
  5663. else if (
  5664. { continue to use lea to adjust the stack pointer,
  5665. it is the recommended way, but only if not optimizing for size }
  5666. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5667. (cs_opt_size in current_settings.optimizerswitches)
  5668. ) and
  5669. { If the flags register is in use, don't change the instruction
  5670. to an ADD otherwise this will scramble the flags. [Kit] }
  5671. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5672. ConvertLEA(taicpu(p)) then
  5673. begin
  5674. Result:=true;
  5675. exit;
  5676. end;
  5677. end;
  5678. { Don't optimise if the stack or frame pointer is the destination register }
  5679. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5680. Exit;
  5681. if GetNextInstruction(p,hp1) and
  5682. (hp1.typ=ait_instruction) then
  5683. begin
  5684. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5685. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5686. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5687. begin
  5688. TransferUsedRegs(TmpUsedRegs);
  5689. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5690. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5691. begin
  5692. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5693. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5694. RemoveInstruction(hp1);
  5695. result:=true;
  5696. exit;
  5697. end;
  5698. end;
  5699. { changes
  5700. lea <ref1>, reg1
  5701. <op> ...,<ref. with reg1>,...
  5702. to
  5703. <op> ...,<ref1>,... }
  5704. { find a reference which uses reg1 }
  5705. 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
  5706. ref:=0
  5707. 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
  5708. ref:=1
  5709. else
  5710. ref:=-1;
  5711. if (ref<>-1) and
  5712. { reg1 must be either the base or the index }
  5713. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5714. begin
  5715. { reg1 can be removed from the reference }
  5716. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5717. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5718. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5719. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5720. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5721. else
  5722. Internalerror(2019111201);
  5723. { check if the can insert all data of the lea into the second instruction }
  5724. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5725. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5726. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5727. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5728. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5729. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5730. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5731. {$ifdef x86_64}
  5732. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5733. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5734. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5735. )
  5736. {$endif x86_64}
  5737. then
  5738. begin
  5739. { reg1 might not used by the second instruction after it is remove from the reference }
  5740. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5741. begin
  5742. TransferUsedRegs(TmpUsedRegs);
  5743. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5744. { reg1 is not updated so it might not be used afterwards }
  5745. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5746. begin
  5747. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5748. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5749. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5750. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5751. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5752. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5753. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5754. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5755. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5756. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5757. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5758. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5759. RemoveCurrentP(p, hp1);
  5760. result:=true;
  5761. exit;
  5762. end
  5763. end;
  5764. end;
  5765. { recover }
  5766. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5767. end;
  5768. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5769. if Adjacent or
  5770. { Check further ahead (up to 2 instructions ahead for -O2) }
  5771. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5772. begin
  5773. { Check common LEA/LEA conditions }
  5774. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5775. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5776. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5777. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5778. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5779. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5780. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5781. (
  5782. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5783. calling it (since it calls GetNextInstruction) }
  5784. Adjacent or
  5785. (
  5786. (
  5787. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5788. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5789. ) and (
  5790. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5791. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5792. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5793. )
  5794. )
  5795. ) then
  5796. begin
  5797. TransferUsedRegs(TmpUsedRegs);
  5798. hp2 := p;
  5799. repeat
  5800. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5801. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5802. IntermediateRegDiscarded :=
  5803. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5804. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5805. { changes
  5806. lea offset1(regX,scale), reg1
  5807. lea offset2(reg1,reg1), reg2
  5808. to
  5809. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5810. and
  5811. lea offset1(regX,scale1), reg1
  5812. lea offset2(reg1,scale2), reg2
  5813. to
  5814. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5815. and
  5816. lea offset1(regX,scale1), reg1
  5817. lea offset2(reg3,reg1,scale2), reg2
  5818. to
  5819. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5820. ... so long as the final scale does not exceed 8
  5821. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5822. }
  5823. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5824. (
  5825. { Don't optimise if size is a concern and the intermediate register remains in use }
  5826. IntermediateRegDiscarded or
  5827. (
  5828. not (cs_opt_size in current_settings.optimizerswitches) and
  5829. { If the intermediate register is not discarded, it must not
  5830. appear in the first LEA's reference. (Fixes #41166) }
  5831. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  5832. )
  5833. ) and
  5834. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5835. (
  5836. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5837. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5838. ) and (
  5839. (
  5840. { lea (reg1,scale2), reg2 variant }
  5841. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5842. (
  5843. Adjacent or
  5844. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5845. ) and
  5846. (
  5847. (
  5848. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5849. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5850. ) or (
  5851. { lea (regX,regX), reg1 variant }
  5852. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5853. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5854. )
  5855. )
  5856. ) or (
  5857. { lea (reg1,reg1), reg1 variant }
  5858. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5859. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5860. )
  5861. ) then
  5862. begin
  5863. { Make everything homogeneous to make calculations easier }
  5864. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5865. begin
  5866. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5867. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5868. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5869. else
  5870. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5871. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5872. end;
  5873. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5874. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5875. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5876. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5877. begin
  5878. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5879. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5880. begin
  5881. { Put the register to change in the index register }
  5882. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5883. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5884. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5885. end;
  5886. { Change lea (reg,reg) to lea(,reg,2) }
  5887. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5888. begin
  5889. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5890. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5891. end;
  5892. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5893. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5894. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5895. { Just to prevent miscalculations }
  5896. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5897. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5898. else
  5899. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5900. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5901. if IntermediateRegDiscarded then
  5902. begin
  5903. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5904. RemoveCurrentP(p);
  5905. end
  5906. else
  5907. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5908. result:=true;
  5909. exit;
  5910. end;
  5911. end;
  5912. { changes
  5913. lea offset1(regX), reg1
  5914. lea offset2(reg1), reg2
  5915. to
  5916. lea offset1+offset2(regX), reg2 }
  5917. if (
  5918. { Don't optimise if size is a concern and the intermediate register remains in use }
  5919. IntermediateRegDiscarded or
  5920. (
  5921. not (cs_opt_size in current_settings.optimizerswitches) and
  5922. { If the intermediate register is not discarded, it must not
  5923. appear in the first LEA's reference. (Fixes #41166) }
  5924. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  5925. )
  5926. ) and
  5927. (
  5928. (
  5929. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5930. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5931. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5932. ) or (
  5933. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5934. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5935. (
  5936. (
  5937. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5938. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5939. ) or (
  5940. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5941. (
  5942. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5943. (
  5944. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5945. (
  5946. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5947. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5948. )
  5949. )
  5950. )
  5951. )
  5952. )
  5953. )
  5954. ) then
  5955. begin
  5956. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5957. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5958. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5959. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5960. begin
  5961. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5962. begin
  5963. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5964. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5965. { if the register is used as index and base, we have to increase for base as well
  5966. and adapt base }
  5967. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5968. begin
  5969. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5970. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5971. end;
  5972. end
  5973. else
  5974. begin
  5975. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5976. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5977. end;
  5978. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5979. begin
  5980. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5981. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5982. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5983. { Catch the situation where the base = index
  5984. and treat this as *2. The scalefactor of
  5985. p will be 0 or 1 due to the conditional
  5986. checks above. Fixes i40647 }
  5987. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5988. else
  5989. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5990. end;
  5991. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5992. if IntermediateRegDiscarded then
  5993. begin
  5994. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5995. RemoveCurrentP(p);
  5996. end
  5997. else
  5998. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5999. result:=true;
  6000. exit;
  6001. end;
  6002. end;
  6003. end;
  6004. { Change:
  6005. leal/q $x(%reg1),%reg2
  6006. ...
  6007. shll/q $y,%reg2
  6008. To:
  6009. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  6010. }
  6011. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6012. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  6013. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6014. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6015. (taicpu(hp1).oper[0]^.val <= 3) then
  6016. begin
  6017. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  6018. TransferUsedRegs(TmpUsedRegs);
  6019. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6020. if
  6021. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  6022. (this works even if scalefactor is zero) }
  6023. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  6024. { Ensure offset doesn't go out of bounds }
  6025. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  6026. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  6027. (
  6028. (
  6029. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  6030. (
  6031. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6032. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6033. (
  6034. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6035. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6036. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6037. )
  6038. )
  6039. ) or (
  6040. (
  6041. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6042. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6043. ) and
  6044. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6045. )
  6046. ) then
  6047. begin
  6048. repeat
  6049. with taicpu(p).oper[0]^.ref^ do
  6050. begin
  6051. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6052. if index = base then
  6053. begin
  6054. if Multiple > 4 then
  6055. { Optimisation will no longer work because resultant
  6056. scale factor will exceed 8 }
  6057. Break;
  6058. base := NR_NO;
  6059. scalefactor := 2;
  6060. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6061. end
  6062. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6063. begin
  6064. { Scale factor only works on the index register }
  6065. index := base;
  6066. base := NR_NO;
  6067. end;
  6068. { For safety }
  6069. if scalefactor <= 1 then
  6070. begin
  6071. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6072. scalefactor := Multiple;
  6073. end
  6074. else
  6075. begin
  6076. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6077. scalefactor := scalefactor * Multiple;
  6078. end;
  6079. offset := offset * Multiple;
  6080. end;
  6081. RemoveInstruction(hp1);
  6082. Result := True;
  6083. Exit;
  6084. { This repeat..until loop exists for the benefit of Break }
  6085. until True;
  6086. end;
  6087. end;
  6088. end;
  6089. end;
  6090. end;
  6091. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6092. var
  6093. hp1 : tai;
  6094. SubInstr: Boolean;
  6095. ThisConst: TCGInt;
  6096. const
  6097. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6098. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6099. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6100. begin
  6101. Result := False;
  6102. if taicpu(p).oper[0]^.typ <> top_const then
  6103. { Should have been confirmed before calling }
  6104. InternalError(2021102601);
  6105. SubInstr := (taicpu(p).opcode = A_SUB);
  6106. if GetLastInstruction(p, hp1) and
  6107. (hp1.typ = ait_instruction) and
  6108. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6109. begin
  6110. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6111. { Bad size }
  6112. InternalError(2022042001);
  6113. case taicpu(hp1).opcode Of
  6114. A_INC:
  6115. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6116. begin
  6117. if SubInstr then
  6118. ThisConst := taicpu(p).oper[0]^.val - 1
  6119. else
  6120. ThisConst := taicpu(p).oper[0]^.val + 1;
  6121. end
  6122. else
  6123. Exit;
  6124. A_DEC:
  6125. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6126. begin
  6127. if SubInstr then
  6128. ThisConst := taicpu(p).oper[0]^.val + 1
  6129. else
  6130. ThisConst := taicpu(p).oper[0]^.val - 1;
  6131. end
  6132. else
  6133. Exit;
  6134. A_SUB:
  6135. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6136. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6137. begin
  6138. if SubInstr then
  6139. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6140. else
  6141. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6142. end
  6143. else
  6144. Exit;
  6145. A_ADD:
  6146. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6147. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6148. begin
  6149. if SubInstr then
  6150. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6151. else
  6152. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6153. end
  6154. else
  6155. Exit;
  6156. else
  6157. Exit;
  6158. end;
  6159. { Check that the values are in range }
  6160. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6161. { Overflow; abort }
  6162. Exit;
  6163. if (ThisConst = 0) then
  6164. begin
  6165. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6166. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6167. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6168. RemoveInstruction(hp1);
  6169. hp1 := tai(p.next);
  6170. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6171. if not GetLastInstruction(hp1, p) then
  6172. p := hp1;
  6173. end
  6174. else
  6175. begin
  6176. if taicpu(hp1).opercnt=1 then
  6177. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6178. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6179. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6180. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6181. else
  6182. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6183. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6184. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6185. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6186. RemoveInstruction(hp1);
  6187. taicpu(p).loadconst(0, ThisConst);
  6188. end;
  6189. Result := True;
  6190. end;
  6191. end;
  6192. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6193. begin
  6194. Result := False;
  6195. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6196. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6197. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6198. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6199. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6200. (
  6201. (
  6202. (taicpu(hp1).opcode = A_TEST)
  6203. ) or (
  6204. (taicpu(hp1).opcode = A_CMP) and
  6205. { A sanity check more than anything }
  6206. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6207. )
  6208. ) then
  6209. begin
  6210. { change
  6211. mov mem, %reg
  6212. ...
  6213. cmp/test x, %reg / test %reg,%reg
  6214. (reg deallocated)
  6215. to
  6216. cmp/test x, mem / cmp 0, mem
  6217. }
  6218. TransferUsedRegs(TmpUsedRegs);
  6219. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6220. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6221. begin
  6222. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6223. if (taicpu(hp1).opcode = A_TEST) and
  6224. (
  6225. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6226. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6227. ) then
  6228. begin
  6229. taicpu(hp1).opcode := A_CMP;
  6230. taicpu(hp1).loadconst(0, 0);
  6231. end;
  6232. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6233. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6234. RemoveCurrentP(p);
  6235. if (p <> hp1) then
  6236. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6237. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6238. { Make sure the flags are allocated across the CMP instruction }
  6239. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6240. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6241. Result := True;
  6242. Exit;
  6243. end;
  6244. end;
  6245. end;
  6246. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6247. var
  6248. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6249. ThisReg, SecondReg: TRegister;
  6250. JumpLoc: TAsmLabel;
  6251. NewSize: TOpSize;
  6252. begin
  6253. Result := False;
  6254. {
  6255. Convert:
  6256. j<c> .L1
  6257. .L2:
  6258. mov 1,reg
  6259. jmp .L3 (or ret, although it might not be a RET yet)
  6260. .L1:
  6261. mov 0,reg
  6262. jmp .L3 (or ret)
  6263. ( As long as .L3 <> .L1 or .L2)
  6264. To:
  6265. mov 0,reg
  6266. set<not(c)> reg
  6267. jmp .L3 (or ret)
  6268. .L2:
  6269. mov 1,reg
  6270. jmp .L3 (or ret)
  6271. .L1:
  6272. mov 0,reg
  6273. jmp .L3 (or ret)
  6274. }
  6275. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6276. Exit;
  6277. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6278. if GetNextInstruction(hp_label, hp2) and
  6279. MatchInstruction(hp2,A_MOV,[]) and
  6280. (taicpu(hp2).oper[0]^.typ = top_const) and
  6281. (
  6282. (
  6283. (taicpu(hp2).oper[1]^.typ = top_reg)
  6284. {$ifdef i386}
  6285. { Under i386, ESI, EDI, EBP and ESP
  6286. don't have an 8-bit representation }
  6287. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6288. {$endif i386}
  6289. ) or (
  6290. {$ifdef i386}
  6291. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6292. {$endif i386}
  6293. (taicpu(hp2).opsize = S_B)
  6294. )
  6295. ) and
  6296. GetNextInstruction(hp2, hp3) and
  6297. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6298. (
  6299. (taicpu(hp3).opcode=A_RET) or
  6300. (
  6301. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6302. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6303. )
  6304. ) and
  6305. GetNextInstruction(hp3, hp4) and
  6306. FindLabel(JumpLoc, hp4) and
  6307. (
  6308. not (cs_opt_size in current_settings.optimizerswitches) or
  6309. { If the initial jump is the label's only reference, then it will
  6310. become a dead label if the other conditions are met and hence
  6311. remove at least 2 instructions, including a jump }
  6312. (JumpLoc.getrefs = 1)
  6313. ) and
  6314. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6315. that will be optimised out }
  6316. GetNextInstruction(hp4, hp5) and
  6317. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6318. (taicpu(hp5).oper[0]^.typ = top_const) and
  6319. (
  6320. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6321. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6322. ) and
  6323. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6324. GetNextInstruction(hp5,hp6) and
  6325. (
  6326. not (hp6.typ in [ait_align, ait_label]) or
  6327. SkipLabels(hp6, hp6)
  6328. ) and
  6329. (hp6.typ=ait_instruction) then
  6330. begin
  6331. { First, let's look at the two jumps that are hp3 and hp6 }
  6332. if not
  6333. (
  6334. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6335. (
  6336. (taicpu(hp6).opcode=A_RET) or
  6337. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6338. )
  6339. ) then
  6340. { If condition is False, then the JMP/RET instructions matched conventionally }
  6341. begin
  6342. { See if one of the jumps can be instantly converted into a RET }
  6343. if (taicpu(hp3).opcode=A_JMP) then
  6344. begin
  6345. { Reuse hp5 }
  6346. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6347. { Make sure hp5 doesn't jump back to .L1 (zero distance jump) or .L2 (infinite loop) }
  6348. if not Assigned(hp5) or (hp5 = hp_label) or (hp5 = hp4) or not GetNextInstruction(hp5, hp5) then
  6349. Exit;
  6350. if MatchInstruction(hp5, A_RET, []) then
  6351. begin
  6352. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6353. ConvertJumpToRET(hp3, hp5);
  6354. Result := True;
  6355. end
  6356. else
  6357. Exit;
  6358. end;
  6359. if (taicpu(hp6).opcode=A_JMP) then
  6360. begin
  6361. { Reuse hp5 }
  6362. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6363. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6364. Exit;
  6365. if MatchInstruction(hp5, A_RET, []) then
  6366. begin
  6367. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6368. ConvertJumpToRET(hp6, hp5);
  6369. Result := True;
  6370. end
  6371. else
  6372. Exit;
  6373. end;
  6374. if not
  6375. (
  6376. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6377. (
  6378. (taicpu(hp6).opcode=A_RET) or
  6379. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6380. )
  6381. ) then
  6382. { Still doesn't match }
  6383. Exit;
  6384. end;
  6385. if (taicpu(hp2).oper[0]^.val = 1) then
  6386. begin
  6387. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6388. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6389. end
  6390. else
  6391. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6392. if taicpu(hp2).opsize=S_B then
  6393. begin
  6394. if taicpu(hp2).oper[1]^.typ = top_reg then
  6395. begin
  6396. SecondReg := taicpu(hp2).oper[1]^.reg;
  6397. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6398. end
  6399. else
  6400. begin
  6401. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6402. SecondReg := NR_NO;
  6403. end;
  6404. hp_pos := p;
  6405. hp_allocstart := hp4;
  6406. end
  6407. else
  6408. begin
  6409. { Will be a register because the size can't be S_B otherwise }
  6410. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6411. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6412. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6413. if (cs_opt_size in current_settings.optimizerswitches) then
  6414. begin
  6415. { Favour using MOVZX when optimising for size }
  6416. case taicpu(hp2).opsize of
  6417. S_W:
  6418. NewSize := S_BW;
  6419. S_L:
  6420. NewSize := S_BL;
  6421. {$ifdef x86_64}
  6422. S_Q:
  6423. begin
  6424. NewSize := S_BL;
  6425. { Will implicitly zero-extend to 64-bit }
  6426. setsubreg(SecondReg, R_SUBD);
  6427. end;
  6428. {$endif x86_64}
  6429. else
  6430. InternalError(2022101301);
  6431. end;
  6432. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6433. { Inserting it right before p will guarantee that the flags are also tracked }
  6434. Asml.InsertBefore(hp5, p);
  6435. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6436. hp_pos := hp5;
  6437. hp_allocstart := hp4;
  6438. end
  6439. else
  6440. begin
  6441. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6442. { Inserting it right before p will guarantee that the flags are also tracked }
  6443. Asml.InsertBefore(hp5, p);
  6444. hp_pos := p;
  6445. hp_allocstart := hp5;
  6446. end;
  6447. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6448. end;
  6449. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6450. taicpu(hp4).condition := taicpu(p).condition;
  6451. asml.InsertBefore(hp4, hp_pos);
  6452. if taicpu(hp3).is_jmp then
  6453. begin
  6454. JumpLoc.decrefs;
  6455. MakeUnconditional(taicpu(p));
  6456. { This also increases the reference count }
  6457. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6458. end
  6459. else
  6460. ConvertJumpToRET(p, hp3);
  6461. if SecondReg <> NR_NO then
  6462. { Ensure the destination register is allocated over this region }
  6463. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6464. if (JumpLoc.getrefs = 0) then
  6465. RemoveDeadCodeAfterJump(hp3);
  6466. Result:=true;
  6467. exit;
  6468. end;
  6469. end;
  6470. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6471. var
  6472. hp1, hp2: tai;
  6473. ActiveReg: TRegister;
  6474. OldOffset: asizeint;
  6475. ThisConst: TCGInt;
  6476. function RegDeallocated: Boolean;
  6477. begin
  6478. TransferUsedRegs(TmpUsedRegs);
  6479. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6480. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6481. end;
  6482. begin
  6483. Result:=false;
  6484. hp1 := nil;
  6485. { replace
  6486. subX const,%reg1
  6487. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6488. dealloc %reg1
  6489. by
  6490. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6491. }
  6492. if MatchOpType(taicpu(p),top_const,top_reg) then
  6493. begin
  6494. ActiveReg := taicpu(p).oper[1]^.reg;
  6495. { Ensures the entire register was updated }
  6496. if (taicpu(p).opsize >= S_L) and
  6497. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6498. MatchInstruction(hp1,A_LEA,[]) and
  6499. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6500. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6501. (
  6502. { Cover the case where the register in the reference is also the destination register }
  6503. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6504. (
  6505. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6506. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6507. RegDeallocated
  6508. )
  6509. ) then
  6510. begin
  6511. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6512. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.base) then
  6513. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6514. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.index) then
  6515. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6516. {$ifdef x86_64}
  6517. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6518. begin
  6519. { Overflow; abort }
  6520. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6521. end
  6522. else
  6523. {$endif x86_64}
  6524. begin
  6525. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6526. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6527. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6528. RemoveCurrentP(p, hp1)
  6529. else
  6530. RemoveCurrentP(p);
  6531. result:=true;
  6532. Exit;
  6533. end;
  6534. end;
  6535. if (
  6536. { Save calling GetNextInstructionUsingReg again }
  6537. Assigned(hp1) or
  6538. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6539. ) and
  6540. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6541. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6542. begin
  6543. if taicpu(hp1).oper[0]^.typ = top_const then
  6544. begin
  6545. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6546. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6547. Result := True;
  6548. { Handle any overflows }
  6549. case taicpu(p).opsize of
  6550. S_B:
  6551. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6552. S_W:
  6553. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6554. S_L:
  6555. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6556. {$ifdef x86_64}
  6557. S_Q:
  6558. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6559. { Overflow; abort }
  6560. Result := False
  6561. else
  6562. taicpu(p).oper[0]^.val := ThisConst;
  6563. {$endif x86_64}
  6564. else
  6565. InternalError(2021102611);
  6566. end;
  6567. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6568. if Result then
  6569. begin
  6570. if (taicpu(p).oper[0]^.val < 0) and
  6571. (
  6572. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6573. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6574. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6575. ) then
  6576. begin
  6577. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6578. taicpu(p).opcode := A_SUB;
  6579. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6580. end
  6581. else
  6582. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6583. RemoveInstruction(hp1);
  6584. end;
  6585. end
  6586. else
  6587. begin
  6588. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6589. TransferUsedRegs(TmpUsedRegs);
  6590. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6591. hp2 := p;
  6592. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6593. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6594. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6595. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6596. begin
  6597. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6598. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6599. Asml.Remove(p);
  6600. Asml.InsertAfter(p, hp1);
  6601. p := hp1;
  6602. Result := True;
  6603. Exit;
  6604. end;
  6605. end;
  6606. end;
  6607. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6608. { * change "sub/add const1, reg" or "dec reg" followed by
  6609. "sub const2, reg" to one "sub ..., reg" }
  6610. {$ifdef i386}
  6611. if (taicpu(p).oper[0]^.val = 2) and
  6612. (ActiveReg = NR_ESP) and
  6613. { Don't do the sub/push optimization if the sub }
  6614. { comes from setting up the stack frame (JM) }
  6615. (not(GetLastInstruction(p,hp1)) or
  6616. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6617. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6618. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6619. begin
  6620. hp1 := tai(p.next);
  6621. while Assigned(hp1) and
  6622. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6623. not RegReadByInstruction(NR_ESP,hp1) and
  6624. not RegModifiedByInstruction(NR_ESP,hp1) do
  6625. hp1 := tai(hp1.next);
  6626. if Assigned(hp1) and
  6627. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6628. begin
  6629. taicpu(hp1).changeopsize(S_L);
  6630. if taicpu(hp1).oper[0]^.typ=top_reg then
  6631. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6632. hp1 := tai(p.next);
  6633. RemoveCurrentp(p, hp1);
  6634. Result:=true;
  6635. exit;
  6636. end;
  6637. end;
  6638. {$endif i386}
  6639. if DoArithCombineOpt(p) then
  6640. Result:=true;
  6641. end;
  6642. end;
  6643. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6644. var
  6645. TmpBool1,TmpBool2 : Boolean;
  6646. tmpref : treference;
  6647. hp1,hp2: tai;
  6648. mask, shiftval: tcgint;
  6649. begin
  6650. Result:=false;
  6651. { All these optimisations work on "shl/sal const,%reg" }
  6652. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6653. Exit;
  6654. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6655. (taicpu(p).oper[0]^.val <= 3) then
  6656. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6657. begin
  6658. { should we check the next instruction? }
  6659. TmpBool1 := True;
  6660. { have we found an add/sub which could be
  6661. integrated in the lea? }
  6662. TmpBool2 := False;
  6663. reference_reset(tmpref,2,[]);
  6664. TmpRef.index := taicpu(p).oper[1]^.reg;
  6665. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6666. while TmpBool1 and
  6667. GetNextInstruction(p, hp1) and
  6668. (tai(hp1).typ = ait_instruction) and
  6669. ((((taicpu(hp1).opcode = A_ADD) or
  6670. (taicpu(hp1).opcode = A_SUB)) and
  6671. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6672. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6673. (((taicpu(hp1).opcode = A_INC) or
  6674. (taicpu(hp1).opcode = A_DEC)) and
  6675. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6676. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6677. ((taicpu(hp1).opcode = A_LEA) and
  6678. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6679. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6680. (not GetNextInstruction(hp1,hp2) or
  6681. not instrReadsFlags(hp2)) Do
  6682. begin
  6683. TmpBool1 := False;
  6684. if taicpu(hp1).opcode=A_LEA then
  6685. begin
  6686. if (TmpRef.base = NR_NO) and
  6687. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6688. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6689. { Segment register isn't a concern here }
  6690. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6691. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6692. begin
  6693. TmpBool1 := True;
  6694. TmpBool2 := True;
  6695. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6696. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6697. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6698. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6699. RemoveInstruction(hp1);
  6700. end
  6701. end
  6702. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6703. begin
  6704. TmpBool1 := True;
  6705. TmpBool2 := True;
  6706. case taicpu(hp1).opcode of
  6707. A_ADD:
  6708. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6709. A_SUB:
  6710. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6711. else
  6712. internalerror(2019050536);
  6713. end;
  6714. RemoveInstruction(hp1);
  6715. end
  6716. else
  6717. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6718. (((taicpu(hp1).opcode = A_ADD) and
  6719. (TmpRef.base = NR_NO)) or
  6720. (taicpu(hp1).opcode = A_INC) or
  6721. (taicpu(hp1).opcode = A_DEC)) then
  6722. begin
  6723. TmpBool1 := True;
  6724. TmpBool2 := True;
  6725. case taicpu(hp1).opcode of
  6726. A_ADD:
  6727. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6728. A_INC:
  6729. inc(TmpRef.offset);
  6730. A_DEC:
  6731. dec(TmpRef.offset);
  6732. else
  6733. internalerror(2019050535);
  6734. end;
  6735. RemoveInstruction(hp1);
  6736. end;
  6737. end;
  6738. if TmpBool2
  6739. {$ifndef x86_64}
  6740. or
  6741. ((current_settings.optimizecputype < cpu_Pentium2) and
  6742. (taicpu(p).oper[0]^.val <= 3) and
  6743. not(cs_opt_size in current_settings.optimizerswitches))
  6744. {$endif x86_64}
  6745. then
  6746. begin
  6747. if not(TmpBool2) and
  6748. (taicpu(p).oper[0]^.val=1) then
  6749. begin
  6750. taicpu(p).opcode := A_ADD;
  6751. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6752. end
  6753. else
  6754. begin
  6755. taicpu(p).opcode := A_LEA;
  6756. taicpu(p).loadref(0, TmpRef);
  6757. end;
  6758. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6759. Result := True;
  6760. end;
  6761. end
  6762. {$ifndef x86_64}
  6763. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6764. begin
  6765. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6766. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6767. (unlike shl, which is only Tairable in the U pipe) }
  6768. if taicpu(p).oper[0]^.val=1 then
  6769. begin
  6770. taicpu(p).opcode := A_ADD;
  6771. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6772. Result := True;
  6773. end
  6774. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6775. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6776. else if (taicpu(p).opsize = S_L) and
  6777. (taicpu(p).oper[0]^.val<= 3) then
  6778. begin
  6779. reference_reset(tmpref,2,[]);
  6780. TmpRef.index := taicpu(p).oper[1]^.reg;
  6781. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6782. taicpu(p).opcode := A_LEA;
  6783. taicpu(p).loadref(0, TmpRef);
  6784. Result := True;
  6785. end;
  6786. end
  6787. {$endif x86_64}
  6788. else if
  6789. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6790. (
  6791. (
  6792. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6793. SetAndTest(hp1, hp2)
  6794. {$ifdef x86_64}
  6795. ) or
  6796. (
  6797. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6798. GetNextInstruction(hp1, hp2) and
  6799. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6800. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6801. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6802. {$endif x86_64}
  6803. )
  6804. ) and
  6805. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6806. begin
  6807. { Change:
  6808. shl x, %reg1
  6809. mov -(1<<x), %reg2
  6810. and %reg2, %reg1
  6811. Or:
  6812. shl x, %reg1
  6813. and -(1<<x), %reg1
  6814. To just:
  6815. shl x, %reg1
  6816. Since the and operation only zeroes bits that are already zero from the shl operation
  6817. }
  6818. case taicpu(p).oper[0]^.val of
  6819. 8:
  6820. mask:=$FFFFFFFFFFFFFF00;
  6821. 16:
  6822. mask:=$FFFFFFFFFFFF0000;
  6823. 32:
  6824. mask:=$FFFFFFFF00000000;
  6825. 63:
  6826. { Constant pre-calculated to prevent overflow errors with Int64 }
  6827. mask:=$8000000000000000;
  6828. else
  6829. begin
  6830. if taicpu(p).oper[0]^.val >= 64 then
  6831. { Shouldn't happen realistically, since the register
  6832. is guaranteed to be set to zero at this point }
  6833. mask := 0
  6834. else
  6835. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6836. end;
  6837. end;
  6838. if taicpu(hp1).oper[0]^.val = mask then
  6839. begin
  6840. { Everything checks out, perform the optimisation, as long as
  6841. the FLAGS register isn't being used}
  6842. TransferUsedRegs(TmpUsedRegs);
  6843. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6844. {$ifdef x86_64}
  6845. if (hp1 <> hp2) then
  6846. begin
  6847. { "shl/mov/and" version }
  6848. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6849. { Don't do the optimisation if the FLAGS register is in use }
  6850. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6851. begin
  6852. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6853. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6854. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6855. begin
  6856. RemoveInstruction(hp1);
  6857. Result := True;
  6858. end;
  6859. { Only set Result to True if the 'mov' instruction was removed }
  6860. RemoveInstruction(hp2);
  6861. end;
  6862. end
  6863. else
  6864. {$endif x86_64}
  6865. begin
  6866. { "shl/and" version }
  6867. { Don't do the optimisation if the FLAGS register is in use }
  6868. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6869. begin
  6870. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6871. RemoveInstruction(hp1);
  6872. Result := True;
  6873. end;
  6874. end;
  6875. Exit;
  6876. end
  6877. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6878. begin
  6879. { Even if the mask doesn't allow for its removal, we might be
  6880. able to optimise the mask for the "shl/and" version, which
  6881. may permit other peephole optimisations }
  6882. {$ifdef DEBUG_AOPTCPU}
  6883. mask := taicpu(hp1).oper[0]^.val and mask;
  6884. if taicpu(hp1).oper[0]^.val <> mask then
  6885. begin
  6886. DebugMsg(
  6887. SPeepholeOptimization +
  6888. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6889. ' to $' + debug_tostr(mask) +
  6890. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6891. taicpu(hp1).oper[0]^.val := mask;
  6892. end;
  6893. {$else DEBUG_AOPTCPU}
  6894. { If debugging is off, just set the operand even if it's the same }
  6895. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6896. {$endif DEBUG_AOPTCPU}
  6897. end;
  6898. end;
  6899. {
  6900. change
  6901. shl/sal const,reg
  6902. <op> ...(...,reg,1),...
  6903. into
  6904. <op> ...(...,reg,1 shl const),...
  6905. if const in 1..3
  6906. }
  6907. if MatchOpType(taicpu(p), top_const, top_reg) and
  6908. (taicpu(p).oper[0]^.val in [1..3]) and
  6909. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6910. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6911. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6912. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6913. MatchOpType(taicpu(hp1),top_ref))
  6914. ) and
  6915. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6916. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6917. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6918. begin
  6919. TransferUsedRegs(TmpUsedRegs);
  6920. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6921. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6922. begin
  6923. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6924. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6925. RemoveCurrentP(p);
  6926. Result:=true;
  6927. exit;
  6928. end;
  6929. end;
  6930. if MatchOpType(taicpu(p), top_const, top_reg) and
  6931. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6932. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6933. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6934. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6935. begin
  6936. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6937. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6938. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6939. {$ifdef x86_64}
  6940. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6941. {$endif x86_64}
  6942. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6943. begin
  6944. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6945. taicpu(hp1).opcode:=A_MOV;
  6946. taicpu(hp1).oper[0]^.val:=0;
  6947. end
  6948. else
  6949. begin
  6950. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6951. taicpu(hp1).oper[0]^.val:=shiftval;
  6952. end;
  6953. RemoveCurrentP(p);
  6954. Result:=true;
  6955. exit;
  6956. end;
  6957. end;
  6958. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6959. begin
  6960. case shr_size of
  6961. S_B:
  6962. { No valid combinations }
  6963. Result := False;
  6964. S_W:
  6965. Result := (Shift >= 8) and (movz_size = S_BW);
  6966. S_L:
  6967. Result :=
  6968. (Shift >= 24) { Any opsize is valid for this shift } or
  6969. ((Shift >= 16) and (movz_size = S_WL));
  6970. {$ifdef x86_64}
  6971. S_Q:
  6972. Result :=
  6973. (Shift >= 56) { Any opsize is valid for this shift } or
  6974. ((Shift >= 48) and (movz_size = S_WL));
  6975. {$endif x86_64}
  6976. else
  6977. InternalError(2022081510);
  6978. end;
  6979. end;
  6980. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6981. var
  6982. hp1, hp2: tai;
  6983. Shift: TCGInt;
  6984. LimitSize: Topsize;
  6985. DoNotMerge: Boolean;
  6986. begin
  6987. Result := False;
  6988. { All these optimisations work on "shr const,%reg" }
  6989. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6990. Exit;
  6991. DoNotMerge := False;
  6992. Shift := taicpu(p).oper[0]^.val;
  6993. LimitSize := taicpu(p).opsize;
  6994. hp1 := p;
  6995. repeat
  6996. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6997. Exit;
  6998. case taicpu(hp1).opcode of
  6999. A_TEST, A_CMP, A_Jcc:
  7000. { Skip over conditional jumps and relevant comparisons }
  7001. Continue;
  7002. A_MOVZX:
  7003. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  7004. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  7005. begin
  7006. { Since the original register is being read as is, subsequent
  7007. SHRs must not be merged at this point }
  7008. DoNotMerge := True;
  7009. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  7010. begin
  7011. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  7012. begin
  7013. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  7014. taicpu(hp1).opcode := A_MOV;
  7015. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  7016. case taicpu(hp1).opsize of
  7017. S_BW:
  7018. taicpu(hp1).opsize := S_W;
  7019. S_BL, S_WL:
  7020. taicpu(hp1).opsize := S_L;
  7021. else
  7022. InternalError(2022081503);
  7023. end;
  7024. { p itself hasn't changed, so no need to set Result to True }
  7025. Include(OptsToCheck, aoc_ForceNewIteration);
  7026. { See if there's anything afterwards that can be
  7027. optimised, since the input register hasn't changed }
  7028. Continue;
  7029. end;
  7030. { NOTE: If the MOVZX instruction reads and writes the same
  7031. register, defer this to the post-peephole optimisation stage }
  7032. Exit;
  7033. end;
  7034. end;
  7035. A_SHL, A_SAL, A_SHR:
  7036. if (taicpu(hp1).opsize <= LimitSize) and
  7037. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7038. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7039. begin
  7040. { Make sure the sizes don't exceed the register size limit
  7041. (measured by the shift value falling below the limit) }
  7042. if taicpu(hp1).opsize < LimitSize then
  7043. LimitSize := taicpu(hp1).opsize;
  7044. if taicpu(hp1).opcode = A_SHR then
  7045. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7046. else
  7047. begin
  7048. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7049. DoNotMerge := True;
  7050. end;
  7051. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7052. Exit;
  7053. { Since we've established that the combined shift is within
  7054. limits, we can actually combine the adjacent SHR
  7055. instructions even if they're different sizes }
  7056. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7057. begin
  7058. hp2 := tai(hp1.Previous);
  7059. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7060. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7061. RemoveInstruction(hp1);
  7062. hp1 := hp2;
  7063. { Though p has changed, only the constant has, and its
  7064. effects can still be detected on the next iteration of
  7065. the repeat..until loop }
  7066. Include(OptsToCheck, aoc_ForceNewIteration);
  7067. end;
  7068. { Move onto the next instruction }
  7069. Continue;
  7070. end;
  7071. else
  7072. ;
  7073. end;
  7074. Break;
  7075. until False;
  7076. end;
  7077. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7078. var
  7079. CurrentRef: TReference;
  7080. FullReg: TRegister;
  7081. hp1, hp2: tai;
  7082. begin
  7083. Result := False;
  7084. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7085. Exit;
  7086. { We assume you've checked if the operand is actually a reference by
  7087. this point. If it isn't, you'll most likely get an access violation }
  7088. CurrentRef := first_mov.oper[1]^.ref^;
  7089. { Memory must be aligned }
  7090. if (CurrentRef.offset mod 4) <> 0 then
  7091. Exit;
  7092. Inc(CurrentRef.offset);
  7093. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7094. if MatchOperand(second_mov.oper[0]^, 0) and
  7095. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7096. GetNextInstruction(second_mov, hp1) and
  7097. (hp1.typ = ait_instruction) and
  7098. (taicpu(hp1).opcode = A_MOV) and
  7099. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7100. (taicpu(hp1).oper[0]^.val = 0) then
  7101. begin
  7102. Inc(CurrentRef.offset);
  7103. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7104. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7105. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7106. begin
  7107. case taicpu(hp1).opsize of
  7108. S_B:
  7109. if GetNextInstruction(hp1, hp2) and
  7110. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7111. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7112. (taicpu(hp2).oper[0]^.val = 0) then
  7113. begin
  7114. Inc(CurrentRef.offset);
  7115. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7116. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7117. (taicpu(hp2).opsize = S_B) then
  7118. begin
  7119. RemoveInstruction(hp1);
  7120. RemoveInstruction(hp2);
  7121. first_mov.opsize := S_L;
  7122. if first_mov.oper[0]^.typ = top_reg then
  7123. begin
  7124. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7125. { Reuse second_mov as a MOVZX instruction }
  7126. second_mov.opcode := A_MOVZX;
  7127. second_mov.opsize := S_BL;
  7128. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7129. second_mov.loadreg(1, FullReg);
  7130. first_mov.oper[0]^.reg := FullReg;
  7131. asml.Remove(second_mov);
  7132. asml.InsertBefore(second_mov, first_mov);
  7133. end
  7134. else
  7135. { It's a value }
  7136. begin
  7137. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7138. RemoveInstruction(second_mov);
  7139. end;
  7140. Result := True;
  7141. Exit;
  7142. end;
  7143. end;
  7144. S_W:
  7145. begin
  7146. RemoveInstruction(hp1);
  7147. first_mov.opsize := S_L;
  7148. if first_mov.oper[0]^.typ = top_reg then
  7149. begin
  7150. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7151. { Reuse second_mov as a MOVZX instruction }
  7152. second_mov.opcode := A_MOVZX;
  7153. second_mov.opsize := S_BL;
  7154. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7155. second_mov.loadreg(1, FullReg);
  7156. first_mov.oper[0]^.reg := FullReg;
  7157. asml.Remove(second_mov);
  7158. asml.InsertBefore(second_mov, first_mov);
  7159. end
  7160. else
  7161. { It's a value }
  7162. begin
  7163. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7164. RemoveInstruction(second_mov);
  7165. end;
  7166. Result := True;
  7167. Exit;
  7168. end;
  7169. else
  7170. ;
  7171. end;
  7172. end;
  7173. end;
  7174. end;
  7175. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7176. { returns true if a "continue" should be done after this optimization }
  7177. var
  7178. hp1, hp2, hp3: tai;
  7179. begin
  7180. Result := false;
  7181. hp3 := nil;
  7182. if MatchOpType(taicpu(p),top_ref) and
  7183. GetNextInstruction(p, hp1) and
  7184. (hp1.typ = ait_instruction) and
  7185. (((taicpu(hp1).opcode = A_FLD) and
  7186. (taicpu(p).opcode = A_FSTP)) or
  7187. ((taicpu(p).opcode = A_FISTP) and
  7188. (taicpu(hp1).opcode = A_FILD))) and
  7189. MatchOpType(taicpu(hp1),top_ref) and
  7190. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7191. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7192. begin
  7193. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7194. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7195. GetNextInstruction(hp1, hp2) and
  7196. (((hp2.typ = ait_instruction) and
  7197. IsExitCode(hp2) and
  7198. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7199. not(assigned(current_procinfo.procdef.funcretsym) and
  7200. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7201. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7202. { fstp <temp>
  7203. fld <temp>
  7204. <dealloc> <temp>
  7205. }
  7206. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7207. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7208. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7209. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7210. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7211. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7212. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7213. )
  7214. )
  7215. ) then
  7216. begin
  7217. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7218. RemoveInstruction(hp1);
  7219. RemoveCurrentP(p, hp2);
  7220. { first case: exit code }
  7221. if hp2.typ = ait_instruction then
  7222. RemoveLastDeallocForFuncRes(p);
  7223. Result := true;
  7224. end
  7225. else
  7226. { we can do this only in fast math mode as fstp is rounding ...
  7227. ... still disabled as it breaks the compiler and/or rtl }
  7228. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7229. { ... or if another fstp equal to the first one follows }
  7230. GetNextInstruction(hp1,hp2) and
  7231. (hp2.typ = ait_instruction) and
  7232. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7233. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7234. begin
  7235. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7236. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7237. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7238. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7239. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7240. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7241. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7242. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7243. ) then
  7244. begin
  7245. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7246. RemoveCurrentP(p,hp2);
  7247. RemoveInstruction(hp1);
  7248. Result := true;
  7249. end
  7250. else if { fst can't store an extended/comp value }
  7251. (taicpu(p).opsize <> S_FX) and
  7252. (taicpu(p).opsize <> S_IQ) then
  7253. begin
  7254. if (taicpu(p).opcode = A_FSTP) then
  7255. taicpu(p).opcode := A_FST
  7256. else
  7257. taicpu(p).opcode := A_FIST;
  7258. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7259. RemoveInstruction(hp1);
  7260. Result := true;
  7261. end;
  7262. end;
  7263. end;
  7264. end;
  7265. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7266. var
  7267. hp1, hp2, hp3: tai;
  7268. begin
  7269. result:=false;
  7270. if MatchOpType(taicpu(p),top_reg) and
  7271. GetNextInstruction(p, hp1) and
  7272. (hp1.typ = Ait_Instruction) and
  7273. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7274. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7275. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7276. { change to
  7277. fld reg fxxx reg,st
  7278. fxxxp st, st1 (hp1)
  7279. Remark: non commutative operations must be reversed!
  7280. }
  7281. begin
  7282. case taicpu(hp1).opcode Of
  7283. A_FMULP,A_FADDP,
  7284. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7285. begin
  7286. case taicpu(hp1).opcode Of
  7287. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7288. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7289. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7290. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7291. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7292. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7293. else
  7294. internalerror(2019050534);
  7295. end;
  7296. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7297. taicpu(hp1).oper[1]^.reg := NR_ST;
  7298. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7299. RemoveCurrentP(p, hp1);
  7300. Result:=true;
  7301. exit;
  7302. end;
  7303. else
  7304. ;
  7305. end;
  7306. end
  7307. else
  7308. if MatchOpType(taicpu(p),top_ref) and
  7309. GetNextInstruction(p, hp2) and
  7310. (hp2.typ = Ait_Instruction) and
  7311. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7312. (taicpu(p).opsize in [S_FS, S_FL]) and
  7313. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7314. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7315. if GetLastInstruction(p, hp1) and
  7316. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7317. MatchOpType(taicpu(hp1),top_ref) and
  7318. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7319. if ((taicpu(hp2).opcode = A_FMULP) or
  7320. (taicpu(hp2).opcode = A_FADDP)) then
  7321. { change to
  7322. fld/fst mem1 (hp1) fld/fst mem1
  7323. fld mem1 (p) fadd/
  7324. faddp/ fmul st, st
  7325. fmulp st, st1 (hp2) }
  7326. begin
  7327. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7328. RemoveCurrentP(p, hp1);
  7329. if (taicpu(hp2).opcode = A_FADDP) then
  7330. taicpu(hp2).opcode := A_FADD
  7331. else
  7332. taicpu(hp2).opcode := A_FMUL;
  7333. taicpu(hp2).oper[1]^.reg := NR_ST;
  7334. end
  7335. else
  7336. { change to
  7337. fld/fst mem1 (hp1) fld/fst mem1
  7338. fld mem1 (p) fld st
  7339. }
  7340. begin
  7341. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7342. taicpu(p).changeopsize(S_FL);
  7343. taicpu(p).loadreg(0,NR_ST);
  7344. end
  7345. else
  7346. begin
  7347. case taicpu(hp2).opcode Of
  7348. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7349. { change to
  7350. fld/fst mem1 (hp1) fld/fst mem1
  7351. fld mem2 (p) fxxx mem2
  7352. fxxxp st, st1 (hp2) }
  7353. begin
  7354. case taicpu(hp2).opcode Of
  7355. A_FADDP: taicpu(p).opcode := A_FADD;
  7356. A_FMULP: taicpu(p).opcode := A_FMUL;
  7357. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7358. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7359. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7360. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7361. else
  7362. internalerror(2019050533);
  7363. end;
  7364. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7365. RemoveInstruction(hp2);
  7366. end
  7367. else
  7368. ;
  7369. end
  7370. end
  7371. end;
  7372. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7373. begin
  7374. Result := condition_in(cond1, cond2) or
  7375. { Not strictly subsets due to the actual flags checked, but because we're
  7376. comparing integers, E is a subset of AE and GE and their aliases }
  7377. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7378. end;
  7379. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7380. var
  7381. v: TCGInt;
  7382. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7383. FirstMatch, TempBool: Boolean;
  7384. NewReg: TRegister;
  7385. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7386. begin
  7387. Result:=false;
  7388. { All these optimisations need a next instruction }
  7389. if not GetNextInstruction(p, hp1) then
  7390. Exit;
  7391. true_hp1 := hp1;
  7392. { Search for:
  7393. cmp ###,###
  7394. j(c1) @lbl1
  7395. ...
  7396. @lbl:
  7397. cmp ###,### (same comparison as above)
  7398. j(c2) @lbl2
  7399. If c1 is a subset of c2, change to:
  7400. cmp ###,###
  7401. j(c1) @lbl2
  7402. (@lbl1 may become a dead label as a result)
  7403. }
  7404. { Also handle cases where there are multiple jumps in a row }
  7405. p_jump := hp1;
  7406. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7407. begin
  7408. Prefetch(p_jump.Next);
  7409. if IsJumpToLabel(taicpu(p_jump)) then
  7410. begin
  7411. { Do jump optimisations first in case the condition becomes
  7412. unnecessary }
  7413. TempBool := True;
  7414. if DoJumpOptimizations(p_jump, TempBool) or
  7415. not TempBool then
  7416. begin
  7417. if Assigned(p_jump) then
  7418. begin
  7419. { CollapseZeroDistJump will be set to the label or an align
  7420. before it after the jump if it optimises, whether or not
  7421. the label is live or dead }
  7422. if (p_jump.typ = ait_align) or
  7423. (
  7424. (p_jump.typ = ait_label) and
  7425. not (tai_label(p_jump).labsym.is_used)
  7426. ) then
  7427. GetNextInstruction(p_jump, p_jump);
  7428. end;
  7429. TransferUsedRegs(TmpUsedRegs);
  7430. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7431. if not Assigned(p_jump) or
  7432. (
  7433. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7434. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7435. ) then
  7436. begin
  7437. { No more conditional jumps; conditional statement is no longer required }
  7438. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7439. RemoveCurrentP(p);
  7440. Result := True;
  7441. Exit;
  7442. end;
  7443. hp1 := p_jump;
  7444. Include(OptsToCheck, aoc_ForceNewIteration);
  7445. Continue;
  7446. end;
  7447. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7448. if GetNextInstruction(p_jump, hp2) and
  7449. (
  7450. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7451. not TempBool
  7452. ) then
  7453. begin
  7454. hp1 := p_jump;
  7455. Include(OptsToCheck, aoc_ForceNewIteration);
  7456. Continue;
  7457. end;
  7458. p_label := nil;
  7459. if Assigned(JumpLabel) then
  7460. p_label := getlabelwithsym(JumpLabel);
  7461. if Assigned(p_label) and
  7462. GetNextInstruction(p_label, p_dist) and
  7463. MatchInstruction(p_dist, A_CMP, []) and
  7464. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7465. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7466. GetNextInstruction(p_dist, hp1_dist) and
  7467. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7468. begin
  7469. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7470. if JumpLabel = JumpLabel_dist then
  7471. { This is an infinite loop }
  7472. Exit;
  7473. { Best optimisation when the first condition is a subset (or equal) of the second }
  7474. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7475. begin
  7476. { Any registers used here will already be allocated }
  7477. if Assigned(JumpLabel) then
  7478. JumpLabel.DecRefs;
  7479. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7480. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7481. Include(OptsToCheck, aoc_ForceNewIteration);
  7482. { Don't exit yet. Since p and p_jump haven't actually been
  7483. removed, we can check for more on this iteration }
  7484. end
  7485. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7486. GetNextInstruction(hp1_dist, hp1_label) and
  7487. (hp1_label.typ = ait_label) then
  7488. begin
  7489. JumpLabel_far := tai_label(hp1_label).labsym;
  7490. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7491. { This is an infinite loop }
  7492. Exit;
  7493. if Assigned(JumpLabel_far) then
  7494. begin
  7495. { In this situation, if the first jump branches, the second one will never,
  7496. branch so change the destination label to after the second jump }
  7497. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7498. if Assigned(JumpLabel) then
  7499. JumpLabel.DecRefs;
  7500. JumpLabel_far.IncRefs;
  7501. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7502. Result := True;
  7503. { Don't exit yet. Since p and p_jump haven't actually been
  7504. removed, we can check for more on this iteration }
  7505. Continue;
  7506. end;
  7507. end;
  7508. end;
  7509. end;
  7510. { Search for:
  7511. cmp ###,###
  7512. j(c1) @lbl1
  7513. cmp ###,### (same as first)
  7514. Remove second cmp
  7515. }
  7516. if GetNextInstruction(p_jump, hp2) and
  7517. (
  7518. (
  7519. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7520. (
  7521. (
  7522. MatchOpType(taicpu(p), top_const, top_reg) and
  7523. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7524. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7525. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7526. ) or (
  7527. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7528. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7529. )
  7530. )
  7531. ) or (
  7532. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7533. MatchOperand(taicpu(p).oper[0]^, 0) and
  7534. (taicpu(p).oper[1]^.typ = top_reg) and
  7535. MatchInstruction(hp2, A_TEST, []) and
  7536. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7537. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7538. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7539. )
  7540. ) then
  7541. begin
  7542. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7543. TransferUsedRegs(TmpUsedRegs);
  7544. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7545. RemoveInstruction(hp2);
  7546. Result := True;
  7547. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7548. end
  7549. else
  7550. begin
  7551. { hp2 is the next instruction, so save time and just set p_jump
  7552. to it instead of calling GetNextInstruction below }
  7553. p_jump := hp2;
  7554. Continue;
  7555. end;
  7556. GetNextInstruction(p_jump, p_jump);
  7557. end;
  7558. if (
  7559. { Don't call GetNextInstruction again if we already have it }
  7560. (true_hp1 = p_jump) or
  7561. GetNextInstruction(p, hp1)
  7562. ) and
  7563. MatchInstruction(hp1, A_Jcc, []) and
  7564. IsJumpToLabel(taicpu(hp1)) and
  7565. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7566. GetNextInstruction(hp1, hp2) then
  7567. begin
  7568. {
  7569. cmp x, y (or "cmp y, x")
  7570. je @lbl
  7571. mov x, y
  7572. @lbl:
  7573. (x and y can be constants, registers or references)
  7574. Change to:
  7575. mov x, y (x and y will always be equal in the end)
  7576. @lbl: (may beceome a dead label)
  7577. Also:
  7578. cmp x, y (or "cmp y, x")
  7579. jne @lbl
  7580. mov x, y
  7581. @lbl:
  7582. (x and y can be constants, registers or references)
  7583. Change to:
  7584. Absolutely nothing! (Except @lbl if it's still live)
  7585. }
  7586. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7587. (
  7588. (
  7589. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7590. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7591. ) or (
  7592. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7593. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7594. )
  7595. ) and
  7596. GetNextInstruction(hp2, hp1_label) and
  7597. (hp1_label.typ = ait_label) and
  7598. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7599. begin
  7600. tai_label(hp1_label).labsym.DecRefs;
  7601. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7602. begin
  7603. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7604. RemoveInstruction(hp2);
  7605. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7606. end
  7607. else
  7608. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7609. RemoveInstruction(hp1);
  7610. RemoveCurrentp(p, hp2);
  7611. Result := True;
  7612. Exit;
  7613. end;
  7614. {
  7615. Try to optimise the following:
  7616. cmp $x,### ($x and $y can be registers or constants)
  7617. je @lbl1 (only reference)
  7618. cmp $y,### (### are identical)
  7619. @Lbl:
  7620. sete %reg1
  7621. Change to:
  7622. cmp $x,###
  7623. sete %reg2 (allocate new %reg2)
  7624. cmp $y,###
  7625. sete %reg1
  7626. orb %reg2,%reg1
  7627. (dealloc %reg2)
  7628. This adds an instruction (so don't perform under -Os), but it removes
  7629. a conditional branch.
  7630. }
  7631. if not (cs_opt_size in current_settings.optimizerswitches) and
  7632. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7633. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7634. { The first operand of CMP instructions can only be a register or
  7635. immediate anyway, so no need to check }
  7636. GetNextInstruction(hp2, p_label) and
  7637. (p_label.typ = ait_label) and
  7638. (tai_label(p_label).labsym.getrefs = 1) and
  7639. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7640. GetNextInstruction(p_label, p_dist) and
  7641. MatchInstruction(p_dist, A_SETcc, []) and
  7642. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7643. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7644. begin
  7645. TransferUsedRegs(TmpUsedRegs);
  7646. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7647. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7648. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7649. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7650. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7651. { Get the instruction after the SETcc instruction so we can
  7652. allocate a new register over the entire range }
  7653. GetNextInstruction(p_dist, hp1_dist) then
  7654. begin
  7655. { Register can appear in p if it's not used afterwards, so only
  7656. allocate between hp1 and hp1_dist }
  7657. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7658. if NewReg <> NR_NO then
  7659. begin
  7660. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7661. { Change the jump instruction into a SETcc instruction }
  7662. taicpu(hp1).opcode := A_SETcc;
  7663. taicpu(hp1).opsize := S_B;
  7664. taicpu(hp1).loadreg(0, NewReg);
  7665. { This is now a dead label }
  7666. tai_label(p_label).labsym.decrefs;
  7667. { Prefer adding before the next instruction so the FLAGS
  7668. register is deallicated first }
  7669. AsmL.InsertBefore(
  7670. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7671. hp1_dist
  7672. );
  7673. Result := True;
  7674. { Don't exit yet, as p wasn't changed and hp1, while
  7675. modified, is still intact and might be optimised by the
  7676. SETcc optimisation below }
  7677. end;
  7678. end;
  7679. end;
  7680. end;
  7681. if (taicpu(p).oper[0]^.typ = top_const) and
  7682. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7683. begin
  7684. if (taicpu(p).oper[0]^.val = 0) and
  7685. (taicpu(p).oper[1]^.typ = top_reg) then
  7686. begin
  7687. hp2 := p;
  7688. FirstMatch := True;
  7689. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7690. anything meaningful once it's converted to "test %reg,%reg";
  7691. additionally, some jumps will always (or never) branch, so
  7692. evaluate every jump immediately following the
  7693. comparison, optimising the conditions if possible.
  7694. Similarly with SETcc... those that are always set to 0 or 1
  7695. are changed to MOV instructions }
  7696. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7697. (
  7698. GetNextInstruction(hp2, hp1) and
  7699. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7700. ) do
  7701. begin
  7702. Prefetch(hp1.Next);
  7703. FirstMatch := False;
  7704. case taicpu(hp1).condition of
  7705. C_B, C_C, C_NAE, C_O:
  7706. { For B/NAE:
  7707. Will never branch since an unsigned integer can never be below zero
  7708. For C/O:
  7709. Result cannot overflow because 0 is being subtracted
  7710. }
  7711. begin
  7712. if taicpu(hp1).opcode = A_Jcc then
  7713. begin
  7714. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7715. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7716. RemoveInstruction(hp1);
  7717. { Since hp1 was deleted, hp2 must not be updated }
  7718. Continue;
  7719. end
  7720. else
  7721. begin
  7722. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7723. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7724. taicpu(hp1).opcode := A_MOV;
  7725. taicpu(hp1).ops := 2;
  7726. taicpu(hp1).condition := C_None;
  7727. taicpu(hp1).opsize := S_B;
  7728. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7729. taicpu(hp1).loadconst(0, 0);
  7730. end;
  7731. end;
  7732. C_BE, C_NA:
  7733. begin
  7734. { Will only branch if equal to zero }
  7735. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7736. taicpu(hp1).condition := C_E;
  7737. end;
  7738. C_A, C_NBE:
  7739. begin
  7740. { Will only branch if not equal to zero }
  7741. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7742. taicpu(hp1).condition := C_NE;
  7743. end;
  7744. C_AE, C_NB, C_NC, C_NO:
  7745. begin
  7746. { Will always branch }
  7747. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7748. if taicpu(hp1).opcode = A_Jcc then
  7749. begin
  7750. MakeUnconditional(taicpu(hp1));
  7751. { Any jumps/set that follow will now be dead code }
  7752. RemoveDeadCodeAfterJump(taicpu(hp1));
  7753. Break;
  7754. end
  7755. else
  7756. begin
  7757. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7758. taicpu(hp1).opcode := A_MOV;
  7759. taicpu(hp1).ops := 2;
  7760. taicpu(hp1).condition := C_None;
  7761. taicpu(hp1).opsize := S_B;
  7762. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7763. taicpu(hp1).loadconst(0, 1);
  7764. end;
  7765. end;
  7766. C_None:
  7767. InternalError(2020012201);
  7768. C_P, C_PE, C_NP, C_PO:
  7769. { We can't handle parity checks and they should never be generated
  7770. after a general-purpose CMP (it's used in some floating-point
  7771. comparisons that don't use CMP) }
  7772. InternalError(2020012202);
  7773. else
  7774. { Zero/Equality, Sign, their complements and all of the
  7775. signed comparisons do not need to be converted };
  7776. end;
  7777. hp2 := hp1;
  7778. end;
  7779. { Convert the instruction to a TEST }
  7780. taicpu(p).opcode := A_TEST;
  7781. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7782. Result := True;
  7783. Exit;
  7784. end
  7785. else
  7786. begin
  7787. TransferUsedRegs(TmpUsedRegs);
  7788. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7789. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7790. begin
  7791. if (taicpu(p).oper[0]^.val = 1) and
  7792. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7793. begin
  7794. { Convert; To:
  7795. cmp $1,r/m cmp $0,r/m
  7796. jl @lbl jle @lbl
  7797. (Also do inverted conditions)
  7798. }
  7799. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7800. taicpu(p).oper[0]^.val := 0;
  7801. if taicpu(hp1).condition in [C_L, C_NGE] then
  7802. taicpu(hp1).condition := C_LE
  7803. else
  7804. taicpu(hp1).condition := C_NLE;
  7805. { If the instruction is now "cmp $0,%reg", convert it to a
  7806. TEST (and effectively do the work of the "cmp $0,%reg" in
  7807. the block above)
  7808. }
  7809. if (taicpu(p).oper[1]^.typ = top_reg) then
  7810. begin
  7811. taicpu(p).opcode := A_TEST;
  7812. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7813. end;
  7814. Result := True;
  7815. Exit;
  7816. end
  7817. else if (taicpu(p).oper[1]^.typ = top_reg)
  7818. {$ifdef x86_64}
  7819. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7820. {$endif x86_64}
  7821. then
  7822. begin
  7823. { cmp register,$8000 neg register
  7824. je target --> jo target
  7825. .... only if register is deallocated before jump.}
  7826. case Taicpu(p).opsize of
  7827. S_B: v:=$80;
  7828. S_W: v:=$8000;
  7829. S_L: v:=qword($80000000);
  7830. else
  7831. internalerror(2013112905);
  7832. end;
  7833. if (taicpu(p).oper[0]^.val=v) and
  7834. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7835. begin
  7836. TransferUsedRegs(TmpUsedRegs);
  7837. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7838. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7839. begin
  7840. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7841. Taicpu(p).opcode:=A_NEG;
  7842. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7843. Taicpu(p).clearop(1);
  7844. Taicpu(p).ops:=1;
  7845. if Taicpu(hp1).condition=C_E then
  7846. Taicpu(hp1).condition:=C_O
  7847. else
  7848. Taicpu(hp1).condition:=C_NO;
  7849. Result:=true;
  7850. exit;
  7851. end;
  7852. end;
  7853. end;
  7854. end;
  7855. end;
  7856. end;
  7857. if TrySwapMovCmp(p, hp1) then
  7858. begin
  7859. Result := True;
  7860. Exit;
  7861. end;
  7862. end;
  7863. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7864. var
  7865. hp1: tai;
  7866. begin
  7867. {
  7868. remove the second (v)pxor from
  7869. pxor reg,reg
  7870. ...
  7871. pxor reg,reg
  7872. }
  7873. Result:=false;
  7874. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7875. MatchOpType(taicpu(p),top_reg,top_reg) and
  7876. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7877. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7878. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7879. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7880. begin
  7881. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7882. RemoveInstruction(hp1);
  7883. Result:=true;
  7884. Exit;
  7885. end
  7886. {
  7887. replace
  7888. pxor reg1,reg1
  7889. movapd/s reg1,reg2
  7890. dealloc reg1
  7891. by
  7892. pxor reg2,reg2
  7893. }
  7894. else if GetNextInstruction(p,hp1) and
  7895. { we mix single and double opperations here because we assume that the compiler
  7896. generates vmovapd only after double operations and vmovaps only after single operations }
  7897. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7898. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7899. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7900. (taicpu(p).oper[0]^.typ=top_reg) then
  7901. begin
  7902. TransferUsedRegs(TmpUsedRegs);
  7903. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7904. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7905. begin
  7906. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7907. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7908. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7909. RemoveInstruction(hp1);
  7910. result:=true;
  7911. end;
  7912. end;
  7913. end;
  7914. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7915. var
  7916. hp1: tai;
  7917. begin
  7918. {
  7919. remove the second (v)pxor from
  7920. (v)pxor reg,reg
  7921. ...
  7922. (v)pxor reg,reg
  7923. }
  7924. Result:=false;
  7925. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7926. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7927. begin
  7928. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7929. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7930. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7931. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7932. begin
  7933. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7934. RemoveInstruction(hp1);
  7935. Result:=true;
  7936. Exit;
  7937. end;
  7938. {$ifdef x86_64}
  7939. {
  7940. replace
  7941. vpxor reg1,reg1,reg1
  7942. vmov reg,mem
  7943. by
  7944. movq $0,mem
  7945. }
  7946. if GetNextInstruction(p,hp1) and
  7947. MatchInstruction(hp1,A_VMOVSD,[]) and
  7948. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7949. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7950. begin
  7951. TransferUsedRegs(TmpUsedRegs);
  7952. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7953. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7954. begin
  7955. taicpu(hp1).loadconst(0,0);
  7956. taicpu(hp1).opcode:=A_MOV;
  7957. taicpu(hp1).opsize:=S_Q;
  7958. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7959. RemoveCurrentP(p);
  7960. result:=true;
  7961. Exit;
  7962. end;
  7963. end;
  7964. {$endif x86_64}
  7965. end
  7966. {
  7967. replace
  7968. vpxor reg1,reg1,reg2
  7969. by
  7970. vpxor reg2,reg2,reg2
  7971. to avoid unncessary data dependencies
  7972. }
  7973. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7974. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7975. begin
  7976. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7977. { avoid unncessary data dependency }
  7978. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7979. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7980. result:=true;
  7981. exit;
  7982. end;
  7983. Result:=OptPass1VOP(p);
  7984. end;
  7985. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7986. var
  7987. hp1 : tai;
  7988. begin
  7989. result:=false;
  7990. { replace
  7991. IMul const,%mreg1,%mreg2
  7992. Mov %reg2,%mreg3
  7993. dealloc %mreg3
  7994. by
  7995. Imul const,%mreg1,%mreg23
  7996. }
  7997. if (taicpu(p).ops=3) and
  7998. GetNextInstruction(p,hp1) and
  7999. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8000. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8001. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8002. begin
  8003. TransferUsedRegs(TmpUsedRegs);
  8004. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8005. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8006. begin
  8007. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8008. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  8009. RemoveInstruction(hp1);
  8010. result:=true;
  8011. end;
  8012. end;
  8013. end;
  8014. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  8015. var
  8016. hp1 : tai;
  8017. begin
  8018. result:=false;
  8019. { replace
  8020. IMul %reg0,%reg1,%reg2
  8021. Mov %reg2,%reg3
  8022. dealloc %reg2
  8023. by
  8024. Imul %reg0,%reg1,%reg3
  8025. }
  8026. if GetNextInstruction(p,hp1) and
  8027. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8028. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8029. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8030. begin
  8031. TransferUsedRegs(TmpUsedRegs);
  8032. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8033. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8034. begin
  8035. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8036. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8037. RemoveInstruction(hp1);
  8038. result:=true;
  8039. end;
  8040. end;
  8041. end;
  8042. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8043. var
  8044. hp1: tai;
  8045. begin
  8046. Result:=false;
  8047. { get rid of
  8048. (v)cvtss2sd reg0,<reg1,>reg2
  8049. (v)cvtss2sd reg2,<reg2,>reg0
  8050. }
  8051. if GetNextInstruction(p,hp1) and
  8052. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8053. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8054. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8055. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8056. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8057. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8058. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8059. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8060. )
  8061. ) then
  8062. begin
  8063. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8064. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8065. begin
  8066. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8067. RemoveCurrentP(p);
  8068. RemoveInstruction(hp1);
  8069. end
  8070. else
  8071. begin
  8072. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8073. if taicpu(hp1).opcode=A_CVTSD2SS then
  8074. begin
  8075. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8076. taicpu(p).opcode:=A_MOVAPS;
  8077. end
  8078. else
  8079. begin
  8080. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8081. taicpu(p).opcode:=A_VMOVAPS;
  8082. end;
  8083. taicpu(p).ops:=2;
  8084. RemoveInstruction(hp1);
  8085. end;
  8086. Result:=true;
  8087. Exit;
  8088. end;
  8089. end;
  8090. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8091. var
  8092. hp1, hp2, hp3, hp4, hp5: tai;
  8093. ThisReg: TRegister;
  8094. begin
  8095. Result := False;
  8096. if not GetNextInstruction(p,hp1) then
  8097. Exit;
  8098. {
  8099. convert
  8100. j<c> .L1
  8101. mov 1,reg
  8102. jmp .L2
  8103. .L1
  8104. mov 0,reg
  8105. .L2
  8106. into
  8107. mov 0,reg
  8108. set<not(c)> reg
  8109. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8110. would destroy the flag contents
  8111. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8112. executed at the same time as a previous comparison.
  8113. set<not(c)> reg
  8114. movzx reg, reg
  8115. }
  8116. if MatchInstruction(hp1,A_MOV,[]) and
  8117. (taicpu(hp1).oper[0]^.typ = top_const) and
  8118. (
  8119. (
  8120. (taicpu(hp1).oper[1]^.typ = top_reg)
  8121. {$ifdef i386}
  8122. { Under i386, ESI, EDI, EBP and ESP
  8123. don't have an 8-bit representation }
  8124. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8125. {$endif i386}
  8126. ) or (
  8127. {$ifdef i386}
  8128. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8129. {$endif i386}
  8130. (taicpu(hp1).opsize = S_B)
  8131. )
  8132. ) and
  8133. GetNextInstruction(hp1,hp2) and
  8134. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8135. GetNextInstruction(hp2,hp3) and
  8136. FindLabel(tasmlabel(taicpu(p).oper[0]^.ref^.symbol), hp3) and
  8137. GetNextInstruction(hp3,hp4) and
  8138. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8139. (taicpu(hp4).oper[0]^.typ = top_const) and
  8140. (
  8141. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8142. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8143. ) and
  8144. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8145. GetNextInstruction(hp4,hp5) and
  8146. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol), hp5) then
  8147. begin
  8148. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8149. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8150. tai_label(hp3).labsym.DecRefs;
  8151. { If this isn't the only reference to the middle label, we can
  8152. still make a saving - only that the first jump and everything
  8153. that follows will remain. }
  8154. if (tai_label(hp3).labsym.getrefs = 0) then
  8155. begin
  8156. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8157. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8158. else
  8159. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8160. { remove jump, first label and second MOV (also catching any aligns) }
  8161. repeat
  8162. if not GetNextInstruction(hp2, hp3) then
  8163. InternalError(2021040810);
  8164. RemoveInstruction(hp2);
  8165. hp2 := hp3;
  8166. until hp2 = hp5;
  8167. { Don't decrement reference count before the removal loop
  8168. above, otherwise GetNextInstruction won't stop on the
  8169. the label }
  8170. tai_label(hp5).labsym.DecRefs;
  8171. end
  8172. else
  8173. begin
  8174. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8175. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8176. else
  8177. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8178. end;
  8179. taicpu(p).opcode:=A_SETcc;
  8180. taicpu(p).opsize:=S_B;
  8181. taicpu(p).is_jmp:=False;
  8182. if taicpu(hp1).opsize=S_B then
  8183. begin
  8184. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8185. if taicpu(hp1).oper[1]^.typ = top_reg then
  8186. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8187. RemoveInstruction(hp1);
  8188. end
  8189. else
  8190. begin
  8191. { Will be a register because the size can't be S_B otherwise }
  8192. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8193. taicpu(p).loadreg(0, ThisReg);
  8194. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8195. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8196. begin
  8197. case taicpu(hp1).opsize of
  8198. S_W:
  8199. taicpu(hp1).opsize := S_BW;
  8200. S_L:
  8201. taicpu(hp1).opsize := S_BL;
  8202. {$ifdef x86_64}
  8203. S_Q:
  8204. begin
  8205. taicpu(hp1).opsize := S_BL;
  8206. { Change the destination register to 32-bit }
  8207. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8208. end;
  8209. {$endif x86_64}
  8210. else
  8211. InternalError(2021040820);
  8212. end;
  8213. taicpu(hp1).opcode := A_MOVZX;
  8214. taicpu(hp1).loadreg(0, ThisReg);
  8215. end
  8216. else
  8217. begin
  8218. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8219. { hp1 is already a MOV instruction with the correct register }
  8220. taicpu(hp1).loadconst(0, 0);
  8221. { Inserting it right before p will guarantee that the flags are also tracked }
  8222. asml.Remove(hp1);
  8223. asml.InsertBefore(hp1, p);
  8224. end;
  8225. end;
  8226. Result:=true;
  8227. exit;
  8228. end
  8229. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8230. Result := TryJccStcClcOpt(p, hp1)
  8231. else if (hp1.typ = ait_label) then
  8232. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8233. end;
  8234. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8235. var
  8236. hp1, hp2, hp3: tai;
  8237. SourceRef, TargetRef: TReference;
  8238. CurrentReg: TRegister;
  8239. begin
  8240. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8241. if not UseAVX then
  8242. InternalError(2021100501);
  8243. Result := False;
  8244. { Look for the following to simplify:
  8245. vmovdqa/u x(mem1), %xmmreg
  8246. vmovdqa/u %xmmreg, y(mem2)
  8247. vmovdqa/u x+16(mem1), %xmmreg
  8248. vmovdqa/u %xmmreg, y+16(mem2)
  8249. Change to:
  8250. vmovdqa/u x(mem1), %ymmreg
  8251. vmovdqa/u %ymmreg, y(mem2)
  8252. vpxor %ymmreg, %ymmreg, %ymmreg
  8253. ( The VPXOR instruction is to zero the upper half, thus removing the
  8254. need to call the potentially expensive VZEROUPPER instruction. Other
  8255. peephole optimisations can remove VPXOR if it's unnecessary )
  8256. }
  8257. TransferUsedRegs(TmpUsedRegs);
  8258. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8259. { NOTE: In the optimisations below, if the references dictate that an
  8260. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8261. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8262. if (taicpu(p).opsize = S_XMM) and
  8263. MatchOpType(taicpu(p), top_ref, top_reg) and
  8264. GetNextInstruction(p, hp1) and
  8265. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8266. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8267. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8268. begin
  8269. SourceRef := taicpu(p).oper[0]^.ref^;
  8270. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8271. if GetNextInstruction(hp1, hp2) and
  8272. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8273. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8274. begin
  8275. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8276. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8277. Inc(SourceRef.offset, 16);
  8278. { Reuse the register in the first block move }
  8279. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8280. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8281. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8282. begin
  8283. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8284. Inc(TargetRef.offset, 16);
  8285. if GetNextInstruction(hp2, hp3) and
  8286. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8287. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8288. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8289. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8290. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8291. begin
  8292. { Update the register tracking to the new size }
  8293. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8294. { Remember that the offsets are 16 ahead }
  8295. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8296. if not (
  8297. ((SourceRef.offset mod 32) = 16) and
  8298. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8299. ) then
  8300. taicpu(p).opcode := A_VMOVDQU;
  8301. taicpu(p).opsize := S_YMM;
  8302. taicpu(p).oper[1]^.reg := CurrentReg;
  8303. if not (
  8304. ((TargetRef.offset mod 32) = 16) and
  8305. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8306. ) then
  8307. taicpu(hp1).opcode := A_VMOVDQU;
  8308. taicpu(hp1).opsize := S_YMM;
  8309. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8310. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8311. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8312. if (pi_uses_ymm in current_procinfo.flags) then
  8313. RemoveInstruction(hp2)
  8314. else
  8315. begin
  8316. taicpu(hp2).opcode := A_VPXOR;
  8317. taicpu(hp2).opsize := S_YMM;
  8318. taicpu(hp2).loadreg(0, CurrentReg);
  8319. taicpu(hp2).loadreg(1, CurrentReg);
  8320. taicpu(hp2).loadreg(2, CurrentReg);
  8321. taicpu(hp2).ops := 3;
  8322. end;
  8323. RemoveInstruction(hp3);
  8324. Result := True;
  8325. Exit;
  8326. end;
  8327. end
  8328. else
  8329. begin
  8330. { See if the next references are 16 less rather than 16 greater }
  8331. Dec(SourceRef.offset, 32); { -16 the other way }
  8332. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8333. begin
  8334. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8335. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8336. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8337. GetNextInstruction(hp2, hp3) and
  8338. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8339. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8340. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8341. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8342. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8343. begin
  8344. { Update the register tracking to the new size }
  8345. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8346. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8347. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8348. if not(
  8349. ((SourceRef.offset mod 32) = 0) and
  8350. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8351. ) then
  8352. taicpu(hp2).opcode := A_VMOVDQU;
  8353. taicpu(hp2).opsize := S_YMM;
  8354. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8355. if not (
  8356. ((TargetRef.offset mod 32) = 0) and
  8357. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8358. ) then
  8359. taicpu(hp3).opcode := A_VMOVDQU;
  8360. taicpu(hp3).opsize := S_YMM;
  8361. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8362. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8363. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8364. if (pi_uses_ymm in current_procinfo.flags) then
  8365. RemoveInstruction(hp1)
  8366. else
  8367. begin
  8368. taicpu(hp1).opcode := A_VPXOR;
  8369. taicpu(hp1).opsize := S_YMM;
  8370. taicpu(hp1).loadreg(0, CurrentReg);
  8371. taicpu(hp1).loadreg(1, CurrentReg);
  8372. taicpu(hp1).loadreg(2, CurrentReg);
  8373. taicpu(hp1).ops := 3;
  8374. Asml.Remove(hp1);
  8375. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8376. end;
  8377. RemoveCurrentP(p, hp2);
  8378. Result := True;
  8379. Exit;
  8380. end;
  8381. end;
  8382. end;
  8383. end;
  8384. end;
  8385. end;
  8386. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8387. var
  8388. hp2, hp3, first_assignment: tai;
  8389. IncCount, OperIdx: Integer;
  8390. OrigLabel: TAsmLabel;
  8391. begin
  8392. Count := 0;
  8393. Result := False;
  8394. first_assignment := nil;
  8395. if (LoopCount >= 20) then
  8396. begin
  8397. { Guard against infinite loops }
  8398. Exit;
  8399. end;
  8400. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8401. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8402. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8403. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8404. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8405. Exit;
  8406. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8407. {
  8408. change
  8409. jmp .L1
  8410. ...
  8411. .L1:
  8412. mov ##, ## ( multiple movs possible )
  8413. jmp/ret
  8414. into
  8415. mov ##, ##
  8416. jmp/ret
  8417. }
  8418. if not Assigned(hp1) then
  8419. begin
  8420. hp1 := GetLabelWithSym(OrigLabel);
  8421. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8422. Exit;
  8423. end;
  8424. hp2 := hp1;
  8425. while Assigned(hp2) do
  8426. begin
  8427. if Assigned(hp2) and (hp2.typ = ait_label) then
  8428. SkipLabels(hp2,hp2);
  8429. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8430. Break;
  8431. case taicpu(hp2).opcode of
  8432. A_MOVSD:
  8433. begin
  8434. if taicpu(hp2).ops = 0 then
  8435. { Wrong MOVSD }
  8436. Break;
  8437. Inc(Count);
  8438. if Count >= 5 then
  8439. { Too many to be worthwhile }
  8440. Break;
  8441. GetNextInstruction(hp2, hp2);
  8442. Continue;
  8443. end;
  8444. A_MOV,
  8445. A_MOVD,
  8446. A_MOVQ,
  8447. A_MOVSX,
  8448. {$ifdef x86_64}
  8449. A_MOVSXD,
  8450. {$endif x86_64}
  8451. A_MOVZX,
  8452. A_MOVAPS,
  8453. A_MOVUPS,
  8454. A_MOVSS,
  8455. A_MOVAPD,
  8456. A_MOVUPD,
  8457. A_MOVDQA,
  8458. A_MOVDQU,
  8459. A_VMOVSS,
  8460. A_VMOVAPS,
  8461. A_VMOVUPS,
  8462. A_VMOVSD,
  8463. A_VMOVAPD,
  8464. A_VMOVUPD,
  8465. A_VMOVDQA,
  8466. A_VMOVDQU:
  8467. begin
  8468. Inc(Count);
  8469. if Count >= 5 then
  8470. { Too many to be worthwhile }
  8471. Break;
  8472. GetNextInstruction(hp2, hp2);
  8473. Continue;
  8474. end;
  8475. A_JMP:
  8476. begin
  8477. { Guard against infinite loops }
  8478. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8479. Exit;
  8480. { Analyse this jump first in case it also duplicates assignments }
  8481. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8482. begin
  8483. { Something did change! }
  8484. Result := True;
  8485. Inc(Count, IncCount);
  8486. if Count >= 5 then
  8487. begin
  8488. { Too many to be worthwhile }
  8489. Exit;
  8490. end;
  8491. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8492. Break;
  8493. end;
  8494. Result := True;
  8495. Break;
  8496. end;
  8497. A_RET:
  8498. begin
  8499. Result := True;
  8500. Break;
  8501. end;
  8502. else
  8503. Break;
  8504. end;
  8505. end;
  8506. if Result then
  8507. begin
  8508. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8509. if Count = 0 then
  8510. begin
  8511. Result := False;
  8512. Exit;
  8513. end;
  8514. TransferUsedRegs(TmpUsedRegs);
  8515. hp3 := p;
  8516. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8517. while True do
  8518. begin
  8519. if Assigned(hp1) and (hp1.typ = ait_label) then
  8520. SkipLabels(hp1,hp1);
  8521. case hp1.typ of
  8522. ait_regalloc:
  8523. if tai_regalloc(hp1).ratype = ra_dealloc then
  8524. begin
  8525. { Duplicate the register deallocation... }
  8526. hp3:=tai(hp1.getcopy);
  8527. if first_assignment = nil then
  8528. first_assignment := hp3;
  8529. asml.InsertBefore(hp3, p);
  8530. { ... but also reallocate it after the jump }
  8531. hp3:=tai(hp1.getcopy);
  8532. tai_regalloc(hp3).ratype := ra_alloc;
  8533. asml.InsertAfter(hp3, p);
  8534. end;
  8535. ait_instruction:
  8536. case taicpu(hp1).opcode of
  8537. A_JMP:
  8538. begin
  8539. { Change the original jump to the new destination }
  8540. OrigLabel.decrefs;
  8541. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8542. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8543. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8544. if not Assigned(first_assignment) then
  8545. InternalError(2021040810)
  8546. else
  8547. p := first_assignment;
  8548. Exit;
  8549. end;
  8550. A_RET:
  8551. begin
  8552. { Now change the jump into a RET instruction }
  8553. ConvertJumpToRET(p, hp1);
  8554. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8555. if not Assigned(first_assignment) then
  8556. InternalError(2021040811)
  8557. else
  8558. p := first_assignment;
  8559. Exit;
  8560. end;
  8561. else
  8562. begin
  8563. { Duplicate the MOV instruction }
  8564. hp3:=tai(hp1.getcopy);
  8565. if first_assignment = nil then
  8566. first_assignment := hp3;
  8567. asml.InsertBefore(hp3, p);
  8568. { Make sure the compiler knows about any final registers written here }
  8569. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8570. with taicpu(hp3).oper[OperIdx]^ do
  8571. begin
  8572. case typ of
  8573. top_ref:
  8574. begin
  8575. if (ref^.base <> NR_NO) and
  8576. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8577. (
  8578. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8579. (
  8580. { Allow the frame pointer if it's not being used by the procedure as such }
  8581. Assigned(current_procinfo) and
  8582. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8583. )
  8584. )
  8585. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8586. then
  8587. begin
  8588. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8589. if not Assigned(first_assignment) then
  8590. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8591. end;
  8592. if (ref^.index <> NR_NO) and
  8593. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8594. (
  8595. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8596. (
  8597. { Allow the frame pointer if it's not being used by the procedure as such }
  8598. Assigned(current_procinfo) and
  8599. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8600. )
  8601. )
  8602. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8603. (ref^.index <> ref^.base) then
  8604. begin
  8605. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8606. if not Assigned(first_assignment) then
  8607. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8608. end;
  8609. end;
  8610. top_reg:
  8611. begin
  8612. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8613. if not Assigned(first_assignment) then
  8614. IncludeRegInUsedRegs(reg, UsedRegs);
  8615. end;
  8616. else
  8617. ;
  8618. end;
  8619. end;
  8620. end;
  8621. end;
  8622. else
  8623. InternalError(2021040720);
  8624. end;
  8625. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8626. { Should have dropped out earlier }
  8627. InternalError(2021040710);
  8628. end;
  8629. end;
  8630. end;
  8631. const
  8632. WriteOp: array[0..3] of set of TInsChange = (
  8633. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8634. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8635. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8636. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8637. RegWriteFlags: array[0..7] of set of TInsChange = (
  8638. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8639. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8640. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8641. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8642. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8643. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8644. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8645. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8646. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8647. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8648. var
  8649. hp2: tai;
  8650. X: Integer;
  8651. begin
  8652. { If we have something like:
  8653. op ###,###
  8654. mov ###,###
  8655. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8656. interfere in regards to what they write to.
  8657. NOTE: p must be a 2-operand instruction
  8658. }
  8659. Result := False;
  8660. if (hp1.typ <> ait_instruction) or
  8661. taicpu(hp1).is_jmp or
  8662. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8663. Exit;
  8664. { NOP is a pipeline fence, likely marking the beginning of the function
  8665. epilogue, so drop out. Similarly, drop out if POP or RET are
  8666. encountered }
  8667. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8668. Exit;
  8669. if (taicpu(hp1).opcode = A_MOVSD) and
  8670. (taicpu(hp1).ops = 0) then
  8671. { Wrong MOVSD }
  8672. Exit;
  8673. { Check for writes to specific registers first }
  8674. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8675. for X := 0 to 7 do
  8676. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8677. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8678. Exit;
  8679. for X := 0 to taicpu(hp1).ops - 1 do
  8680. begin
  8681. { Check to see if this operand writes to something }
  8682. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8683. { And matches something in the CMP/TEST instruction }
  8684. (
  8685. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8686. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8687. (
  8688. { If it's a register, make sure the register written to doesn't
  8689. appear in the cmp instruction as part of a reference }
  8690. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8691. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8692. )
  8693. ) then
  8694. Exit;
  8695. end;
  8696. { Check p to make sure it doesn't write to something that affects hp1 }
  8697. { Check for writes to specific registers first }
  8698. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8699. for X := 0 to 7 do
  8700. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8701. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8702. Exit;
  8703. for X := 0 to taicpu(p).ops - 1 do
  8704. begin
  8705. { Check to see if this operand writes to something }
  8706. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8707. { And matches something in hp1 }
  8708. (taicpu(p).oper[X]^.typ = top_reg) and
  8709. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8710. Exit;
  8711. end;
  8712. { The instruction can be safely moved }
  8713. asml.Remove(hp1);
  8714. { Try to insert after the last instructions where the FLAGS register is not
  8715. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8716. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8717. asml.InsertBefore(hp1, hp2)
  8718. { Failing that, try to insert after the last instructions where the
  8719. FLAGS register is not yet in use }
  8720. else if GetLastInstruction(p, hp2) and
  8721. (
  8722. (hp2.typ <> ait_instruction) or
  8723. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8724. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8725. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8726. ) then
  8727. asml.InsertAfter(hp1, hp2)
  8728. else
  8729. { Note, if p.Previous is nil (even if it should logically never be the
  8730. case), FindRegAllocBackward immediately exits with False and so we
  8731. safely land here (we can't just pass p because FindRegAllocBackward
  8732. immediately exits on an instruction). [Kit] }
  8733. asml.InsertBefore(hp1, p);
  8734. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8735. { We can't trust UsedRegs because we're looking backwards, although we
  8736. know the registers are allocated after p at the very least, so manually
  8737. create tai_regalloc objects if needed }
  8738. for X := 0 to taicpu(hp1).ops - 1 do
  8739. case taicpu(hp1).oper[X]^.typ of
  8740. top_reg:
  8741. begin
  8742. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8743. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8744. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8745. end;
  8746. top_ref:
  8747. begin
  8748. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8749. begin
  8750. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8751. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8752. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8753. end;
  8754. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8755. begin
  8756. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8757. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8758. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8759. end;
  8760. end;
  8761. else
  8762. ;
  8763. end;
  8764. Result := True;
  8765. end;
  8766. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8767. var
  8768. hp2: tai;
  8769. X: Integer;
  8770. begin
  8771. { If we have something like:
  8772. cmp ###,%reg1
  8773. mov 0,%reg2
  8774. And no modified registers are shared, move the instruction to before
  8775. the comparison as this means it can be optimised without worrying
  8776. about the FLAGS register. (CMP/MOV is generated by
  8777. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8778. As long as the second instruction doesn't use the flags or one of the
  8779. registers used by CMP or TEST (also check any references that use the
  8780. registers), then it can be moved prior to the comparison.
  8781. }
  8782. Result := False;
  8783. if not TrySwapMovOp(p, hp1) then
  8784. Exit;
  8785. if taicpu(hp1).opcode = A_LEA then
  8786. { The flags will be overwritten by the CMP/TEST instruction }
  8787. ConvertLEA(taicpu(hp1));
  8788. Result := True;
  8789. { Can we move it one further back? }
  8790. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8791. { Check to see if CMP/TEST is a comparison against zero }
  8792. (
  8793. (
  8794. (taicpu(p).opcode = A_CMP) and
  8795. MatchOperand(taicpu(p).oper[0]^, 0)
  8796. ) or
  8797. (
  8798. (taicpu(p).opcode = A_TEST) and
  8799. (
  8800. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8801. MatchOperand(taicpu(p).oper[0]^, -1)
  8802. )
  8803. )
  8804. ) and
  8805. { These instructions set the zero flag if the result is zero }
  8806. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8807. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8808. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8809. TrySwapMovOp(hp2, hp1);
  8810. end;
  8811. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8812. var
  8813. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8814. JumpLabel: TAsmLabel;
  8815. TmpBool: Boolean;
  8816. begin
  8817. Result := False;
  8818. { Look for:
  8819. stc/clc
  8820. j(c) .L1
  8821. ...
  8822. .L1:
  8823. set(n)cb %reg
  8824. (flags deallocated)
  8825. j(c) .L2
  8826. Change to:
  8827. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8828. j(c) .L2
  8829. }
  8830. p_last := p;
  8831. while GetNextInstruction(p_last, hp1) and
  8832. (hp1.typ = ait_instruction) and
  8833. IsJumpToLabel(taicpu(hp1)) do
  8834. begin
  8835. if DoJumpOptimizations(hp1, TmpBool) then
  8836. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8837. Continue;
  8838. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8839. if not Assigned(JumpLabel) then
  8840. InternalError(2024012801);
  8841. { Optimise the J(c); stc/clc optimisation first since this will
  8842. get missed if the main optimisation takes place }
  8843. if (taicpu(hp1).opcode = A_JCC) then
  8844. begin
  8845. if GetNextInstruction(hp1, hp2) and
  8846. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8847. TryJccStcClcOpt(hp1, hp2) then
  8848. begin
  8849. Result := True;
  8850. Exit;
  8851. end;
  8852. hp2 := nil; { Suppress compiler warning }
  8853. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8854. { Make sure the flags aren't used again }
  8855. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8856. begin
  8857. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8858. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8859. begin
  8860. if (taicpu(p).opcode = A_STC) then
  8861. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8862. else
  8863. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8864. MakeUnconditional(taicpu(hp1));
  8865. { Move the jump to after the flag deallocations }
  8866. Asml.Remove(hp1);
  8867. Asml.InsertAfter(hp1, hp2);
  8868. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8869. Result := True;
  8870. Exit;
  8871. end
  8872. else
  8873. begin
  8874. if (taicpu(p).opcode = A_STC) then
  8875. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8876. else
  8877. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8878. { In this case, the jump is deterministic in that it will never be taken }
  8879. JumpLabel.DecRefs;
  8880. RemoveInstruction(hp1);
  8881. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8882. Result := True;
  8883. Exit;
  8884. end;
  8885. end;
  8886. end;
  8887. hp2 := nil; { Suppress compiler warning }
  8888. if
  8889. { Make sure the carry flag doesn't appear in the jump conditions }
  8890. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8891. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8892. GetNextInstruction(hp2, p_dist) and
  8893. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8894. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8895. begin
  8896. case taicpu(p_dist).opcode of
  8897. A_Jcc:
  8898. begin
  8899. if DoJumpOptimizations(p_dist, TmpBool) then
  8900. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8901. Continue;
  8902. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8903. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8904. begin
  8905. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8906. JumpLabel.decrefs;
  8907. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8908. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8909. Result := True;
  8910. Exit;
  8911. end
  8912. else if GetNextInstruction(p_dist, hp1_dist) and
  8913. (hp1_dist.typ = ait_label) then
  8914. begin
  8915. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8916. JumpLabel.decrefs;
  8917. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8918. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8919. Result := True;
  8920. Exit;
  8921. end;
  8922. end;
  8923. A_SETcc:
  8924. if { Make sure the flags aren't used again }
  8925. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8926. GetNextInstruction(hp2, hp1_dist) and
  8927. (hp1_dist.typ = ait_instruction) and
  8928. IsJumpToLabel(taicpu(hp1_dist)) and
  8929. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8930. { This works if hp1_dist or both are regular JMP instructions }
  8931. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8932. (
  8933. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8934. { Make sure the register isn't still in use, otherwise it
  8935. may get corrupted (fixes #40659) }
  8936. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8937. ) then
  8938. begin
  8939. taicpu(p).allocate_oper(2);
  8940. taicpu(p).ops := 2;
  8941. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8942. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8943. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8944. taicpu(p).opcode := A_MOV;
  8945. taicpu(p).opsize := S_B;
  8946. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8947. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8948. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8949. JumpLabel.decrefs;
  8950. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8951. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8952. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8953. (tai_regalloc(hp2).ratype = ra_alloc) then
  8954. begin
  8955. Asml.Remove(hp2);
  8956. Asml.InsertAfter(hp2, p);
  8957. end;
  8958. Result := True;
  8959. Exit;
  8960. end;
  8961. else
  8962. ;
  8963. end;
  8964. end;
  8965. p_last := hp1;
  8966. end;
  8967. end;
  8968. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8969. var
  8970. hp2, hp3: tai;
  8971. TempBool: Boolean;
  8972. begin
  8973. Result := False;
  8974. {
  8975. j(c) .L1
  8976. stc/clc
  8977. .L1:
  8978. jc/jnc .L2
  8979. (Flags deallocated)
  8980. Change to:
  8981. j)c) .L1
  8982. jmp .L2
  8983. .L1:
  8984. jc/jnc .L2
  8985. Then call DoJumpOptimizations to convert to:
  8986. j(nc) .L2
  8987. .L1: (may become a dead label)
  8988. jc/jnc .L2
  8989. }
  8990. if GetNextInstruction(hp1, hp2) and
  8991. (hp2.typ = ait_label) and
  8992. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8993. GetNextInstruction(hp2, hp3) and
  8994. MatchInstruction(hp3, A_Jcc, []) and
  8995. (
  8996. (
  8997. (taicpu(hp3).condition = C_C) and
  8998. (taicpu(hp1).opcode = A_STC)
  8999. ) or (
  9000. (taicpu(hp3).condition = C_NC) and
  9001. (taicpu(hp1).opcode = A_CLC)
  9002. )
  9003. ) and
  9004. { Make sure the flags aren't used again }
  9005. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  9006. begin
  9007. taicpu(hp1).allocate_oper(1);
  9008. taicpu(hp1).ops := 1;
  9009. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  9010. taicpu(hp1).opcode := A_JMP;
  9011. taicpu(hp1).is_jmp := True;
  9012. TempBool := True; { Prevent compiler warnings }
  9013. if DoJumpOptimizations(p, TempBool) then
  9014. Result := True
  9015. else
  9016. Include(OptsToCheck, aoc_ForceNewIteration);
  9017. end;
  9018. end;
  9019. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  9020. begin
  9021. { This generally only executes under -O3 and above }
  9022. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  9023. end;
  9024. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  9025. var
  9026. hp1, hp2: tai;
  9027. FoundComparison: Boolean;
  9028. begin
  9029. { Run the pass 1 optimisations as well, since they may have some effect
  9030. after the CMOV blocks are created in OptPass2Jcc }
  9031. Result := False;
  9032. { Result := OptPass1CMOVcc(p);
  9033. if Result then
  9034. Exit;}
  9035. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9036. and make a slightly inefficent result on branching-type blocks, notably
  9037. when setting a function result then jumping to the function epilogue.
  9038. In this case, change:
  9039. cmov(c) %reg1,%reg2
  9040. j(c) @lbl
  9041. (%reg2 deallocated)
  9042. To:
  9043. mov %reg11,%reg2
  9044. j(c) @lbl
  9045. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9046. jump because if it's not present, we may end up with a jump that's
  9047. completely unrelated.
  9048. }
  9049. hp1 := p;
  9050. while GetNextInstruction(hp1, hp1) and
  9051. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9052. if (hp1.typ = ait_instruction) and
  9053. (taicpu(hp1).opcode = A_Jcc) and
  9054. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9055. begin
  9056. TransferUsedRegs(TmpUsedRegs);
  9057. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9058. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9059. (
  9060. { See if we can find a more distant instruction that overwrites
  9061. the destination register }
  9062. (cs_opt_level3 in current_settings.optimizerswitches) and
  9063. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9064. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9065. ) then
  9066. begin
  9067. if (taicpu(p).oper[0]^.typ = top_reg) then
  9068. begin
  9069. { Search backwards to see if the source register is set to a
  9070. constant }
  9071. FoundComparison := False;
  9072. hp1 := p;
  9073. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9074. begin
  9075. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9076. begin
  9077. FoundComparison := True;
  9078. Continue;
  9079. end;
  9080. { Once we find the CMP, TEST or similar instruction, we
  9081. have to stop if we find anything other than a MOV }
  9082. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9083. Break;
  9084. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9085. { Destination register was modified }
  9086. Break;
  9087. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9088. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9089. begin
  9090. { Found a constant! }
  9091. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9092. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9093. { The source register is no longer in use }
  9094. RemoveInstruction(hp1);
  9095. Break;
  9096. end;
  9097. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9098. { Some other instruction has modified the source register }
  9099. Break;
  9100. end;
  9101. end;
  9102. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9103. taicpu(p).opcode := A_MOV;
  9104. taicpu(p).condition := C_None;
  9105. { Rely on the post peephole stage to put the MOV before the
  9106. CMP/TEST instruction that appears prior }
  9107. Result := True;
  9108. Exit;
  9109. end;
  9110. end;
  9111. end;
  9112. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9113. function IsXCHGAcceptable: Boolean; inline;
  9114. begin
  9115. { Always accept if optimising for size }
  9116. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9117. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9118. than 3, so it becomes a saving compared to three MOVs with two of
  9119. them able to execute simultaneously. [Kit] }
  9120. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9121. end;
  9122. var
  9123. NewRef: TReference;
  9124. hp1, hp2, hp3, hp4: Tai;
  9125. {$ifndef x86_64}
  9126. OperIdx: Integer;
  9127. {$endif x86_64}
  9128. NewInstr : Taicpu;
  9129. NewAligh : Tai_align;
  9130. DestLabel: TAsmLabel;
  9131. TempTracking: TAllUsedRegs;
  9132. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9133. var
  9134. NextInstr: tai;
  9135. begin
  9136. Result := False;
  9137. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9138. if not GetNextInstruction(InputInstr, NextInstr) or
  9139. (
  9140. { The FLAGS register isn't always tracked properly, so do not
  9141. perform this optimisation if a conditional statement follows }
  9142. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9143. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9144. ) then
  9145. begin
  9146. reference_reset(NewRef, 1, []);
  9147. NewRef.base := taicpu(p).oper[0]^.reg;
  9148. NewRef.scalefactor := 1;
  9149. if taicpu(InputInstr).opcode = A_ADD then
  9150. begin
  9151. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9152. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9153. end
  9154. else
  9155. begin
  9156. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9157. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9158. end;
  9159. taicpu(p).opcode := A_LEA;
  9160. taicpu(p).loadref(0, NewRef);
  9161. { For the sake of debugging, have the line info match the
  9162. arithmetic instruction rather than the MOV instruction }
  9163. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9164. RemoveInstruction(InputInstr);
  9165. Result := True;
  9166. end;
  9167. end;
  9168. begin
  9169. Result:=false;
  9170. { This optimisation adds an instruction, so only do it for speed }
  9171. if not (cs_opt_size in current_settings.optimizerswitches) and
  9172. MatchOpType(taicpu(p), top_const, top_reg) and
  9173. (taicpu(p).oper[0]^.val = 0) then
  9174. begin
  9175. { To avoid compiler warning }
  9176. DestLabel := nil;
  9177. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9178. InternalError(2021040750);
  9179. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9180. Exit;
  9181. case hp1.typ of
  9182. ait_label:
  9183. begin
  9184. { Change:
  9185. mov $0,%reg mov $0,%reg
  9186. @Lbl1: @Lbl1:
  9187. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9188. je @Lbl2 jne @Lbl2
  9189. To: To:
  9190. mov $0,%reg mov $0,%reg
  9191. jmp @Lbl2 jmp @Lbl3
  9192. (align) (align)
  9193. @Lbl1: @Lbl1:
  9194. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9195. je @Lbl2 je @Lbl2
  9196. @Lbl3: <-- Only if label exists
  9197. (Not if it's optimised for size)
  9198. }
  9199. if not GetNextInstruction(hp1, hp2) then
  9200. Exit;
  9201. if (hp2.typ = ait_instruction) and
  9202. (
  9203. { Register sizes must exactly match }
  9204. (
  9205. (taicpu(hp2).opcode = A_CMP) and
  9206. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9207. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9208. ) or (
  9209. (taicpu(hp2).opcode = A_TEST) and
  9210. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9211. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9212. )
  9213. ) and GetNextInstruction(hp2, hp3) and
  9214. (hp3.typ = ait_instruction) and
  9215. (taicpu(hp3).opcode = A_JCC) and
  9216. (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
  9217. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9218. begin
  9219. { Check condition of jump }
  9220. { Always true? }
  9221. if condition_in(C_E, taicpu(hp3).condition) then
  9222. begin
  9223. { Copy label symbol and obtain matching label entry for the
  9224. conditional jump, as this will be our destination}
  9225. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9226. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9227. Result := True;
  9228. end
  9229. { Always false? }
  9230. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9231. begin
  9232. { This is only worth it if there's a jump to take }
  9233. case hp2.typ of
  9234. ait_instruction:
  9235. begin
  9236. if taicpu(hp2).opcode = A_JMP then
  9237. begin
  9238. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9239. { An unconditional jump follows the conditional jump which will always be false,
  9240. so use this jump's destination for the new jump }
  9241. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9242. Result := True;
  9243. end
  9244. else if taicpu(hp2).opcode = A_JCC then
  9245. begin
  9246. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9247. if condition_in(C_E, taicpu(hp2).condition) then
  9248. begin
  9249. { A second conditional jump follows the conditional jump which will always be false,
  9250. while the second jump is always True, so use this jump's destination for the new jump }
  9251. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9252. Result := True;
  9253. end;
  9254. { Don't risk it if the jump isn't always true (Result remains False) }
  9255. end;
  9256. end;
  9257. else
  9258. { If anything else don't optimise };
  9259. end;
  9260. end;
  9261. if Result then
  9262. begin
  9263. { Just so we have something to insert as a paremeter}
  9264. reference_reset(NewRef, 1, []);
  9265. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9266. { Now actually load the correct parameter (this also
  9267. increases the reference count) }
  9268. NewInstr.loadsymbol(0, DestLabel, 0);
  9269. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9270. begin
  9271. { Get instruction before original label (may not be p under -O3) }
  9272. if not GetLastInstruction(hp1, hp2) then
  9273. { Shouldn't fail here }
  9274. InternalError(2021040701);
  9275. end
  9276. else
  9277. hp2 := p;
  9278. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9279. AsmL.InsertAfter(NewInstr, hp2);
  9280. { Add new alignment field }
  9281. (* AsmL.InsertAfter(
  9282. cai_align.create_max(
  9283. current_settings.alignment.jumpalign,
  9284. current_settings.alignment.jumpalignskipmax
  9285. ),
  9286. NewInstr
  9287. ); *)
  9288. end;
  9289. Exit;
  9290. end;
  9291. end;
  9292. else
  9293. ;
  9294. end;
  9295. end;
  9296. if not GetNextInstruction(p, hp1) then
  9297. Exit;
  9298. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9299. begin
  9300. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9301. begin
  9302. Result := True;
  9303. Exit;
  9304. end;
  9305. { This optimisation is only effective on a second run of Pass 2,
  9306. hence -O3 or above.
  9307. Change:
  9308. mov %reg1,%reg2
  9309. cmp/test (contains %reg1)
  9310. mov x, %reg1
  9311. (another mov or a j(c))
  9312. To:
  9313. mov %reg1,%reg2
  9314. mov x, %reg1
  9315. cmp (%reg1 replaced with %reg2)
  9316. (another mov or a j(c))
  9317. The requirement of an additional MOV or a jump ensures there
  9318. isn't performance loss, since a j(c) will permit macro-fusion
  9319. with the cmp instruction, while another MOV likely means it's
  9320. not all being executed in a single cycle due to parallelisation.
  9321. }
  9322. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9323. MatchOpType(taicpu(p), top_reg, top_reg) and
  9324. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9325. GetNextInstruction(hp1, hp2) and
  9326. MatchInstruction(hp2, A_MOV, []) and
  9327. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9328. { Registers don't have to be the same size in this case }
  9329. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9330. GetNextInstruction(hp2, hp3) and
  9331. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9332. { Make sure the operands in the camparison can be safely replaced }
  9333. (
  9334. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9335. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9336. ) and
  9337. (
  9338. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9339. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9340. ) then
  9341. begin
  9342. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9343. AsmL.Remove(hp2);
  9344. AsmL.InsertAfter(hp2, p);
  9345. Result := True;
  9346. Exit;
  9347. end;
  9348. end;
  9349. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9350. begin
  9351. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9352. further, but we can't just put this jump optimisation in pass 1
  9353. because it tends to perform worse when conditional jumps are
  9354. nearby (e.g. when converting CMOV instructions). [Kit] }
  9355. CopyUsedRegs(TempTracking);
  9356. UpdateUsedRegs(tai(p.Next));
  9357. if OptPass2JMP(hp1) then
  9358. begin
  9359. { Restore register state }
  9360. RestoreUsedRegs(TempTracking);
  9361. ReleaseUsedRegs(TempTracking);
  9362. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9363. OptPass1MOV(p);
  9364. Result := True;
  9365. Exit;
  9366. end;
  9367. { If OptPass2JMP returned False, no optimisations were done to
  9368. the jump and there are no further optimisations that can be done
  9369. to the MOV instruction on this pass other than FuncMov2Func }
  9370. { Restore register state }
  9371. RestoreUsedRegs(TempTracking);
  9372. ReleaseUsedRegs(TempTracking);
  9373. Result := FuncMov2Func(p, hp1);
  9374. Exit;
  9375. end;
  9376. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9377. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9378. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9379. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9380. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9381. begin
  9382. { Change:
  9383. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9384. addl/q $x,%reg2 subl/q $x,%reg2
  9385. To:
  9386. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9387. }
  9388. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9389. { be lazy, checking separately for sub would be slightly better }
  9390. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9391. begin
  9392. TransferUsedRegs(TmpUsedRegs);
  9393. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9394. if TryMovArith2Lea(hp1) then
  9395. begin
  9396. Result := True;
  9397. Exit;
  9398. end
  9399. end
  9400. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9401. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9402. { Same as above, but also adds or subtracts to %reg2 in between.
  9403. It's still valid as long as the flags aren't in use }
  9404. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9405. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9406. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9407. { be lazy, checking separately for sub would be slightly better }
  9408. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9409. begin
  9410. TransferUsedRegs(TmpUsedRegs);
  9411. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9412. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9413. if TryMovArith2Lea(hp2) then
  9414. begin
  9415. Result := True;
  9416. Exit;
  9417. end;
  9418. end;
  9419. end;
  9420. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9421. {$ifdef x86_64}
  9422. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9423. {$else x86_64}
  9424. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9425. {$endif x86_64}
  9426. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9427. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9428. { mov reg1, reg2 mov reg1, reg2
  9429. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9430. begin
  9431. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9432. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9433. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9434. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9435. TransferUsedRegs(TmpUsedRegs);
  9436. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9437. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9438. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9439. then
  9440. begin
  9441. RemoveCurrentP(p, hp1);
  9442. Result:=true;
  9443. end;
  9444. Exit;
  9445. end;
  9446. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9447. IsXCHGAcceptable and
  9448. { XCHG doesn't support 8-bit registers }
  9449. (taicpu(p).opsize <> S_B) and
  9450. MatchInstruction(hp1, A_MOV, []) and
  9451. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9452. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9453. GetNextInstruction(hp1, hp2) and
  9454. MatchInstruction(hp2, A_MOV, []) and
  9455. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9456. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9457. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9458. begin
  9459. { mov %reg1,%reg2
  9460. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9461. mov %reg2,%reg3
  9462. (%reg2 not used afterwards)
  9463. Note that xchg takes 3 cycles to execute, and generally mov's take
  9464. only one cycle apiece, but the first two mov's can be executed in
  9465. parallel, only taking 2 cycles overall. Older processors should
  9466. therefore only optimise for size. [Kit]
  9467. }
  9468. TransferUsedRegs(TmpUsedRegs);
  9469. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9470. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9471. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9472. begin
  9473. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9474. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9475. taicpu(hp1).opcode := A_XCHG;
  9476. RemoveCurrentP(p, hp1);
  9477. RemoveInstruction(hp2);
  9478. Result := True;
  9479. Exit;
  9480. end;
  9481. end;
  9482. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9483. MatchInstruction(hp1, A_SAR, []) then
  9484. begin
  9485. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9486. begin
  9487. { the use of %edx also covers the opsize being S_L }
  9488. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9489. begin
  9490. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9491. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9492. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9493. begin
  9494. { Change:
  9495. movl %eax,%edx
  9496. sarl $31,%edx
  9497. To:
  9498. cltd
  9499. }
  9500. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9501. RemoveInstruction(hp1);
  9502. taicpu(p).opcode := A_CDQ;
  9503. taicpu(p).opsize := S_NO;
  9504. taicpu(p).clearop(1);
  9505. taicpu(p).clearop(0);
  9506. taicpu(p).ops:=0;
  9507. Result := True;
  9508. Exit;
  9509. end
  9510. else if (cs_opt_size in current_settings.optimizerswitches) and
  9511. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9512. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9513. begin
  9514. { Change:
  9515. movl %edx,%eax
  9516. sarl $31,%edx
  9517. To:
  9518. movl %edx,%eax
  9519. cltd
  9520. Note that this creates a dependency between the two instructions,
  9521. so only perform if optimising for size.
  9522. }
  9523. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9524. taicpu(hp1).opcode := A_CDQ;
  9525. taicpu(hp1).opsize := S_NO;
  9526. taicpu(hp1).clearop(1);
  9527. taicpu(hp1).clearop(0);
  9528. taicpu(hp1).ops:=0;
  9529. Include(OptsToCheck, aoc_ForceNewIteration);
  9530. Exit;
  9531. end;
  9532. {$ifndef x86_64}
  9533. end
  9534. { Don't bother if CMOV is supported, because a more optimal
  9535. sequence would have been generated for the Abs() intrinsic }
  9536. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9537. { the use of %eax also covers the opsize being S_L }
  9538. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9539. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9540. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9541. GetNextInstruction(hp1, hp2) and
  9542. MatchInstruction(hp2, A_XOR, [S_L]) and
  9543. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9544. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9545. GetNextInstruction(hp2, hp3) and
  9546. MatchInstruction(hp3, A_SUB, [S_L]) and
  9547. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9548. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9549. begin
  9550. { Change:
  9551. movl %eax,%edx
  9552. sarl $31,%eax
  9553. xorl %eax,%edx
  9554. subl %eax,%edx
  9555. (Instruction that uses %edx)
  9556. (%eax deallocated)
  9557. (%edx deallocated)
  9558. To:
  9559. cltd
  9560. xorl %edx,%eax <-- Note the registers have swapped
  9561. subl %edx,%eax
  9562. (Instruction that uses %eax) <-- %eax rather than %edx
  9563. }
  9564. TransferUsedRegs(TmpUsedRegs);
  9565. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9566. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9567. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9568. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9569. begin
  9570. if GetNextInstruction(hp3, hp4) and
  9571. not RegModifiedByInstruction(NR_EDX, hp4) and
  9572. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9573. begin
  9574. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9575. taicpu(p).opcode := A_CDQ;
  9576. taicpu(p).clearop(1);
  9577. taicpu(p).clearop(0);
  9578. taicpu(p).ops:=0;
  9579. RemoveInstruction(hp1);
  9580. taicpu(hp2).loadreg(0, NR_EDX);
  9581. taicpu(hp2).loadreg(1, NR_EAX);
  9582. taicpu(hp3).loadreg(0, NR_EDX);
  9583. taicpu(hp3).loadreg(1, NR_EAX);
  9584. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9585. { Convert references in the following instruction (hp4) from %edx to %eax }
  9586. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9587. with taicpu(hp4).oper[OperIdx]^ do
  9588. case typ of
  9589. top_reg:
  9590. if getsupreg(reg) = RS_EDX then
  9591. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9592. top_ref:
  9593. begin
  9594. if getsupreg(reg) = RS_EDX then
  9595. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9596. if getsupreg(reg) = RS_EDX then
  9597. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9598. end;
  9599. else
  9600. ;
  9601. end;
  9602. Result := True;
  9603. Exit;
  9604. end;
  9605. end;
  9606. {$else x86_64}
  9607. end;
  9608. end
  9609. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9610. { the use of %rdx also covers the opsize being S_Q }
  9611. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9612. begin
  9613. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9614. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9615. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9616. begin
  9617. { Change:
  9618. movq %rax,%rdx
  9619. sarq $63,%rdx
  9620. To:
  9621. cqto
  9622. }
  9623. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9624. RemoveInstruction(hp1);
  9625. taicpu(p).opcode := A_CQO;
  9626. taicpu(p).opsize := S_NO;
  9627. taicpu(p).clearop(1);
  9628. taicpu(p).clearop(0);
  9629. taicpu(p).ops:=0;
  9630. Result := True;
  9631. Exit;
  9632. end
  9633. else if (cs_opt_size in current_settings.optimizerswitches) and
  9634. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9635. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9636. begin
  9637. { Change:
  9638. movq %rdx,%rax
  9639. sarq $63,%rdx
  9640. To:
  9641. movq %rdx,%rax
  9642. cqto
  9643. Note that this creates a dependency between the two instructions,
  9644. so only perform if optimising for size.
  9645. }
  9646. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9647. taicpu(hp1).opcode := A_CQO;
  9648. taicpu(hp1).opsize := S_NO;
  9649. taicpu(hp1).clearop(1);
  9650. taicpu(hp1).clearop(0);
  9651. taicpu(hp1).ops:=0;
  9652. Include(OptsToCheck, aoc_ForceNewIteration);
  9653. Exit;
  9654. {$endif x86_64}
  9655. end;
  9656. end;
  9657. end;
  9658. if MatchInstruction(hp1, A_MOV, []) and
  9659. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9660. { Though "GetNextInstruction" could be factored out, along with
  9661. the instructions that depend on hp2, it is an expensive call that
  9662. should be delayed for as long as possible, hence we do cheaper
  9663. checks first that are likely to be False. [Kit] }
  9664. begin
  9665. if (
  9666. (
  9667. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9668. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9669. (
  9670. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9671. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9672. )
  9673. ) or
  9674. (
  9675. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9676. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9677. (
  9678. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9679. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9680. )
  9681. )
  9682. ) and
  9683. GetNextInstruction(hp1, hp2) and
  9684. MatchInstruction(hp2, A_SAR, []) and
  9685. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9686. begin
  9687. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9688. begin
  9689. { Change:
  9690. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9691. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9692. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9693. To:
  9694. movl r/m,%eax <- Note the change in register
  9695. cltd
  9696. }
  9697. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9698. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9699. taicpu(p).loadreg(1, NR_EAX);
  9700. taicpu(hp1).opcode := A_CDQ;
  9701. taicpu(hp1).clearop(1);
  9702. taicpu(hp1).clearop(0);
  9703. taicpu(hp1).ops:=0;
  9704. RemoveInstruction(hp2);
  9705. Include(OptsToCheck, aoc_ForceNewIteration);
  9706. (*
  9707. {$ifdef x86_64}
  9708. end
  9709. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9710. { This code sequence does not get generated - however it might become useful
  9711. if and when 128-bit signed integer types make an appearance, so the code
  9712. is kept here for when it is eventually needed. [Kit] }
  9713. (
  9714. (
  9715. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9716. (
  9717. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9718. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9719. )
  9720. ) or
  9721. (
  9722. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9723. (
  9724. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9725. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9726. )
  9727. )
  9728. ) and
  9729. GetNextInstruction(hp1, hp2) and
  9730. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9731. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9732. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9733. begin
  9734. { Change:
  9735. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9736. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9737. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9738. To:
  9739. movq r/m,%rax <- Note the change in register
  9740. cqto
  9741. }
  9742. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9743. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9744. taicpu(p).loadreg(1, NR_RAX);
  9745. taicpu(hp1).opcode := A_CQO;
  9746. taicpu(hp1).clearop(1);
  9747. taicpu(hp1).clearop(0);
  9748. taicpu(hp1).ops:=0;
  9749. RemoveInstruction(hp2);
  9750. Include(OptsToCheck, aoc_ForceNewIteration);
  9751. {$endif x86_64}
  9752. *)
  9753. end;
  9754. end;
  9755. {$ifdef x86_64}
  9756. end;
  9757. if (taicpu(p).opsize = S_L) and
  9758. (taicpu(p).oper[1]^.typ = top_reg) and
  9759. (
  9760. MatchInstruction(hp1, A_MOV,[]) and
  9761. (taicpu(hp1).opsize = S_L) and
  9762. (taicpu(hp1).oper[1]^.typ = top_reg)
  9763. ) and (
  9764. GetNextInstruction(hp1, hp2) and
  9765. (tai(hp2).typ=ait_instruction) and
  9766. (taicpu(hp2).opsize = S_Q) and
  9767. (
  9768. (
  9769. MatchInstruction(hp2, A_ADD,[]) and
  9770. (taicpu(hp2).opsize = S_Q) and
  9771. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9772. (
  9773. (
  9774. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9775. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9776. ) or (
  9777. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9778. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9779. )
  9780. )
  9781. ) or (
  9782. MatchInstruction(hp2, A_LEA,[]) and
  9783. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9784. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9785. (
  9786. (
  9787. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9788. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9789. ) or (
  9790. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9791. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9792. )
  9793. ) and (
  9794. (
  9795. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9796. ) or (
  9797. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9798. )
  9799. )
  9800. )
  9801. )
  9802. ) and (
  9803. GetNextInstruction(hp2, hp3) and
  9804. MatchInstruction(hp3, A_SHR,[]) and
  9805. (taicpu(hp3).opsize = S_Q) and
  9806. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9807. (taicpu(hp3).oper[0]^.val = 1) and
  9808. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9809. ) then
  9810. begin
  9811. { Change movl x, reg1d movl x, reg1d
  9812. movl y, reg2d movl y, reg2d
  9813. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9814. shrq $1, reg1q shrq $1, reg1q
  9815. ( reg1d and reg2d can be switched around in the first two instructions )
  9816. To movl x, reg1d
  9817. addl y, reg1d
  9818. rcrl $1, reg1d
  9819. This corresponds to the common expression (x + y) shr 1, where
  9820. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9821. smaller code, but won't account for x + y causing an overflow). [Kit]
  9822. }
  9823. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9824. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9825. begin
  9826. { Change first MOV command to have the same register as the final output }
  9827. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9828. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  9829. Result := True;
  9830. end
  9831. else
  9832. begin
  9833. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9834. Include(OptsToCheck, aoc_ForceNewIteration);
  9835. end;
  9836. { Change second MOV command to an ADD command. This is easier than
  9837. converting the existing command because it means we don't have to
  9838. touch 'y', which might be a complicated reference, and also the
  9839. fact that the third command might either be ADD or LEA. [Kit] }
  9840. taicpu(hp1).opcode := A_ADD;
  9841. { Delete old ADD/LEA instruction }
  9842. RemoveInstruction(hp2);
  9843. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9844. taicpu(hp3).opcode := A_RCR;
  9845. taicpu(hp3).changeopsize(S_L);
  9846. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9847. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  9848. called, so FuncMov2Func below is safe to call }
  9849. {$endif x86_64}
  9850. end;
  9851. if FuncMov2Func(p, hp1) then
  9852. begin
  9853. Result := True;
  9854. Exit;
  9855. end;
  9856. end;
  9857. {$push}
  9858. {$q-}{$r-}
  9859. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9860. var
  9861. ThisReg: TRegister;
  9862. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9863. TargetSubReg: TSubRegister;
  9864. hp1, hp2: tai;
  9865. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9866. { Store list of found instructions so we don't have to call
  9867. GetNextInstructionUsingReg multiple times }
  9868. InstrList: array of taicpu;
  9869. InstrMax, Index: Integer;
  9870. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9871. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9872. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9873. WorkingValue: TCgInt;
  9874. PreMessage: string;
  9875. { Data flow analysis }
  9876. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9877. BitwiseOnly, OrXorUsed,
  9878. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9879. function CheckOverflowConditions: Boolean;
  9880. begin
  9881. Result := True;
  9882. if (TestValSignedMax > SignedUpperLimit) then
  9883. UpperSignedOverflow := True;
  9884. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9885. LowerSignedOverflow := True;
  9886. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9887. LowerUnsignedOverflow := True;
  9888. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9889. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9890. begin
  9891. { Absolute overflow }
  9892. Result := False;
  9893. Exit;
  9894. end;
  9895. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9896. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9897. ShiftDownOverflow := True;
  9898. if (TestValMin < 0) or (TestValMax < 0) then
  9899. begin
  9900. LowerUnsignedOverflow := True;
  9901. UpperUnsignedOverflow := True;
  9902. end;
  9903. end;
  9904. function AdjustInitialLoadAndSize: Boolean;
  9905. begin
  9906. Result := False;
  9907. if not p_removed then
  9908. begin
  9909. if TargetSize = MinSize then
  9910. begin
  9911. { Convert the input MOVZX to a MOV }
  9912. if (taicpu(p).oper[0]^.typ = top_reg) and
  9913. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9914. begin
  9915. { Or remove it completely! }
  9916. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9917. RemoveCurrentP(p);
  9918. p_removed := True;
  9919. end
  9920. else
  9921. begin
  9922. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9923. taicpu(p).opcode := A_MOV;
  9924. taicpu(p).oper[1]^.reg := ThisReg;
  9925. taicpu(p).opsize := TargetSize;
  9926. end;
  9927. Result := True;
  9928. end
  9929. else if TargetSize <> MaxSize then
  9930. begin
  9931. case MaxSize of
  9932. S_L:
  9933. if TargetSize = S_W then
  9934. begin
  9935. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9936. taicpu(p).opsize := S_BW;
  9937. taicpu(p).oper[1]^.reg := ThisReg;
  9938. Result := True;
  9939. end
  9940. else
  9941. InternalError(2020112341);
  9942. S_W:
  9943. if TargetSize = S_L then
  9944. begin
  9945. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9946. taicpu(p).opsize := S_BL;
  9947. taicpu(p).oper[1]^.reg := ThisReg;
  9948. Result := True;
  9949. end
  9950. else
  9951. InternalError(2020112342);
  9952. else
  9953. ;
  9954. end;
  9955. end
  9956. else if not hp1_removed and not RegInUse then
  9957. begin
  9958. { If we have something like:
  9959. movzbl (oper),%regd
  9960. add x, %regd
  9961. movzbl %regb, %regd
  9962. We can reduce the register size to the input of the final
  9963. movzbl instruction. Overflows won't have any effect.
  9964. }
  9965. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9966. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9967. begin
  9968. TargetSize := S_B;
  9969. setsubreg(ThisReg, R_SUBL);
  9970. Result := True;
  9971. end
  9972. else if (taicpu(p).opsize = S_WL) and
  9973. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9974. begin
  9975. TargetSize := S_W;
  9976. setsubreg(ThisReg, R_SUBW);
  9977. Result := True;
  9978. end;
  9979. if Result then
  9980. begin
  9981. { Convert the input MOVZX to a MOV }
  9982. if (taicpu(p).oper[0]^.typ = top_reg) and
  9983. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9984. begin
  9985. { Or remove it completely! }
  9986. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9987. RemoveCurrentP(p);
  9988. p_removed := True;
  9989. end
  9990. else
  9991. begin
  9992. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9993. taicpu(p).opcode := A_MOV;
  9994. taicpu(p).oper[1]^.reg := ThisReg;
  9995. taicpu(p).opsize := TargetSize;
  9996. end;
  9997. end;
  9998. end;
  9999. end;
  10000. end;
  10001. procedure AdjustFinalLoad;
  10002. begin
  10003. if not LowerUnsignedOverflow then
  10004. begin
  10005. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  10006. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  10007. begin
  10008. { Convert the output MOVZX to a MOV }
  10009. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10010. begin
  10011. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  10012. if (MinSize = S_B) or
  10013. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  10014. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  10015. begin
  10016. { Remove it completely! }
  10017. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  10018. { Be careful; if p = hp1 and p was also removed, p
  10019. will become a dangling pointer }
  10020. if p = hp1 then
  10021. begin
  10022. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10023. p_removed := True;
  10024. end
  10025. else
  10026. RemoveInstruction(hp1);
  10027. hp1_removed := True;
  10028. end;
  10029. end
  10030. else
  10031. begin
  10032. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10033. taicpu(hp1).opcode := A_MOV;
  10034. taicpu(hp1).oper[0]^.reg := ThisReg;
  10035. taicpu(hp1).opsize := TargetSize;
  10036. end;
  10037. end
  10038. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10039. begin
  10040. { Need to change the size of the output }
  10041. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10042. taicpu(hp1).oper[0]^.reg := ThisReg;
  10043. taicpu(hp1).opsize := S_BL;
  10044. end;
  10045. end;
  10046. end;
  10047. function CompressInstructions: Boolean;
  10048. var
  10049. LocalIndex: Integer;
  10050. begin
  10051. Result := False;
  10052. { The objective here is to try to find a combination that
  10053. removes one of the MOV/Z instructions. }
  10054. if (
  10055. (taicpu(p).oper[0]^.typ <> top_reg) or
  10056. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10057. ) and
  10058. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10059. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10060. begin
  10061. { Make a preference to remove the second MOVZX instruction }
  10062. case taicpu(hp1).opsize of
  10063. S_BL, S_WL:
  10064. begin
  10065. TargetSize := S_L;
  10066. TargetSubReg := R_SUBD;
  10067. end;
  10068. S_BW:
  10069. begin
  10070. TargetSize := S_W;
  10071. TargetSubReg := R_SUBW;
  10072. end;
  10073. else
  10074. InternalError(2020112302);
  10075. end;
  10076. end
  10077. else
  10078. begin
  10079. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10080. begin
  10081. { Exceeded lower bound but not upper bound }
  10082. TargetSize := MaxSize;
  10083. end
  10084. else if not LowerUnsignedOverflow then
  10085. begin
  10086. { Size didn't exceed lower bound }
  10087. TargetSize := MinSize;
  10088. end
  10089. else
  10090. Exit;
  10091. end;
  10092. case TargetSize of
  10093. S_B:
  10094. TargetSubReg := R_SUBL;
  10095. S_W:
  10096. TargetSubReg := R_SUBW;
  10097. S_L:
  10098. TargetSubReg := R_SUBD;
  10099. else
  10100. InternalError(2020112350);
  10101. end;
  10102. { Update the register to its new size }
  10103. setsubreg(ThisReg, TargetSubReg);
  10104. RegInUse := False;
  10105. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10106. begin
  10107. { Check to see if the active register is used afterwards;
  10108. if not, we can change it and make a saving. }
  10109. TransferUsedRegs(TmpUsedRegs);
  10110. { The target register may be marked as in use to cross
  10111. a jump to a distant label, so exclude it }
  10112. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10113. hp2 := p;
  10114. repeat
  10115. { Explicitly check for the excluded register (don't include the first
  10116. instruction as it may be reading from here }
  10117. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10118. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10119. begin
  10120. RegInUse := True;
  10121. Break;
  10122. end;
  10123. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10124. if not GetNextInstruction(hp2, hp2) then
  10125. InternalError(2020112340);
  10126. until (hp2 = hp1);
  10127. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10128. { We might still be able to get away with this }
  10129. RegInUse := not
  10130. (
  10131. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10132. (hp2.typ = ait_instruction) and
  10133. (
  10134. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10135. instruction that doesn't actually contain ThisReg }
  10136. (cs_opt_level3 in current_settings.optimizerswitches) or
  10137. RegInInstruction(ThisReg, hp2)
  10138. ) and
  10139. RegLoadedWithNewValue(ThisReg, hp2)
  10140. );
  10141. if not RegInUse then
  10142. begin
  10143. { Force the register size to the same as this instruction so it can be removed}
  10144. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10145. begin
  10146. TargetSize := S_L;
  10147. TargetSubReg := R_SUBD;
  10148. end
  10149. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10150. begin
  10151. TargetSize := S_W;
  10152. TargetSubReg := R_SUBW;
  10153. end;
  10154. ThisReg := taicpu(hp1).oper[1]^.reg;
  10155. setsubreg(ThisReg, TargetSubReg);
  10156. RegChanged := True;
  10157. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10158. TransferUsedRegs(TmpUsedRegs);
  10159. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10160. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10161. if p = hp1 then
  10162. begin
  10163. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10164. p_removed := True;
  10165. end
  10166. else
  10167. RemoveInstruction(hp1);
  10168. hp1_removed := True;
  10169. { Instruction will become "mov %reg,%reg" }
  10170. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10171. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10172. begin
  10173. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10174. RemoveCurrentP(p);
  10175. p_removed := True;
  10176. end
  10177. else
  10178. taicpu(p).oper[1]^.reg := ThisReg;
  10179. Result := True;
  10180. end
  10181. else
  10182. begin
  10183. if TargetSize <> MaxSize then
  10184. begin
  10185. { Since the register is in use, we have to force it to
  10186. MaxSize otherwise part of it may become undefined later on }
  10187. TargetSize := MaxSize;
  10188. case TargetSize of
  10189. S_B:
  10190. TargetSubReg := R_SUBL;
  10191. S_W:
  10192. TargetSubReg := R_SUBW;
  10193. S_L:
  10194. TargetSubReg := R_SUBD;
  10195. else
  10196. InternalError(2020112351);
  10197. end;
  10198. setsubreg(ThisReg, TargetSubReg);
  10199. end;
  10200. AdjustFinalLoad;
  10201. end;
  10202. end
  10203. else
  10204. AdjustFinalLoad;
  10205. Result := AdjustInitialLoadAndSize or Result;
  10206. { Now go through every instruction we found and change the
  10207. size. If TargetSize = MaxSize, then almost no changes are
  10208. needed and Result can remain False if it hasn't been set
  10209. yet.
  10210. If RegChanged is True, then the register requires changing
  10211. and so the point about TargetSize = MaxSize doesn't apply. }
  10212. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10213. begin
  10214. for LocalIndex := 0 to InstrMax do
  10215. begin
  10216. { If p_removed is true, then the original MOV/Z was removed
  10217. and removing the AND instruction may not be safe if it
  10218. appears first }
  10219. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10220. InternalError(2020112310);
  10221. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10222. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10223. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10224. InstrList[LocalIndex].opsize := TargetSize;
  10225. end;
  10226. Result := True;
  10227. end;
  10228. end;
  10229. begin
  10230. Result := False;
  10231. p_removed := False;
  10232. hp1_removed := False;
  10233. ThisReg := taicpu(p).oper[1]^.reg;
  10234. { Check for:
  10235. movs/z ###,%ecx (or %cx or %rcx)
  10236. ...
  10237. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10238. (dealloc %ecx)
  10239. Change to:
  10240. mov ###,%cl (if ### = %cl, then remove completely)
  10241. ...
  10242. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10243. }
  10244. if (getsupreg(ThisReg) = RS_ECX) and
  10245. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10246. (hp1.typ = ait_instruction) and
  10247. (
  10248. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10249. instruction that doesn't actually contain ECX }
  10250. (cs_opt_level3 in current_settings.optimizerswitches) or
  10251. RegInInstruction(NR_ECX, hp1) or
  10252. (
  10253. { It's common for the shift/rotate's read/write register to be
  10254. initialised in between, so under -O2 and under, search ahead
  10255. one more instruction
  10256. }
  10257. GetNextInstruction(hp1, hp1) and
  10258. (hp1.typ = ait_instruction) and
  10259. RegInInstruction(NR_ECX, hp1)
  10260. )
  10261. ) and
  10262. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10263. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10264. begin
  10265. TransferUsedRegs(TmpUsedRegs);
  10266. hp2 := p;
  10267. repeat
  10268. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10269. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10270. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10271. begin
  10272. case taicpu(p).opsize of
  10273. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10274. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10275. begin
  10276. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10277. RemoveCurrentP(p);
  10278. end
  10279. else
  10280. begin
  10281. taicpu(p).opcode := A_MOV;
  10282. taicpu(p).opsize := S_B;
  10283. taicpu(p).oper[1]^.reg := NR_CL;
  10284. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10285. end;
  10286. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10287. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10288. begin
  10289. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10290. RemoveCurrentP(p);
  10291. end
  10292. else
  10293. begin
  10294. taicpu(p).opcode := A_MOV;
  10295. taicpu(p).opsize := S_W;
  10296. taicpu(p).oper[1]^.reg := NR_CX;
  10297. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10298. end;
  10299. {$ifdef x86_64}
  10300. S_LQ:
  10301. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10302. begin
  10303. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10304. RemoveCurrentP(p);
  10305. end
  10306. else
  10307. begin
  10308. taicpu(p).opcode := A_MOV;
  10309. taicpu(p).opsize := S_L;
  10310. taicpu(p).oper[1]^.reg := NR_ECX;
  10311. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10312. end;
  10313. {$endif x86_64}
  10314. else
  10315. InternalError(2021120401);
  10316. end;
  10317. Result := True;
  10318. Exit;
  10319. end;
  10320. end;
  10321. { This is anything but quick! }
  10322. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10323. Exit;
  10324. SetLength(InstrList, 0);
  10325. InstrMax := -1;
  10326. case taicpu(p).opsize of
  10327. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10328. begin
  10329. {$if defined(i386) or defined(i8086)}
  10330. { If the target size is 8-bit, make sure we can actually encode it }
  10331. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10332. Exit;
  10333. {$endif i386 or i8086}
  10334. LowerLimit := $FF;
  10335. SignedLowerLimit := $7F;
  10336. SignedLowerLimitBottom := -128;
  10337. MinSize := S_B;
  10338. if taicpu(p).opsize = S_BW then
  10339. begin
  10340. MaxSize := S_W;
  10341. UpperLimit := $FFFF;
  10342. SignedUpperLimit := $7FFF;
  10343. SignedUpperLimitBottom := -32768;
  10344. end
  10345. else
  10346. begin
  10347. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10348. MaxSize := S_L;
  10349. UpperLimit := $FFFFFFFF;
  10350. SignedUpperLimit := $7FFFFFFF;
  10351. SignedUpperLimitBottom := -2147483648;
  10352. end;
  10353. end;
  10354. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10355. begin
  10356. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10357. LowerLimit := $FFFF;
  10358. SignedLowerLimit := $7FFF;
  10359. SignedLowerLimitBottom := -32768;
  10360. UpperLimit := $FFFFFFFF;
  10361. SignedUpperLimit := $7FFFFFFF;
  10362. SignedUpperLimitBottom := -2147483648;
  10363. MinSize := S_W;
  10364. MaxSize := S_L;
  10365. end;
  10366. {$ifdef x86_64}
  10367. S_LQ:
  10368. begin
  10369. { Both the lower and upper limits are set to 32-bit. If a limit
  10370. is breached, then optimisation is impossible }
  10371. LowerLimit := $FFFFFFFF;
  10372. SignedLowerLimit := $7FFFFFFF;
  10373. SignedLowerLimitBottom := -2147483648;
  10374. UpperLimit := $FFFFFFFF;
  10375. SignedUpperLimit := $7FFFFFFF;
  10376. SignedUpperLimitBottom := -2147483648;
  10377. MinSize := S_L;
  10378. MaxSize := S_L;
  10379. end;
  10380. {$endif x86_64}
  10381. else
  10382. InternalError(2020112301);
  10383. end;
  10384. TestValMin := 0;
  10385. TestValMax := LowerLimit;
  10386. TestValSignedMax := SignedLowerLimit;
  10387. TryShiftDownLimit := LowerLimit;
  10388. TryShiftDown := S_NO;
  10389. ShiftDownOverflow := False;
  10390. RegChanged := False;
  10391. BitwiseOnly := True;
  10392. OrXorUsed := False;
  10393. UpperSignedOverflow := False;
  10394. LowerSignedOverflow := False;
  10395. UpperUnsignedOverflow := False;
  10396. LowerUnsignedOverflow := False;
  10397. hp1 := p;
  10398. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10399. (hp1.typ = ait_instruction) and
  10400. (
  10401. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10402. instruction that doesn't actually contain ThisReg }
  10403. (cs_opt_level3 in current_settings.optimizerswitches) or
  10404. { This allows this Movx optimisation to work through the SETcc instructions
  10405. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10406. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10407. skip over these SETcc instructions). }
  10408. (taicpu(hp1).opcode = A_SETcc) or
  10409. RegInInstruction(ThisReg, hp1)
  10410. ) do
  10411. begin
  10412. case taicpu(hp1).opcode of
  10413. A_INC,A_DEC:
  10414. begin
  10415. { Has to be an exact match on the register }
  10416. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10417. Break;
  10418. if taicpu(hp1).opcode = A_INC then
  10419. begin
  10420. Inc(TestValMin);
  10421. Inc(TestValMax);
  10422. Inc(TestValSignedMax);
  10423. end
  10424. else
  10425. begin
  10426. Dec(TestValMin);
  10427. Dec(TestValMax);
  10428. Dec(TestValSignedMax);
  10429. end;
  10430. end;
  10431. A_TEST, A_CMP:
  10432. begin
  10433. if (
  10434. { Too high a risk of non-linear behaviour that breaks DFA
  10435. here, unless it's cmp $0,%reg, which is equivalent to
  10436. test %reg,%reg }
  10437. OrXorUsed and
  10438. (taicpu(hp1).opcode = A_CMP) and
  10439. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10440. ) or
  10441. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10442. { Has to be an exact match on the register }
  10443. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10444. (
  10445. { Permit "test %reg,%reg" }
  10446. (taicpu(hp1).opcode = A_TEST) and
  10447. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10448. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10449. ) or
  10450. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10451. { Make sure the comparison value is not smaller than the
  10452. smallest allowed signed value for the minimum size (e.g.
  10453. -128 for 8-bit) }
  10454. not (
  10455. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10456. { Is it in the negative range? }
  10457. (
  10458. (taicpu(hp1).oper[0]^.val < 0) and
  10459. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10460. )
  10461. ) then
  10462. Break;
  10463. { Check to see if the active register is used afterwards }
  10464. TransferUsedRegs(TmpUsedRegs);
  10465. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10466. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10467. begin
  10468. { Make sure the comparison or any previous instructions
  10469. hasn't pushed the test values outside of the range of
  10470. MinSize }
  10471. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10472. begin
  10473. { Exceeded lower bound but not upper bound }
  10474. Exit;
  10475. end
  10476. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10477. begin
  10478. { Size didn't exceed lower bound }
  10479. TargetSize := MinSize;
  10480. end
  10481. else
  10482. Break;
  10483. case TargetSize of
  10484. S_B:
  10485. TargetSubReg := R_SUBL;
  10486. S_W:
  10487. TargetSubReg := R_SUBW;
  10488. S_L:
  10489. TargetSubReg := R_SUBD;
  10490. else
  10491. InternalError(2021051002);
  10492. end;
  10493. if TargetSize <> MaxSize then
  10494. begin
  10495. { Update the register to its new size }
  10496. setsubreg(ThisReg, TargetSubReg);
  10497. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10498. taicpu(hp1).oper[1]^.reg := ThisReg;
  10499. taicpu(hp1).opsize := TargetSize;
  10500. { Convert the input MOVZX to a MOV if necessary }
  10501. AdjustInitialLoadAndSize;
  10502. if (InstrMax >= 0) then
  10503. begin
  10504. for Index := 0 to InstrMax do
  10505. begin
  10506. { If p_removed is true, then the original MOV/Z was removed
  10507. and removing the AND instruction may not be safe if it
  10508. appears first }
  10509. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10510. InternalError(2020112311);
  10511. if InstrList[Index].oper[0]^.typ = top_reg then
  10512. InstrList[Index].oper[0]^.reg := ThisReg;
  10513. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10514. InstrList[Index].opsize := MinSize;
  10515. end;
  10516. end;
  10517. Result := True;
  10518. end;
  10519. Exit;
  10520. end;
  10521. end;
  10522. A_SETcc:
  10523. begin
  10524. { This allows this Movx optimisation to work through the SETcc instructions
  10525. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10526. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10527. skip over these SETcc instructions). }
  10528. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10529. { Of course, break out if the current register is used }
  10530. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10531. Break
  10532. else
  10533. { We must use Continue so the instruction doesn't get added
  10534. to InstrList }
  10535. Continue;
  10536. end;
  10537. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10538. begin
  10539. if
  10540. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10541. { Has to be an exact match on the register }
  10542. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10543. (
  10544. (
  10545. (taicpu(hp1).oper[0]^.typ = top_const) and
  10546. (
  10547. (
  10548. (taicpu(hp1).opcode = A_SHL) and
  10549. (
  10550. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10551. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10552. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10553. )
  10554. ) or (
  10555. (taicpu(hp1).opcode <> A_SHL) and
  10556. (
  10557. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10558. { Is it in the negative range? }
  10559. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10560. )
  10561. )
  10562. )
  10563. ) or (
  10564. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10565. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10566. )
  10567. ) then
  10568. Break;
  10569. { Only process OR and XOR if there are only bitwise operations,
  10570. since otherwise they can too easily fool the data flow
  10571. analysis (they can cause non-linear behaviour) }
  10572. case taicpu(hp1).opcode of
  10573. A_ADD:
  10574. begin
  10575. if OrXorUsed then
  10576. { Too high a risk of non-linear behaviour that breaks DFA here }
  10577. Break
  10578. else
  10579. BitwiseOnly := False;
  10580. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10581. begin
  10582. TestValMin := TestValMin * 2;
  10583. TestValMax := TestValMax * 2;
  10584. TestValSignedMax := TestValSignedMax * 2;
  10585. end
  10586. else
  10587. begin
  10588. WorkingValue := taicpu(hp1).oper[0]^.val;
  10589. TestValMin := TestValMin + WorkingValue;
  10590. TestValMax := TestValMax + WorkingValue;
  10591. TestValSignedMax := TestValSignedMax + WorkingValue;
  10592. end;
  10593. end;
  10594. A_SUB:
  10595. begin
  10596. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10597. begin
  10598. TestValMin := 0;
  10599. TestValMax := 0;
  10600. TestValSignedMax := 0;
  10601. end
  10602. else
  10603. begin
  10604. if OrXorUsed then
  10605. { Too high a risk of non-linear behaviour that breaks DFA here }
  10606. Break
  10607. else
  10608. BitwiseOnly := False;
  10609. WorkingValue := taicpu(hp1).oper[0]^.val;
  10610. TestValMin := TestValMin - WorkingValue;
  10611. TestValMax := TestValMax - WorkingValue;
  10612. TestValSignedMax := TestValSignedMax - WorkingValue;
  10613. end;
  10614. end;
  10615. A_AND:
  10616. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10617. begin
  10618. { we might be able to go smaller if AND appears first }
  10619. if InstrMax = -1 then
  10620. case MinSize of
  10621. S_B:
  10622. ;
  10623. S_W:
  10624. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10625. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10626. begin
  10627. TryShiftDown := S_B;
  10628. TryShiftDownLimit := $FF;
  10629. end;
  10630. S_L:
  10631. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10632. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10633. begin
  10634. TryShiftDown := S_B;
  10635. TryShiftDownLimit := $FF;
  10636. end
  10637. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10638. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10639. begin
  10640. TryShiftDown := S_W;
  10641. TryShiftDownLimit := $FFFF;
  10642. end;
  10643. else
  10644. InternalError(2020112320);
  10645. end;
  10646. WorkingValue := taicpu(hp1).oper[0]^.val;
  10647. TestValMin := TestValMin and WorkingValue;
  10648. TestValMax := TestValMax and WorkingValue;
  10649. TestValSignedMax := TestValSignedMax and WorkingValue;
  10650. end;
  10651. A_OR:
  10652. begin
  10653. if not BitwiseOnly then
  10654. Break;
  10655. OrXorUsed := True;
  10656. WorkingValue := taicpu(hp1).oper[0]^.val;
  10657. TestValMin := TestValMin or WorkingValue;
  10658. TestValMax := TestValMax or WorkingValue;
  10659. TestValSignedMax := TestValSignedMax or WorkingValue;
  10660. end;
  10661. A_XOR:
  10662. begin
  10663. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10664. begin
  10665. TestValMin := 0;
  10666. TestValMax := 0;
  10667. TestValSignedMax := 0;
  10668. end
  10669. else
  10670. begin
  10671. if not BitwiseOnly then
  10672. Break;
  10673. OrXorUsed := True;
  10674. WorkingValue := taicpu(hp1).oper[0]^.val;
  10675. TestValMin := TestValMin xor WorkingValue;
  10676. TestValMax := TestValMax xor WorkingValue;
  10677. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10678. end;
  10679. end;
  10680. A_SHL:
  10681. begin
  10682. BitwiseOnly := False;
  10683. WorkingValue := taicpu(hp1).oper[0]^.val;
  10684. TestValMin := TestValMin shl WorkingValue;
  10685. TestValMax := TestValMax shl WorkingValue;
  10686. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10687. end;
  10688. A_SHR,
  10689. { The first instruction was MOVZX, so the value won't be negative }
  10690. A_SAR:
  10691. begin
  10692. if InstrMax <> -1 then
  10693. BitwiseOnly := False
  10694. else
  10695. { we might be able to go smaller if SHR appears first }
  10696. case MinSize of
  10697. S_B:
  10698. ;
  10699. S_W:
  10700. if (taicpu(hp1).oper[0]^.val >= 8) then
  10701. begin
  10702. TryShiftDown := S_B;
  10703. TryShiftDownLimit := $FF;
  10704. TryShiftDownSignedLimit := $7F;
  10705. TryShiftDownSignedLimitLower := -128;
  10706. end;
  10707. S_L:
  10708. if (taicpu(hp1).oper[0]^.val >= 24) then
  10709. begin
  10710. TryShiftDown := S_B;
  10711. TryShiftDownLimit := $FF;
  10712. TryShiftDownSignedLimit := $7F;
  10713. TryShiftDownSignedLimitLower := -128;
  10714. end
  10715. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10716. begin
  10717. TryShiftDown := S_W;
  10718. TryShiftDownLimit := $FFFF;
  10719. TryShiftDownSignedLimit := $7FFF;
  10720. TryShiftDownSignedLimitLower := -32768;
  10721. end;
  10722. else
  10723. InternalError(2020112321);
  10724. end;
  10725. WorkingValue := taicpu(hp1).oper[0]^.val;
  10726. if taicpu(hp1).opcode = A_SAR then
  10727. begin
  10728. TestValMin := SarInt64(TestValMin, WorkingValue);
  10729. TestValMax := SarInt64(TestValMax, WorkingValue);
  10730. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10731. end
  10732. else
  10733. begin
  10734. TestValMin := TestValMin shr WorkingValue;
  10735. TestValMax := TestValMax shr WorkingValue;
  10736. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10737. end;
  10738. end;
  10739. else
  10740. InternalError(2020112303);
  10741. end;
  10742. end;
  10743. (*
  10744. A_IMUL:
  10745. case taicpu(hp1).ops of
  10746. 2:
  10747. begin
  10748. if not MatchOpType(hp1, top_reg, top_reg) or
  10749. { Has to be an exact match on the register }
  10750. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10751. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10752. Break;
  10753. TestValMin := TestValMin * TestValMin;
  10754. TestValMax := TestValMax * TestValMax;
  10755. TestValSignedMax := TestValSignedMax * TestValMax;
  10756. end;
  10757. 3:
  10758. begin
  10759. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10760. { Has to be an exact match on the register }
  10761. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10762. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10763. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10764. { Is it in the negative range? }
  10765. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10766. Break;
  10767. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10768. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10769. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10770. end;
  10771. else
  10772. Break;
  10773. end;
  10774. A_IDIV:
  10775. case taicpu(hp1).ops of
  10776. 3:
  10777. begin
  10778. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10779. { Has to be an exact match on the register }
  10780. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10781. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10782. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10783. { Is it in the negative range? }
  10784. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10785. Break;
  10786. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10787. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10788. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10789. end;
  10790. else
  10791. Break;
  10792. end;
  10793. *)
  10794. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10795. begin
  10796. { If there are no instructions in between, then we might be able to make a saving }
  10797. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10798. Break;
  10799. { We have something like:
  10800. movzbw %dl,%dx
  10801. ...
  10802. movswl %dx,%edx
  10803. Change the latter to a zero-extension then enter the
  10804. A_MOVZX case branch.
  10805. }
  10806. {$ifdef x86_64}
  10807. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10808. begin
  10809. { this becomes a zero extension from 32-bit to 64-bit, but
  10810. the upper 32 bits are already zero, so just delete the
  10811. instruction }
  10812. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10813. RemoveInstruction(hp1);
  10814. Result := True;
  10815. Exit;
  10816. end
  10817. else
  10818. {$endif x86_64}
  10819. begin
  10820. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10821. taicpu(hp1).opcode := A_MOVZX;
  10822. {$ifdef x86_64}
  10823. case taicpu(hp1).opsize of
  10824. S_BQ:
  10825. begin
  10826. taicpu(hp1).opsize := S_BL;
  10827. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10828. end;
  10829. S_WQ:
  10830. begin
  10831. taicpu(hp1).opsize := S_WL;
  10832. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10833. end;
  10834. S_LQ:
  10835. begin
  10836. taicpu(hp1).opcode := A_MOV;
  10837. taicpu(hp1).opsize := S_L;
  10838. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10839. { In this instance, we need to break out because the
  10840. instruction is no longer MOVZX or MOVSXD }
  10841. Result := True;
  10842. Exit;
  10843. end;
  10844. else
  10845. ;
  10846. end;
  10847. {$endif x86_64}
  10848. Result := CompressInstructions;
  10849. Exit;
  10850. end;
  10851. end;
  10852. A_MOVZX:
  10853. begin
  10854. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10855. Break;
  10856. if (InstrMax = -1) then
  10857. begin
  10858. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10859. begin
  10860. { Optimise around i40003 }
  10861. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10862. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10863. {$ifndef x86_64}
  10864. and (
  10865. (taicpu(p).oper[0]^.typ <> top_reg) or
  10866. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10867. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10868. )
  10869. {$endif not x86_64}
  10870. then
  10871. begin
  10872. if (taicpu(p).oper[0]^.typ = top_reg) then
  10873. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10874. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10875. taicpu(p).opsize := S_BL;
  10876. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10877. RemoveInstruction(hp1);
  10878. Result := True;
  10879. Exit;
  10880. end;
  10881. end
  10882. else
  10883. begin
  10884. { Will return false if the second parameter isn't ThisReg
  10885. (can happen on -O2 and under) }
  10886. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10887. begin
  10888. { The two MOVZX instructions are adjacent, so remove the first one }
  10889. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10890. RemoveCurrentP(p);
  10891. Result := True;
  10892. Exit;
  10893. end;
  10894. Break;
  10895. end;
  10896. end;
  10897. Result := CompressInstructions;
  10898. Exit;
  10899. end;
  10900. else
  10901. { This includes ADC, SBB and IDIV }
  10902. Break;
  10903. end;
  10904. if not CheckOverflowConditions then
  10905. Break;
  10906. { Contains highest index (so instruction count - 1) }
  10907. Inc(InstrMax);
  10908. if InstrMax > High(InstrList) then
  10909. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10910. InstrList[InstrMax] := taicpu(hp1);
  10911. end;
  10912. end;
  10913. {$pop}
  10914. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10915. var
  10916. hp1 : tai;
  10917. begin
  10918. Result:=false;
  10919. if (taicpu(p).ops >= 2) and
  10920. ((taicpu(p).oper[0]^.typ = top_const) or
  10921. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10922. (taicpu(p).oper[1]^.typ = top_reg) and
  10923. ((taicpu(p).ops = 2) or
  10924. ((taicpu(p).oper[2]^.typ = top_reg) and
  10925. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10926. GetLastInstruction(p,hp1) and
  10927. MatchInstruction(hp1,A_MOV,[]) and
  10928. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10929. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10930. begin
  10931. TransferUsedRegs(TmpUsedRegs);
  10932. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10933. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10934. { change
  10935. mov reg1,reg2
  10936. imul y,reg2 to imul y,reg1,reg2 }
  10937. begin
  10938. taicpu(p).ops := 3;
  10939. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10940. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10941. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10942. RemoveInstruction(hp1);
  10943. result:=true;
  10944. end;
  10945. end;
  10946. end;
  10947. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10948. var
  10949. ThisLabel: TAsmLabel;
  10950. begin
  10951. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10952. ThisLabel.decrefs;
  10953. taicpu(p).condition := C_None;
  10954. taicpu(p).opcode := A_RET;
  10955. taicpu(p).is_jmp := false;
  10956. taicpu(p).ops := taicpu(ret_p).ops;
  10957. case taicpu(ret_p).ops of
  10958. 0:
  10959. taicpu(p).clearop(0);
  10960. 1:
  10961. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10962. else
  10963. internalerror(2016041301);
  10964. end;
  10965. { If the original label is now dead, it might turn out that the label
  10966. immediately follows p. As a result, everything beyond it, which will
  10967. be just some final register configuration and a RET instruction, is
  10968. now dead code. [Kit] }
  10969. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10970. running RemoveDeadCodeAfterJump for each RET instruction, because
  10971. this optimisation rarely happens and most RETs appear at the end of
  10972. routines where there is nothing that can be stripped. [Kit] }
  10973. if not ThisLabel.is_used then
  10974. RemoveDeadCodeAfterJump(p);
  10975. end;
  10976. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10977. var
  10978. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10979. Unconditional, PotentialModified: Boolean;
  10980. OperPtr: POper;
  10981. NewRef: TReference;
  10982. InstrList: array of taicpu;
  10983. InstrMax, Index: Integer;
  10984. const
  10985. {$ifdef DEBUG_AOPTCPU}
  10986. SNoFlags: shortstring = ' so the flags aren''t modified';
  10987. {$else DEBUG_AOPTCPU}
  10988. SNoFlags = '';
  10989. {$endif DEBUG_AOPTCPU}
  10990. begin
  10991. Result:=false;
  10992. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10993. begin
  10994. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10995. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10996. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10997. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10998. GetNextInstruction(hp1, hp2) and
  10999. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  11000. { Change from: To:
  11001. set(C) %reg j(~C) label
  11002. test %reg,%reg/cmp $0,%reg
  11003. je label
  11004. set(C) %reg j(C) label
  11005. test %reg,%reg/cmp $0,%reg
  11006. jne label
  11007. (Also do something similar with sete/setne instead of je/jne)
  11008. }
  11009. begin
  11010. { Before we do anything else, we need to check the instructions
  11011. in between SETcc and TEST to make sure they don't modify the
  11012. FLAGS register - if -O2 or under, there won't be any
  11013. instructions between SET and TEST }
  11014. TransferUsedRegs(TmpUsedRegs);
  11015. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11016. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11017. begin
  11018. next := p;
  11019. SetLength(InstrList, 0);
  11020. InstrMax := -1;
  11021. PotentialModified := False;
  11022. { Make a note of every instruction that modifies the FLAGS
  11023. register }
  11024. while GetNextInstruction(next, next) and (next <> hp1) do
  11025. begin
  11026. if next.typ <> ait_instruction then
  11027. { GetNextInstructionUsingReg should have returned False }
  11028. InternalError(2021051701);
  11029. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11030. begin
  11031. case taicpu(next).opcode of
  11032. A_SETcc,
  11033. A_CMOVcc,
  11034. A_Jcc:
  11035. begin
  11036. if PotentialModified then
  11037. { Not safe because the flags were modified earlier }
  11038. Exit
  11039. else
  11040. { Condition is the same as the initial SETcc, so this is safe
  11041. (don't add to instruction list though) }
  11042. Continue;
  11043. end;
  11044. A_ADD:
  11045. begin
  11046. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11047. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11048. (taicpu(next).oper[1]^.typ <> top_reg) or
  11049. { Must write to a register }
  11050. (taicpu(next).oper[0]^.typ = top_ref) then
  11051. { Require a constant or a register }
  11052. Exit;
  11053. PotentialModified := True;
  11054. end;
  11055. A_SUB:
  11056. begin
  11057. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11058. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11059. (taicpu(next).oper[1]^.typ <> top_reg) or
  11060. { Must write to a register }
  11061. (taicpu(next).oper[0]^.typ <> top_const) or
  11062. (taicpu(next).oper[0]^.val = $80000000) then
  11063. { Can't subtract a register with LEA - also
  11064. check that the value isn't -2^31, as this
  11065. can't be negated }
  11066. Exit;
  11067. PotentialModified := True;
  11068. end;
  11069. A_SAL,
  11070. A_SHL:
  11071. begin
  11072. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11073. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11074. (taicpu(next).oper[1]^.typ <> top_reg) or
  11075. { Must write to a register }
  11076. (taicpu(next).oper[0]^.typ <> top_const) or
  11077. (taicpu(next).oper[0]^.val < 0) or
  11078. (taicpu(next).oper[0]^.val > 3) then
  11079. Exit;
  11080. PotentialModified := True;
  11081. end;
  11082. A_IMUL:
  11083. begin
  11084. if (taicpu(next).ops <> 3) or
  11085. (taicpu(next).oper[1]^.typ <> top_reg) or
  11086. { Must write to a register }
  11087. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11088. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11089. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11090. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11091. Exit
  11092. else
  11093. PotentialModified := True;
  11094. end;
  11095. else
  11096. { Don't know how to change this, so abort }
  11097. Exit;
  11098. end;
  11099. { Contains highest index (so instruction count - 1) }
  11100. Inc(InstrMax);
  11101. if InstrMax > High(InstrList) then
  11102. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11103. InstrList[InstrMax] := taicpu(next);
  11104. end;
  11105. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11106. end;
  11107. if not Assigned(next) or (next <> hp1) then
  11108. { It should be equal to hp1 }
  11109. InternalError(2021051702);
  11110. { Cycle through each instruction and check to see if we can
  11111. change them to versions that don't modify the flags }
  11112. if (InstrMax >= 0) then
  11113. begin
  11114. for Index := 0 to InstrMax do
  11115. case InstrList[Index].opcode of
  11116. A_ADD:
  11117. begin
  11118. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11119. InstrList[Index].opcode := A_LEA;
  11120. reference_reset(NewRef, 1, []);
  11121. NewRef.base := InstrList[Index].oper[1]^.reg;
  11122. if InstrList[Index].oper[0]^.typ = top_reg then
  11123. begin
  11124. NewRef.index := InstrList[Index].oper[0]^.reg;
  11125. NewRef.scalefactor := 1;
  11126. end
  11127. else
  11128. NewRef.offset := InstrList[Index].oper[0]^.val;
  11129. InstrList[Index].loadref(0, NewRef);
  11130. end;
  11131. A_SUB:
  11132. begin
  11133. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11134. InstrList[Index].opcode := A_LEA;
  11135. reference_reset(NewRef, 1, []);
  11136. NewRef.base := InstrList[Index].oper[1]^.reg;
  11137. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11138. InstrList[Index].loadref(0, NewRef);
  11139. end;
  11140. A_SHL,
  11141. A_SAL:
  11142. begin
  11143. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11144. InstrList[Index].opcode := A_LEA;
  11145. reference_reset(NewRef, 1, []);
  11146. NewRef.index := InstrList[Index].oper[1]^.reg;
  11147. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11148. InstrList[Index].loadref(0, NewRef);
  11149. end;
  11150. A_IMUL:
  11151. begin
  11152. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11153. InstrList[Index].opcode := A_LEA;
  11154. reference_reset(NewRef, 1, []);
  11155. NewRef.index := InstrList[Index].oper[1]^.reg;
  11156. case InstrList[Index].oper[0]^.val of
  11157. 2, 4, 8:
  11158. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11159. else {3, 5 and 9}
  11160. begin
  11161. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11162. NewRef.base := InstrList[Index].oper[1]^.reg;
  11163. end;
  11164. end;
  11165. InstrList[Index].loadref(0, NewRef);
  11166. end;
  11167. else
  11168. InternalError(2021051710);
  11169. end;
  11170. end;
  11171. { Mark the FLAGS register as used across this whole block }
  11172. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11173. end;
  11174. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11175. JumpC := taicpu(hp2).condition;
  11176. Unconditional := False;
  11177. if conditions_equal(JumpC, C_E) then
  11178. SetC := inverse_cond(taicpu(p).condition)
  11179. else if conditions_equal(JumpC, C_NE) then
  11180. SetC := taicpu(p).condition
  11181. else
  11182. { We've got something weird here (and inefficent) }
  11183. begin
  11184. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11185. SetC := C_NONE;
  11186. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11187. if condition_in(C_AE, JumpC) then
  11188. Unconditional := True
  11189. else
  11190. { Not sure what to do with this jump - drop out }
  11191. Exit;
  11192. end;
  11193. RemoveInstruction(hp1);
  11194. if Unconditional then
  11195. MakeUnconditional(taicpu(hp2))
  11196. else
  11197. begin
  11198. if SetC = C_NONE then
  11199. InternalError(2018061402);
  11200. taicpu(hp2).SetCondition(SetC);
  11201. end;
  11202. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11203. TmpUsedRegs }
  11204. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11205. begin
  11206. RemoveCurrentp(p, hp2);
  11207. if taicpu(hp2).opcode = A_SETcc then
  11208. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11209. else
  11210. begin
  11211. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11212. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11213. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11214. end;
  11215. end
  11216. else
  11217. if taicpu(hp2).opcode = A_SETcc then
  11218. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11219. else
  11220. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11221. Result := True;
  11222. end
  11223. else if
  11224. { Make sure the instructions are adjacent }
  11225. (
  11226. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11227. GetNextInstruction(p, hp1)
  11228. ) and
  11229. MatchInstruction(hp1, A_MOV, [S_B]) and
  11230. { Writing to memory is allowed }
  11231. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11232. begin
  11233. {
  11234. Watch out for sequences such as:
  11235. set(c)b %regb
  11236. movb %regb,(ref)
  11237. movb $0,1(ref)
  11238. movb $0,2(ref)
  11239. movb $0,3(ref)
  11240. Much more efficient to turn it into:
  11241. movl $0,%regl
  11242. set(c)b %regb
  11243. movl %regl,(ref)
  11244. Or:
  11245. set(c)b %regb
  11246. movzbl %regb,%regl
  11247. movl %regl,(ref)
  11248. }
  11249. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11250. GetNextInstruction(hp1, hp2) and
  11251. MatchInstruction(hp2, A_MOV, [S_B]) and
  11252. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11253. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11254. begin
  11255. { Don't do anything else except set Result to True }
  11256. end
  11257. else
  11258. begin
  11259. if taicpu(p).oper[0]^.typ = top_reg then
  11260. begin
  11261. TransferUsedRegs(TmpUsedRegs);
  11262. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11263. end;
  11264. { If it's not a register, it's a memory address }
  11265. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11266. begin
  11267. { Even if the register is still in use, we can minimise the
  11268. pipeline stall by changing the MOV into another SETcc. }
  11269. taicpu(hp1).opcode := A_SETcc;
  11270. taicpu(hp1).condition := taicpu(p).condition;
  11271. if taicpu(hp1).oper[1]^.typ = top_ref then
  11272. begin
  11273. { Swapping the operand pointers like this is probably a
  11274. bit naughty, but it is far faster than using loadoper
  11275. to transfer the reference from oper[1] to oper[0] if
  11276. you take into account the extra procedure calls and
  11277. the memory allocation and deallocation required }
  11278. OperPtr := taicpu(hp1).oper[1];
  11279. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11280. taicpu(hp1).oper[0] := OperPtr;
  11281. end
  11282. else
  11283. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11284. taicpu(hp1).clearop(1);
  11285. taicpu(hp1).ops := 1;
  11286. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11287. end
  11288. else
  11289. begin
  11290. if taicpu(hp1).oper[1]^.typ = top_reg then
  11291. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11292. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11293. RemoveInstruction(hp1);
  11294. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11295. end
  11296. end;
  11297. Result := True;
  11298. end;
  11299. end;
  11300. end;
  11301. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11302. var
  11303. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11304. TargetReg: TRegister;
  11305. condition, inverted_condition: TAsmCond;
  11306. FoundMOV: Boolean;
  11307. begin
  11308. Result := False;
  11309. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11310. create the most optimial instructions possible due to limited
  11311. register availability, and there are situations where two
  11312. complementary "simple" CMOV blocks are created which, after the fact
  11313. can be merged into a "double" block. For example:
  11314. movw $257,%ax
  11315. movw $2,%r8w
  11316. xorl r9d,%r9d
  11317. testw $16,18(%rcx)
  11318. cmovew %ax,%dx
  11319. cmovew %r8w,%bx
  11320. cmovel %r9d,%r14d
  11321. movw $1283,%ax
  11322. movw $4,%r8w
  11323. movl $9,%r9d
  11324. cmovnew %ax,%dx
  11325. cmovnew %r8w,%bx
  11326. cmovnel %r9d,%r14d
  11327. The CMOVNE instructions at the end can be removed, and the
  11328. destination registers copied into the MOV instructions directly
  11329. above them, before finally being moved to before the first CMOVE
  11330. instructions, to produce:
  11331. movw $257,%ax
  11332. movw $2,%r8w
  11333. xorl r9d,%r9d
  11334. testw $16,18(%rcx)
  11335. movw $1283,%dx
  11336. movw $4,%bx
  11337. movl $9,%r14d
  11338. cmovew %ax,%dx
  11339. cmovew %r8w,%bx
  11340. cmovel %r9d,%r14d
  11341. Which can then be later optimised to:
  11342. movw $257,%ax
  11343. movw $2,%r8w
  11344. xorl r9d,%r9d
  11345. movw $1283,%dx
  11346. movw $4,%bx
  11347. movl $9,%r14d
  11348. testw $16,18(%rcx)
  11349. cmovew %ax,%dx
  11350. cmovew %r8w,%bx
  11351. cmovel %r9d,%r14d
  11352. }
  11353. TargetReg := taicpu(hp1).oper[1]^.reg;
  11354. condition := taicpu(hp1).condition;
  11355. inverted_condition := inverse_cond(condition);
  11356. pFirstMov := nil;
  11357. pLastMov := nil;
  11358. pCMOV := nil;
  11359. if (p.typ = ait_instruction) then
  11360. pCond := p
  11361. else if not GetNextInstruction(p, pCond) then
  11362. InternalError(2024012501);
  11363. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11364. { We should get the CMP or TEST instructeion }
  11365. InternalError(2024012502);
  11366. if (
  11367. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11368. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11369. ) then
  11370. begin
  11371. { We have to tread carefully here, hence why we're not using
  11372. GetNextInstructionUsingReg... we can only accept MOV and other
  11373. CMOV instructions. Anything else and we must drop out}
  11374. hp2 := hp1;
  11375. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11376. begin
  11377. if (hp2.typ <> ait_instruction) then
  11378. Exit;
  11379. case taicpu(hp2).opcode of
  11380. A_MOV:
  11381. begin
  11382. if not Assigned(pFirstMov) then
  11383. pFirstMov := hp2;
  11384. pLastMOV := hp2;
  11385. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11386. { Something different - drop out }
  11387. Exit;
  11388. { Otherwise, leave it for now }
  11389. end;
  11390. A_CMOVcc:
  11391. begin
  11392. if taicpu(hp2).condition = inverted_condition then
  11393. begin
  11394. { We found what we're looking for }
  11395. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11396. begin
  11397. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11398. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11399. begin
  11400. pCMOV := hp2;
  11401. Break;
  11402. end
  11403. else
  11404. { Unsafe reference - drop out }
  11405. Exit;
  11406. end;
  11407. end
  11408. else if taicpu(hp2).condition <> condition then
  11409. { Something weird - drop out }
  11410. Exit;
  11411. end;
  11412. else
  11413. { Invalid }
  11414. Exit;
  11415. end;
  11416. end;
  11417. if not Assigned(pCMOV) then
  11418. { No complementary CMOV found }
  11419. Exit;
  11420. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11421. begin
  11422. { Don't need to do anything special or search for a matching MOV }
  11423. Asml.Remove(pCMOV);
  11424. if RegInInstruction(TargetReg, pCond) then
  11425. { Make sure we don't overwrite the register if it's being used in the condition }
  11426. Asml.InsertAfter(pCMOV, pCond)
  11427. else
  11428. Asml.InsertBefore(pCMOV, pCond);
  11429. taicpu(pCMOV).opcode := A_MOV;
  11430. taicpu(pCMOV).condition := C_None;
  11431. { Don't need to worry about allocating new registers in these cases }
  11432. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11433. Result := True;
  11434. Exit;
  11435. end
  11436. else
  11437. begin
  11438. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11439. FoundMOV := False;
  11440. { Search for the MOV that sets the target register }
  11441. hp2 := pFirstMov;
  11442. repeat
  11443. if (taicpu(hp2).opcode = A_MOV) and
  11444. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11445. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11446. begin
  11447. { Change the destination }
  11448. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11449. if not FoundMOV then
  11450. begin
  11451. FoundMOV := True;
  11452. { Make sure the register is allocated }
  11453. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11454. end;
  11455. hp1 := tai(hp2.Previous);
  11456. Asml.Remove(hp2);
  11457. if RegInInstruction(TargetReg, pCond) then
  11458. { Make sure we don't overwrite the register if it's being used in the condition }
  11459. Asml.InsertAfter(hp2, pCond)
  11460. else
  11461. Asml.InsertBefore(hp2, pCond);
  11462. if (hp2 = pLastMov) then
  11463. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11464. Break;
  11465. hp2 := hp1;
  11466. end;
  11467. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11468. if FoundMOV then
  11469. { Delete the CMOV }
  11470. RemoveInstruction(pCMOV)
  11471. else
  11472. begin
  11473. { If no MOV was found, we have to actually move and transmute the CMOV }
  11474. Asml.Remove(pCMOV);
  11475. if RegInInstruction(TargetReg, pCond) then
  11476. { Make sure we don't overwrite the register if it's being used in the condition }
  11477. Asml.InsertAfter(pCMOV, pCond)
  11478. else
  11479. Asml.InsertBefore(pCMOV, pCond);
  11480. taicpu(pCMOV).opcode := A_MOV;
  11481. taicpu(pCMOV).condition := C_None;
  11482. end;
  11483. Result := True;
  11484. Exit;
  11485. end;
  11486. end;
  11487. end;
  11488. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11489. var
  11490. hp1, hp2, pCond: tai;
  11491. begin
  11492. Result := False;
  11493. { Search ahead for CMOV instructions }
  11494. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11495. begin
  11496. hp1 := p;
  11497. hp2 := p;
  11498. pCond := nil; { To prevent compiler warnings }
  11499. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11500. DEFAULTFLAGS }
  11501. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11502. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11503. pCond := p;
  11504. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11505. begin
  11506. if (hp1.typ <> ait_instruction) then
  11507. { Break out on markers and labels etc. }
  11508. Break;
  11509. case taicpu(hp1).opcode of
  11510. A_MOV:
  11511. { Ignore regular MOVs unless they are obviously not related
  11512. to a CMOV block }
  11513. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11514. Break;
  11515. A_CMOVcc:
  11516. if TryCmpCMovOpts(pCond, hp1) then
  11517. begin
  11518. hp1 := hp2;
  11519. { p itself isn't changed, and we're still inside a
  11520. while loop to catch subsequent CMOVs, so just flag
  11521. a new iteration }
  11522. Include(OptsToCheck, aoc_ForceNewIteration);
  11523. Continue;
  11524. end;
  11525. else
  11526. { Drop out if we find anything else }
  11527. Break;
  11528. end;
  11529. hp2 := hp1;
  11530. end;
  11531. end;
  11532. end;
  11533. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11534. var
  11535. hp1, hp2, pCond: tai;
  11536. SourceReg, TargetReg: TRegister;
  11537. begin
  11538. Result := False;
  11539. { In some situations, we end up with an inefficient arrangement of
  11540. instructions in the form of:
  11541. or %reg1,%reg2
  11542. (%reg1 deallocated)
  11543. test %reg2,%reg2
  11544. mov x,%reg2
  11545. we may be able to swap and rearrange the registers to produce:
  11546. or %reg2,%reg1
  11547. mov x,%reg2
  11548. test %reg1,%reg1
  11549. (%reg1 deallocated)
  11550. }
  11551. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11552. (taicpu(p).oper[1]^.typ = top_reg) and
  11553. (
  11554. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11555. MatchOperand(taicpu(p).oper[0]^, -1)
  11556. ) and
  11557. GetNextInstruction(p, hp1) and
  11558. MatchInstruction(hp1, A_MOV, []) and
  11559. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11560. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11561. begin
  11562. TargetReg := taicpu(p).oper[1]^.reg;
  11563. { Now look backwards to find a simple commutative operation: ADD,
  11564. IMUL (2-register version), OR, AND or XOR - whose destination
  11565. register is the same as TEST }
  11566. hp2 := p;
  11567. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11568. if RegInInstruction(TargetReg, hp2) then
  11569. begin
  11570. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11571. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11572. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11573. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11574. begin
  11575. SourceReg := taicpu(hp2).oper[0]^.reg;
  11576. if
  11577. { Make sure the MOV doesn't use the other register }
  11578. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11579. { And make sure the source register is not used afterwards }
  11580. not RegInUsedRegs(SourceReg, UsedRegs) then
  11581. begin
  11582. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11583. taicpu(hp2).oper[0]^.reg := TargetReg;
  11584. taicpu(hp2).oper[1]^.reg := SourceReg;
  11585. if taicpu(p).oper[0]^.typ = top_reg then
  11586. taicpu(p).oper[0]^.reg := SourceReg;
  11587. taicpu(p).oper[1]^.reg := SourceReg;
  11588. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11589. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11590. Include(OptsToCheck, aoc_ForceNewIteration);
  11591. { We can still check the following optimisations since
  11592. the instruction is still a TEST }
  11593. end;
  11594. end;
  11595. Break;
  11596. end;
  11597. end;
  11598. { Search ahead3 for CMOV instructions }
  11599. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11600. begin
  11601. hp1 := p;
  11602. hp2 := p;
  11603. pCond := nil; { To prevent compiler warnings }
  11604. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11605. DEFAULTFLAGS }
  11606. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11607. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11608. pCond := p;
  11609. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11610. begin
  11611. if (hp1.typ <> ait_instruction) then
  11612. { Break out on markers and labels etc. }
  11613. Break;
  11614. case taicpu(hp1).opcode of
  11615. A_MOV:
  11616. { Ignore regular MOVs unless they are obviously not related
  11617. to a CMOV block }
  11618. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11619. Break;
  11620. A_CMOVcc:
  11621. if TryCmpCMovOpts(pCond, hp1) then
  11622. begin
  11623. hp1 := hp2;
  11624. { p itself isn't changed, and we're still inside a
  11625. while loop to catch subsequent CMOVs, so just flag
  11626. a new iteration }
  11627. Include(OptsToCheck, aoc_ForceNewIteration);
  11628. Continue;
  11629. end;
  11630. else
  11631. { Drop out if we find anything else }
  11632. Break;
  11633. end;
  11634. hp2 := hp1;
  11635. end;
  11636. end;
  11637. end;
  11638. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11639. var
  11640. hp1: tai;
  11641. Count: Integer;
  11642. OrigLabel: TAsmLabel;
  11643. begin
  11644. result := False;
  11645. { Sometimes, the optimisations below can permit this }
  11646. RemoveDeadCodeAfterJump(p);
  11647. 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
  11648. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11649. begin
  11650. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11651. { Also a side-effect of optimisations }
  11652. if CollapseZeroDistJump(p, OrigLabel) then
  11653. begin
  11654. Result := True;
  11655. Exit;
  11656. end;
  11657. hp1 := GetLabelWithSym(OrigLabel);
  11658. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11659. begin
  11660. if taicpu(hp1).opcode = A_RET then
  11661. begin
  11662. {
  11663. change
  11664. jmp .L1
  11665. ...
  11666. .L1:
  11667. ret
  11668. into
  11669. ret
  11670. }
  11671. begin
  11672. ConvertJumpToRET(p, hp1);
  11673. result:=true;
  11674. end;
  11675. end
  11676. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11677. not (cs_opt_size in current_settings.optimizerswitches) and
  11678. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11679. begin
  11680. Result := True;
  11681. Exit;
  11682. end;
  11683. end;
  11684. end;
  11685. end;
  11686. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11687. begin
  11688. Result := assigned(p) and
  11689. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11690. (taicpu(p).oper[1]^.typ = top_reg) and
  11691. (
  11692. (taicpu(p).oper[0]^.typ = top_reg) or
  11693. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11694. it is not expected that this can cause a seg. violation }
  11695. (
  11696. (taicpu(p).oper[0]^.typ = top_ref) and
  11697. { TODO: Can we detect which references become constants at this
  11698. stage so we don't have to do a blanket ban? }
  11699. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11700. (
  11701. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11702. (
  11703. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11704. not RefModified and
  11705. { If the reference also appears in the condition, then we know it's safe, otherwise
  11706. any kind of access violation would have occurred already }
  11707. Assigned(cond_p) and
  11708. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11709. (cond_p.typ = ait_instruction) and
  11710. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11711. { Just consider 2-operand comparison instructions for now to be safe }
  11712. (taicpu(cond_p).ops = 2) and
  11713. (
  11714. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11715. (
  11716. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11717. { Don't risk identical registers but different offsets, as we may have constructs
  11718. such as buffer streams with things like length fields that indicate whether
  11719. any more data follows. And there are probably some contrived examples where
  11720. writing to offsets behind the one being read also lead to access violations }
  11721. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11722. (
  11723. { Check that we're not modifying a register that appears in the reference }
  11724. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11725. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11726. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11727. )
  11728. )
  11729. )
  11730. )
  11731. )
  11732. )
  11733. );
  11734. end;
  11735. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11736. begin
  11737. { Update integer registers, ignoring deallocations }
  11738. repeat
  11739. while assigned(p) and
  11740. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11741. (p.typ = ait_label) or
  11742. ((p.typ = ait_marker) and
  11743. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11744. p := tai(p.next);
  11745. while assigned(p) and
  11746. (p.typ=ait_RegAlloc) Do
  11747. begin
  11748. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11749. begin
  11750. case tai_regalloc(p).ratype of
  11751. ra_alloc :
  11752. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11753. else
  11754. ;
  11755. end;
  11756. end;
  11757. p := tai(p.next);
  11758. end;
  11759. until not(assigned(p)) or
  11760. (not(p.typ in SkipInstr) and
  11761. not((p.typ = ait_label) and
  11762. labelCanBeSkipped(tai_label(p))));
  11763. end;
  11764. {$ifndef 8086}
  11765. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11766. begin
  11767. Result := False;
  11768. EndJump := nil;
  11769. BlockStop := nil;
  11770. while (BlockStart <> fOptimizer.BlockEnd) and
  11771. { stop on labels }
  11772. (BlockStart.typ <> ait_label) do
  11773. begin
  11774. { Keep track of all integer registers that are used }
  11775. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11776. if BlockStart.typ = ait_instruction then
  11777. begin
  11778. if (taicpu(BlockStart).opcode = A_JMP) then
  11779. begin
  11780. if not IsJumpToLabel(taicpu(BlockStart)) or
  11781. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11782. Exit;
  11783. EndJump := BlockStart;
  11784. Break;
  11785. end
  11786. { Check to see if we have a valid MOV instruction instead }
  11787. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11788. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11789. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11790. begin
  11791. Exit;
  11792. end
  11793. else
  11794. { This will be a valid MOV }
  11795. fAllocationRange := BlockStart;
  11796. end;
  11797. OneBeforeBlock := BlockStart;
  11798. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11799. end;
  11800. if (BlockStart = fOptimizer.BlockEnd) then
  11801. Exit;
  11802. BlockStop := BlockStart;
  11803. Result := True;
  11804. end;
  11805. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11806. var
  11807. hp1: tai;
  11808. RefModified: Boolean;
  11809. begin
  11810. Result := 0;
  11811. hp1 := BlockStart;
  11812. RefModified := False; { As long as the condition is inverted, this can be reset }
  11813. while assigned(hp1) and
  11814. (hp1 <> BlockStop) do
  11815. begin
  11816. case hp1.typ of
  11817. ait_instruction:
  11818. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11819. begin
  11820. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11821. begin
  11822. Inc(Result);
  11823. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11824. Assigned(fCondition) and
  11825. { Will have 2 operands }
  11826. (
  11827. (
  11828. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11829. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11830. ) or
  11831. (
  11832. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11833. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11834. )
  11835. ) then
  11836. { It is no longer safe to use the reference in the condition.
  11837. this prevents problems such as:
  11838. mov (%reg),%reg
  11839. mov (%reg),...
  11840. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11841. (fixes #40165)
  11842. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11843. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11844. }
  11845. RefModified := True;
  11846. end
  11847. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11848. { CMOV with constants grows the code size }
  11849. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11850. begin
  11851. { Register was reserved by TryCMOVConst and
  11852. stored on ConstRegs }
  11853. end
  11854. else
  11855. begin
  11856. Result := -1;
  11857. Exit;
  11858. end;
  11859. end
  11860. else
  11861. begin
  11862. Result := -1;
  11863. Exit;
  11864. end;
  11865. else
  11866. { Most likely an align };
  11867. end;
  11868. fOptimizer.GetNextInstruction(hp1, hp1);
  11869. end;
  11870. end;
  11871. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11872. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11873. (this is done as a separate stage because the double types are extensions of the branching type,
  11874. but we can't discount the conditional jump until the last step) }
  11875. procedure EvaluateBranchingType;
  11876. begin
  11877. Inc(CMOVScore);
  11878. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11879. { Too many instructions to be worthwhile }
  11880. fState := tsInvalid;
  11881. end;
  11882. var
  11883. hp1: tai;
  11884. Count: Integer;
  11885. begin
  11886. { Table of valid CMOV block types
  11887. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11888. ---------- --------- --------- --------- --------- ---------
  11889. tsSimple X Yes X X X
  11890. tsDetour = 1st X X X X
  11891. tsBranching <> Mid Yes X X X
  11892. tsDouble End-label Yes * Yes X Yes
  11893. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11894. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11895. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11896. * Only one reference allowed
  11897. }
  11898. hp1 := nil; { To prevent compiler warnings }
  11899. Optimizer.CopyUsedRegs(RegisterTracking);
  11900. fOptimizer := Optimizer;
  11901. fLabel := AFirstLabel;
  11902. CMOVScore := 0;
  11903. ConstCount := 0;
  11904. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11905. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11906. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11907. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11908. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11909. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11910. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11911. fInsertionPoint := p_initialjump;
  11912. fCondition := nil;
  11913. fInitialJump := p_initialjump;
  11914. fFirstMovBlock := p_initialmov;
  11915. fFirstMovBlockStop := nil;
  11916. fSecondJump := nil;
  11917. fSecondMovBlock := nil;
  11918. fSecondMovBlockStop := nil;
  11919. fMidLabel := nil;
  11920. fSecondJump := nil;
  11921. fSecondMovBlock := nil;
  11922. fEndLabel := nil;
  11923. fAllocationRange := nil;
  11924. { Assume it all goes horribly wrong! }
  11925. fState := tsInvalid;
  11926. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11927. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11928. 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
  11929. begin
  11930. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11931. for Count := 0 to 1 do
  11932. with taicpu(fCondition).oper[Count]^ do
  11933. case typ of
  11934. top_reg:
  11935. if getregtype(reg) = R_INTREGISTER then
  11936. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11937. top_ref:
  11938. begin
  11939. if
  11940. {$ifdef x86_64}
  11941. (ref^.base <> NR_RIP) and
  11942. {$endif x86_64}
  11943. (ref^.base <> NR_NO) then
  11944. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11945. if (ref^.index <> NR_NO) then
  11946. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11947. end
  11948. else
  11949. ;
  11950. end;
  11951. { When inserting instructions before hp_prev, try to insert them
  11952. before the allocation of the FLAGS register }
  11953. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11954. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11955. { If not found, set it equal to the condition so it's something sensible }
  11956. fInsertionPoint := fCondition;
  11957. { When dealing with a comparison against zero, take note of the
  11958. instruction before it to see if we can move instructions further
  11959. back in order to benefit PostPeepholeOptTestOr.
  11960. }
  11961. if (
  11962. (
  11963. (taicpu(fCondition).opcode = A_CMP) and
  11964. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11965. ) or
  11966. (
  11967. (taicpu(fCondition).opcode = A_TEST) and
  11968. (
  11969. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11970. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11971. )
  11972. )
  11973. ) and
  11974. Optimizer.GetLastInstruction(fCondition, hp1) then
  11975. begin
  11976. { These instructions set the zero flag if the result is zero }
  11977. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11978. begin
  11979. fInsertionPoint := hp1;
  11980. { Also mark all the registers in this previous instruction
  11981. as 'in use', even if they've just been deallocated }
  11982. for Count := 0 to 1 do
  11983. with taicpu(hp1).oper[Count]^ do
  11984. case typ of
  11985. top_reg:
  11986. if getregtype(reg) = R_INTREGISTER then
  11987. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11988. top_ref:
  11989. begin
  11990. if
  11991. {$ifdef x86_64}
  11992. (ref^.base <> NR_RIP) and
  11993. {$endif x86_64}
  11994. (ref^.base <> NR_NO) then
  11995. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11996. if (ref^.index <> NR_NO) then
  11997. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11998. end
  11999. else
  12000. ;
  12001. end;
  12002. end;
  12003. end;
  12004. end
  12005. else
  12006. fCondition := nil;
  12007. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  12008. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  12009. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  12010. { If not found, set it equal to p so it's something sensible }
  12011. fInsertionPoint := hp1;
  12012. hp1 := p_initialmov;
  12013. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  12014. Exit;
  12015. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  12016. if (hp1.typ <> ait_label) then { should be on a jump }
  12017. begin
  12018. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  12019. { Need a label afterwards }
  12020. Exit;
  12021. end
  12022. else
  12023. fMidLabel := hp1;
  12024. if tai_label(fMidLabel).labsym <> AFirstLabel then
  12025. { Not the correct label }
  12026. fMidLabel := nil;
  12027. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12028. { If there's neither a 2nd jump nor correct label, then it's invalid
  12029. (see above table) }
  12030. Exit;
  12031. { Analyse the first block of MOVs more closely }
  12032. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12033. if Assigned(fSecondJump) then
  12034. begin
  12035. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12036. begin
  12037. fState := tsDetour
  12038. end
  12039. else
  12040. begin
  12041. { Need the correct mid-label for this one }
  12042. if not Assigned(fMidLabel) then
  12043. Exit;
  12044. fState := tsBranching;
  12045. end;
  12046. end
  12047. else
  12048. { No jump. but mid-label is present }
  12049. fState := tsSimple;
  12050. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12051. begin
  12052. { Invalid or too many instructions to be worthwhile }
  12053. fState := tsInvalid;
  12054. Exit;
  12055. end;
  12056. { check further for
  12057. jCC xxx
  12058. <several movs 1>
  12059. jmp yyy
  12060. xxx:
  12061. <several movs 2>
  12062. yyy:
  12063. etc.
  12064. }
  12065. if (fState = tsBranching) and
  12066. { Estimate for required savings for extra jump }
  12067. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12068. { Only one reference is allowed for double blocks }
  12069. (AFirstLabel.getrefs = 1) then
  12070. begin
  12071. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12072. fSecondMovBlock := hp1;
  12073. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12074. begin
  12075. EvaluateBranchingType;
  12076. Exit;
  12077. end;
  12078. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12079. if (hp1.typ <> ait_label) then { should be on a jump }
  12080. begin
  12081. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12082. begin
  12083. { Need a label afterwards }
  12084. EvaluateBranchingType;
  12085. Exit;
  12086. end;
  12087. end
  12088. else
  12089. fEndLabel := hp1;
  12090. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12091. { Second jump doesn't go to the end }
  12092. fEndLabel := nil;
  12093. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12094. begin
  12095. { If there's neither a 3rd jump nor correct end label, then it's
  12096. not a invalid double block, but is a valid single branching
  12097. block (see above table) }
  12098. EvaluateBranchingType;
  12099. Exit;
  12100. end;
  12101. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12102. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12103. { Invalid or too many instructions to be worthwhile }
  12104. Exit;
  12105. Inc(CMOVScore, Count);
  12106. if Assigned(fThirdJump) then
  12107. begin
  12108. if not Assigned(fSecondJump) then
  12109. fState := tsDoubleSecondBranching
  12110. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12111. fState := tsDoubleBranchSame
  12112. else
  12113. fState := tsDoubleBranchDifferent;
  12114. end
  12115. else
  12116. fState := tsDouble;
  12117. end;
  12118. if fState = tsBranching then
  12119. EvaluateBranchingType;
  12120. end;
  12121. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12122. new register to store the constant }
  12123. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12124. var
  12125. RegSize: TSubRegister;
  12126. CurrentVal: TCGInt;
  12127. ANewReg: TRegister;
  12128. X: ShortInt;
  12129. begin
  12130. Result := False;
  12131. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12132. Exit;
  12133. if ConstCount >= MAX_CMOV_REGISTERS then
  12134. { Arrays are full }
  12135. Exit;
  12136. { Remember that CMOV can't encode 8-bit registers }
  12137. case taicpu(p).opsize of
  12138. S_W:
  12139. RegSize := R_SUBW;
  12140. S_L:
  12141. RegSize := R_SUBD;
  12142. {$ifdef x86_64}
  12143. S_Q:
  12144. RegSize := R_SUBQ;
  12145. {$endif x86_64}
  12146. else
  12147. InternalError(2021100401);
  12148. end;
  12149. { See if the value has already been reserved for another CMOV instruction }
  12150. CurrentVal := taicpu(p).oper[0]^.val;
  12151. for X := 0 to ConstCount - 1 do
  12152. if ConstVals[X] = CurrentVal then
  12153. begin
  12154. ConstRegs[ConstCount] := ConstRegs[X];
  12155. ConstSizes[ConstCount] := RegSize;
  12156. ConstVals[ConstCount] := CurrentVal;
  12157. Inc(ConstCount);
  12158. Inc(Count);
  12159. Result := True;
  12160. Exit;
  12161. end;
  12162. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12163. if ANewReg = NR_NO then
  12164. { No free registers }
  12165. Exit;
  12166. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12167. up vying for the same register }
  12168. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12169. ConstRegs[ConstCount] := ANewReg;
  12170. ConstSizes[ConstCount] := RegSize;
  12171. ConstVals[ConstCount] := CurrentVal;
  12172. Inc(ConstCount);
  12173. Inc(Count);
  12174. Result := True;
  12175. end;
  12176. destructor TCMOVTracking.Done;
  12177. begin
  12178. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12179. end;
  12180. procedure TCMOVTracking.Process(out new_p: tai);
  12181. var
  12182. Count, Writes: LongInt;
  12183. RegMatch: Boolean;
  12184. hp1, hp_new: tai;
  12185. inverted_condition, condition: TAsmCond;
  12186. begin
  12187. if (fState in [tsInvalid, tsProcessed]) then
  12188. InternalError(2023110701);
  12189. { Repurpose RegisterTracking to mark registers that we've defined }
  12190. RegisterTracking[R_INTREGISTER].Clear;
  12191. Count := 0;
  12192. Writes := 0;
  12193. condition := taicpu(fInitialJump).condition;
  12194. inverted_condition := inverse_cond(condition);
  12195. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12196. doesn't get CMOVs in this case }
  12197. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12198. begin
  12199. { Include the jump in the flag tracking }
  12200. if Assigned(fThirdJump) then
  12201. begin
  12202. if (fState = tsDoubleBranchSame) then
  12203. begin
  12204. { Will be an unconditional jump, so track to the instruction before it }
  12205. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12206. InternalError(2023110710);
  12207. end
  12208. else
  12209. hp1 := fThirdJump;
  12210. end
  12211. else
  12212. hp1 := fSecondMovBlockStop;
  12213. end
  12214. else
  12215. begin
  12216. { Include a conditional jump in the flag tracking }
  12217. if Assigned(fSecondJump) then
  12218. begin
  12219. if (fState = tsDetour) then
  12220. begin
  12221. { Will be an unconditional jump, so track to the instruction before it }
  12222. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12223. InternalError(2023110711);
  12224. end
  12225. else
  12226. hp1 := fSecondJump;
  12227. end
  12228. else
  12229. hp1 := fFirstMovBlockStop;
  12230. end;
  12231. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12232. { Process the second set of MOVs first, because if a destination
  12233. register is shared between the first and second MOV sets, it is more
  12234. efficient to turn the first one into a MOV instruction and place it
  12235. before the CMP if possible, but we won't know which registers are
  12236. shared until we've processed at least one list, so we might as well
  12237. make it the second one since that won't be modified again. }
  12238. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12239. begin
  12240. hp1 := fSecondMovBlock;
  12241. repeat
  12242. if not Assigned(hp1) then
  12243. InternalError(2018062902);
  12244. if (hp1.typ = ait_instruction) then
  12245. begin
  12246. { Extra safeguard }
  12247. if (taicpu(hp1).opcode <> A_MOV) then
  12248. InternalError(2018062903);
  12249. { Note: tsDoubleBranchDifferent is essentially identical to
  12250. tsBranching and the 2nd block is best left largely
  12251. untouched, but we need to evaluate which registers the MOVs
  12252. write to in order to track what would be complementary CMOV
  12253. pairs that can be further optimised. [Kit] }
  12254. if fState <> tsDoubleBranchDifferent then
  12255. begin
  12256. if taicpu(hp1).oper[0]^.typ = top_const then
  12257. begin
  12258. RegMatch := False;
  12259. for Count := 0 to ConstCount - 1 do
  12260. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12261. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12262. begin
  12263. RegMatch := True;
  12264. { If it's in RegisterTracking, then this register
  12265. is being used more than once and hence has
  12266. already had its value defined (it gets added to
  12267. UsedRegs through AllocRegBetween below) }
  12268. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12269. begin
  12270. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12271. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12272. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12273. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12274. ConstMovs[Count] := hp_new;
  12275. end
  12276. else
  12277. { We just need an instruction between hp_prev and hp1
  12278. where we know the register is marked as in use }
  12279. hp_new := fSecondMovBlock;
  12280. { Keep track of largest write for this register so it can be optimised later }
  12281. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12282. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12283. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12284. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12285. Break;
  12286. end;
  12287. if not RegMatch then
  12288. InternalError(2021100411);
  12289. end;
  12290. taicpu(hp1).opcode := A_CMOVcc;
  12291. taicpu(hp1).condition := condition;
  12292. end;
  12293. { Store these writes to search for duplicates later on }
  12294. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12295. Inc(Writes);
  12296. end;
  12297. fOptimizer.GetNextInstruction(hp1, hp1);
  12298. until (hp1 = fSecondMovBlockStop);
  12299. end;
  12300. { Now do the first set of MOVs }
  12301. hp1 := fFirstMovBlock;
  12302. repeat
  12303. if not Assigned(hp1) then
  12304. InternalError(2018062904);
  12305. if (hp1.typ = ait_instruction) then
  12306. begin
  12307. RegMatch := False;
  12308. { Extra safeguard }
  12309. if (taicpu(hp1).opcode <> A_MOV) then
  12310. InternalError(2018062905);
  12311. { Search through the RegWrites list to see if there are any
  12312. opposing CMOV pairs that write to the same register }
  12313. for Count := 0 to Writes - 1 do
  12314. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12315. begin
  12316. { We have a match. Keep this as a MOV }
  12317. { Move ahead in preparation }
  12318. fOptimizer.GetNextInstruction(hp1, hp1);
  12319. RegMatch := True;
  12320. Break;
  12321. end;
  12322. if RegMatch then
  12323. Continue;
  12324. if taicpu(hp1).oper[0]^.typ = top_const then
  12325. begin
  12326. for Count := 0 to ConstCount - 1 do
  12327. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12328. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12329. begin
  12330. RegMatch := True;
  12331. { If it's in RegisterTracking, then this register is
  12332. being used more than once and hence has already had
  12333. its value defined (it gets added to UsedRegs through
  12334. AllocRegBetween below) }
  12335. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12336. begin
  12337. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12338. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12339. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12340. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12341. ConstMovs[Count] := hp_new;
  12342. end
  12343. else
  12344. { We just need an instruction between hp_prev and hp1
  12345. where we know the register is marked as in use }
  12346. hp_new := fFirstMovBlock;
  12347. { Keep track of largest write for this register so it can be optimised later }
  12348. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12349. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12350. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12351. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12352. Break;
  12353. end;
  12354. if not RegMatch then
  12355. InternalError(2021100412);
  12356. end;
  12357. taicpu(hp1).opcode := A_CMOVcc;
  12358. taicpu(hp1).condition := inverted_condition;
  12359. if (fState = tsDoubleBranchDifferent) then
  12360. begin
  12361. { Store these writes to search for duplicates later on }
  12362. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12363. Inc(Writes);
  12364. end;
  12365. end;
  12366. fOptimizer.GetNextInstruction(hp1, hp1);
  12367. until (hp1 = fFirstMovBlockStop);
  12368. { Update initialisation MOVs to the smallest possible size }
  12369. for Count := 0 to ConstCount - 1 do
  12370. if Assigned(ConstMovs[Count]) then
  12371. begin
  12372. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12373. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12374. end;
  12375. case fState of
  12376. tsSimple:
  12377. begin
  12378. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12379. { No branch to delete }
  12380. end;
  12381. tsDetour:
  12382. begin
  12383. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12384. { Preserve jump }
  12385. end;
  12386. tsBranching, tsDoubleBranchDifferent:
  12387. begin
  12388. if (fState = tsBranching) then
  12389. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12390. else
  12391. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12392. taicpu(fSecondJump).opcode := A_JCC;
  12393. taicpu(fSecondJump).condition := inverted_condition;
  12394. end;
  12395. tsDouble, tsDoubleBranchSame:
  12396. begin
  12397. if (fState = tsDouble) then
  12398. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12399. else
  12400. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12401. { Delete second jump }
  12402. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12403. fOptimizer.RemoveInstruction(fSecondJump);
  12404. end;
  12405. tsDoubleSecondBranching:
  12406. begin
  12407. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12408. { Delete second jump, preserve third jump as conditional }
  12409. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12410. fOptimizer.RemoveInstruction(fSecondJump);
  12411. taicpu(fThirdJump).opcode := A_JCC;
  12412. taicpu(fThirdJump).condition := condition;
  12413. end;
  12414. else
  12415. InternalError(2023110720);
  12416. end;
  12417. { Now we can safely decrement the reference count }
  12418. tasmlabel(fLabel).decrefs;
  12419. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12420. { Remove the original jump }
  12421. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12422. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12423. fState := tsProcessed;
  12424. end;
  12425. {$endif 8086}
  12426. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12427. var
  12428. hp1,hp2: tai;
  12429. carryadd_opcode : TAsmOp;
  12430. symbol: TAsmSymbol;
  12431. increg, tmpreg: TRegister;
  12432. {$ifndef i8086}
  12433. CMOVTracking: PCMOVTracking;
  12434. hp3,hp4,hp5: tai;
  12435. {$endif i8086}
  12436. TempBool: Boolean;
  12437. begin
  12438. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12439. DoJumpOptimizations(p, TempBool) then
  12440. Exit(True);
  12441. result:=false;
  12442. if GetNextInstruction(p,hp1) then
  12443. begin
  12444. if (hp1.typ=ait_label) then
  12445. begin
  12446. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12447. Exit;
  12448. end
  12449. else if (hp1.typ<>ait_instruction) then
  12450. Exit;
  12451. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12452. if (
  12453. (
  12454. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12455. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12456. (Taicpu(hp1).oper[0]^.val=1)
  12457. ) or
  12458. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12459. ) and
  12460. GetNextInstruction(hp1,hp2) and
  12461. FindLabel(TAsmLabel(symbol), hp2) then
  12462. { jb @@1 cmc
  12463. inc/dec operand --> adc/sbb operand,0
  12464. @@1:
  12465. ... and ...
  12466. jnb @@1
  12467. inc/dec operand --> adc/sbb operand,0
  12468. @@1: }
  12469. begin
  12470. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12471. begin
  12472. case taicpu(hp1).opcode of
  12473. A_INC,
  12474. A_ADD:
  12475. carryadd_opcode:=A_ADC;
  12476. A_DEC,
  12477. A_SUB:
  12478. carryadd_opcode:=A_SBB;
  12479. else
  12480. InternalError(2021011001);
  12481. end;
  12482. Taicpu(p).clearop(0);
  12483. Taicpu(p).ops:=0;
  12484. Taicpu(p).is_jmp:=false;
  12485. Taicpu(p).opcode:=A_CMC;
  12486. Taicpu(p).condition:=C_NONE;
  12487. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12488. Taicpu(hp1).ops:=2;
  12489. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12490. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12491. else
  12492. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12493. Taicpu(hp1).loadconst(0,0);
  12494. Taicpu(hp1).opcode:=carryadd_opcode;
  12495. result:=true;
  12496. exit;
  12497. end
  12498. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12499. begin
  12500. case taicpu(hp1).opcode of
  12501. A_INC,
  12502. A_ADD:
  12503. carryadd_opcode:=A_ADC;
  12504. A_DEC,
  12505. A_SUB:
  12506. carryadd_opcode:=A_SBB;
  12507. else
  12508. InternalError(2021011002);
  12509. end;
  12510. Taicpu(hp1).ops:=2;
  12511. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12512. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12513. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12514. else
  12515. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12516. Taicpu(hp1).loadconst(0,0);
  12517. Taicpu(hp1).opcode:=carryadd_opcode;
  12518. RemoveCurrentP(p, hp1);
  12519. result:=true;
  12520. exit;
  12521. end
  12522. {
  12523. jcc @@1 setcc tmpreg
  12524. inc/dec/add/sub operand -> (movzx tmpreg)
  12525. @@1: add/sub tmpreg,operand
  12526. While this increases code size slightly, it makes the code much faster if the
  12527. jump is unpredictable
  12528. }
  12529. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12530. begin
  12531. { search for an available register which is volatile }
  12532. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12533. if increg <> NR_NO then
  12534. begin
  12535. { We don't need to check if tmpreg is in hp1 or not, because
  12536. it will be marked as in use at p (if not, this is
  12537. indictive of a compiler bug). }
  12538. TAsmLabel(symbol).decrefs;
  12539. Taicpu(p).clearop(0);
  12540. Taicpu(p).ops:=1;
  12541. Taicpu(p).is_jmp:=false;
  12542. Taicpu(p).opcode:=A_SETcc;
  12543. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12544. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12545. Taicpu(p).loadreg(0,increg);
  12546. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12547. begin
  12548. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12549. R_SUBW:
  12550. begin
  12551. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12552. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12553. end;
  12554. R_SUBD:
  12555. begin
  12556. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12557. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12558. end;
  12559. {$ifdef x86_64}
  12560. R_SUBQ:
  12561. begin
  12562. { MOVZX doesn't have a 64-bit variant, because
  12563. the 32-bit version implicitly zeroes the
  12564. upper 32-bits of the destination register }
  12565. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12566. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12567. setsubreg(tmpreg, R_SUBQ);
  12568. end;
  12569. {$endif x86_64}
  12570. else
  12571. Internalerror(2020030601);
  12572. end;
  12573. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12574. asml.InsertAfter(hp2,p);
  12575. end
  12576. else
  12577. tmpreg := increg;
  12578. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12579. begin
  12580. Taicpu(hp1).ops:=2;
  12581. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12582. end;
  12583. Taicpu(hp1).loadreg(0,tmpreg);
  12584. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12585. Result := True;
  12586. { p is no longer a Jcc instruction, so exit }
  12587. Exit;
  12588. end;
  12589. end;
  12590. end;
  12591. { Detect the following:
  12592. jmp<cond> @Lbl1
  12593. jmp @Lbl2
  12594. ...
  12595. @Lbl1:
  12596. ret
  12597. Change to:
  12598. jmp<inv_cond> @Lbl2
  12599. ret
  12600. }
  12601. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12602. begin
  12603. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12604. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12605. MatchInstruction(hp2,A_RET,[S_NO]) then
  12606. begin
  12607. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12608. { Change label address to that of the unconditional jump }
  12609. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12610. TAsmLabel(symbol).DecRefs;
  12611. taicpu(hp1).opcode := A_RET;
  12612. taicpu(hp1).is_jmp := false;
  12613. taicpu(hp1).ops := taicpu(hp2).ops;
  12614. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12615. case taicpu(hp2).ops of
  12616. 0:
  12617. taicpu(hp1).clearop(0);
  12618. 1:
  12619. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12620. else
  12621. internalerror(2016041302);
  12622. end;
  12623. end;
  12624. {$ifndef i8086}
  12625. end
  12626. {
  12627. convert
  12628. j<c> .L1
  12629. mov 1,reg
  12630. jmp .L2
  12631. .L1
  12632. mov 0,reg
  12633. .L2
  12634. into
  12635. mov 0,reg
  12636. set<not(c)> reg
  12637. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12638. would destroy the flag contents
  12639. }
  12640. else if MatchInstruction(hp1,A_MOV,[]) and
  12641. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12642. {$ifdef i386}
  12643. (
  12644. { Under i386, ESI, EDI, EBP and ESP
  12645. don't have an 8-bit representation }
  12646. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12647. ) and
  12648. {$endif i386}
  12649. (taicpu(hp1).oper[0]^.val=1) and
  12650. GetNextInstruction(hp1,hp2) and
  12651. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12652. GetNextInstruction(hp2,hp3) and
  12653. (hp3.typ=ait_label) and
  12654. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12655. (tai_label(hp3).labsym.getrefs=1) and
  12656. GetNextInstruction(hp3,hp4) and
  12657. MatchInstruction(hp4,A_MOV,[]) and
  12658. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12659. (taicpu(hp4).oper[0]^.val=0) and
  12660. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12661. GetNextInstruction(hp4,hp5) and
  12662. (hp5.typ=ait_label) and
  12663. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12664. (tai_label(hp5).labsym.getrefs=1) then
  12665. begin
  12666. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12667. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12668. { remove last label }
  12669. RemoveInstruction(hp5);
  12670. { remove second label }
  12671. RemoveInstruction(hp3);
  12672. { remove jmp }
  12673. RemoveInstruction(hp2);
  12674. if taicpu(hp1).opsize=S_B then
  12675. RemoveInstruction(hp1)
  12676. else
  12677. taicpu(hp1).loadconst(0,0);
  12678. taicpu(hp4).opcode:=A_SETcc;
  12679. taicpu(hp4).opsize:=S_B;
  12680. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12681. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12682. taicpu(hp4).opercnt:=1;
  12683. taicpu(hp4).ops:=1;
  12684. taicpu(hp4).freeop(1);
  12685. RemoveCurrentP(p);
  12686. Result:=true;
  12687. exit;
  12688. end
  12689. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12690. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12691. begin
  12692. { check for
  12693. jCC xxx
  12694. <several movs>
  12695. xxx:
  12696. Also spot:
  12697. Jcc xxx
  12698. <several movs>
  12699. jmp xxx
  12700. Change to:
  12701. <several cmovs with inverted condition>
  12702. jmp xxx (only for the 2nd case)
  12703. }
  12704. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12705. if CMOVTracking^.State <> tsInvalid then
  12706. begin
  12707. CMovTracking^.Process(p);
  12708. Result := True;
  12709. end;
  12710. CMOVTracking^.Done;
  12711. {$endif i8086}
  12712. end;
  12713. end;
  12714. end;
  12715. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12716. var
  12717. hp1,hp2,hp3: tai;
  12718. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12719. NewSize: TOpSize;
  12720. NewRegSize: TSubRegister;
  12721. Limit: TCgInt;
  12722. SwapOper: POper;
  12723. begin
  12724. result:=false;
  12725. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12726. GetNextInstruction(p,hp1) and
  12727. (hp1.typ = ait_instruction);
  12728. if reg_and_hp1_is_instr and
  12729. (
  12730. (taicpu(hp1).opcode <> A_LEA) or
  12731. { If the LEA instruction can be converted into an arithmetic instruction,
  12732. it may be possible to then fold it. }
  12733. (
  12734. { If the flags register is in use, don't change the instruction
  12735. to an ADD otherwise this will scramble the flags. [Kit] }
  12736. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12737. ConvertLEA(taicpu(hp1))
  12738. )
  12739. ) and
  12740. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12741. GetNextInstruction(hp1,hp2) and
  12742. MatchInstruction(hp2,A_MOV,[]) and
  12743. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12744. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12745. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12746. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12747. {$ifdef i386}
  12748. { not all registers have byte size sub registers on i386 }
  12749. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12750. {$endif i386}
  12751. (((taicpu(hp1).ops=2) and
  12752. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12753. ((taicpu(hp1).ops=1) and
  12754. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12755. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12756. begin
  12757. { change movsX/movzX reg/ref, reg2
  12758. add/sub/or/... reg3/$const, reg2
  12759. mov reg2 reg/ref
  12760. to add/sub/or/... reg3/$const, reg/ref }
  12761. { by example:
  12762. movswl %si,%eax movswl %si,%eax p
  12763. decl %eax addl %edx,%eax hp1
  12764. movw %ax,%si movw %ax,%si hp2
  12765. ->
  12766. movswl %si,%eax movswl %si,%eax p
  12767. decw %eax addw %edx,%eax hp1
  12768. movw %ax,%si movw %ax,%si hp2
  12769. }
  12770. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12771. {
  12772. ->
  12773. movswl %si,%eax movswl %si,%eax p
  12774. decw %si addw %dx,%si hp1
  12775. movw %ax,%si movw %ax,%si hp2
  12776. }
  12777. case taicpu(hp1).ops of
  12778. 1:
  12779. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12780. 2:
  12781. begin
  12782. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12783. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12784. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12785. end;
  12786. else
  12787. internalerror(2008042702);
  12788. end;
  12789. {
  12790. ->
  12791. decw %si addw %dx,%si p
  12792. }
  12793. DebugMsg(SPeepholeOptimization + 'var3',p);
  12794. RemoveCurrentP(p, hp1);
  12795. RemoveInstruction(hp2);
  12796. Result := True;
  12797. Exit;
  12798. end;
  12799. if reg_and_hp1_is_instr and
  12800. (taicpu(hp1).opcode = A_MOV) and
  12801. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12802. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12803. {$ifdef x86_64}
  12804. { check for implicit extension to 64 bit }
  12805. or
  12806. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12807. (taicpu(hp1).opsize=S_Q) and
  12808. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12809. )
  12810. {$endif x86_64}
  12811. )
  12812. then
  12813. begin
  12814. { change
  12815. movx %reg1,%reg2
  12816. mov %reg2,%reg3
  12817. dealloc %reg2
  12818. into
  12819. movx %reg,%reg3
  12820. }
  12821. TransferUsedRegs(TmpUsedRegs);
  12822. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12823. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12824. begin
  12825. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12826. {$ifdef x86_64}
  12827. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12828. (taicpu(hp1).opsize=S_Q) then
  12829. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12830. else
  12831. {$endif x86_64}
  12832. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12833. RemoveInstruction(hp1);
  12834. Result := True;
  12835. Exit;
  12836. end;
  12837. end;
  12838. if reg_and_hp1_is_instr and
  12839. ((taicpu(hp1).opcode=A_MOV) or
  12840. (taicpu(hp1).opcode=A_ADD) or
  12841. (taicpu(hp1).opcode=A_SUB) or
  12842. (taicpu(hp1).opcode=A_CMP) or
  12843. (taicpu(hp1).opcode=A_OR) or
  12844. (taicpu(hp1).opcode=A_XOR) or
  12845. (taicpu(hp1).opcode=A_AND)
  12846. ) and
  12847. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12848. begin
  12849. AndTest := (taicpu(hp1).opcode=A_AND) and
  12850. GetNextInstruction(hp1, hp2) and
  12851. (hp2.typ = ait_instruction) and
  12852. (
  12853. (
  12854. (taicpu(hp2).opcode=A_TEST) and
  12855. (
  12856. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12857. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12858. (
  12859. { If the AND and TEST instructions share a constant, this is also valid }
  12860. (taicpu(hp1).oper[0]^.typ = top_const) and
  12861. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12862. )
  12863. ) and
  12864. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12865. ) or
  12866. (
  12867. (taicpu(hp2).opcode=A_CMP) and
  12868. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12869. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12870. )
  12871. );
  12872. { change
  12873. movx (oper),%reg2
  12874. and $x,%reg2
  12875. test %reg2,%reg2
  12876. dealloc %reg2
  12877. into
  12878. op %reg1,%reg3
  12879. if the second op accesses only the bits stored in reg1
  12880. }
  12881. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12882. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12883. (taicpu(hp1).oper[0]^.typ = top_const) and
  12884. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12885. AndTest then
  12886. begin
  12887. { Check if the AND constant is in range }
  12888. case taicpu(p).opsize of
  12889. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12890. begin
  12891. NewSize := S_B;
  12892. Limit := $FF;
  12893. end;
  12894. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12895. begin
  12896. NewSize := S_W;
  12897. Limit := $FFFF;
  12898. end;
  12899. {$ifdef x86_64}
  12900. S_LQ:
  12901. begin
  12902. NewSize := S_L;
  12903. Limit := $FFFFFFFF;
  12904. end;
  12905. {$endif x86_64}
  12906. else
  12907. InternalError(2021120303);
  12908. end;
  12909. if (
  12910. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12911. { Check for negative operands }
  12912. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12913. ) and
  12914. GetNextInstruction(hp2,hp3) and
  12915. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12916. (taicpu(hp3).condition in [C_E,C_NE]) then
  12917. begin
  12918. TransferUsedRegs(TmpUsedRegs);
  12919. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12920. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12921. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12922. begin
  12923. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12924. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12925. taicpu(hp1).opcode := A_TEST;
  12926. taicpu(hp1).opsize := NewSize;
  12927. RemoveInstruction(hp2);
  12928. RemoveCurrentP(p, hp1);
  12929. Result:=true;
  12930. exit;
  12931. end;
  12932. end;
  12933. end;
  12934. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12935. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12936. (taicpu(hp1).opsize=S_B)) or
  12937. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12938. (taicpu(hp1).opsize=S_W))
  12939. {$ifdef x86_64}
  12940. or ((taicpu(p).opsize=S_LQ) and
  12941. (taicpu(hp1).opsize=S_L))
  12942. {$endif x86_64}
  12943. ) and
  12944. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12945. begin
  12946. { change
  12947. movx %reg1,%reg2
  12948. op %reg2,%reg3
  12949. dealloc %reg2
  12950. into
  12951. op %reg1,%reg3
  12952. if the second op accesses only the bits stored in reg1
  12953. }
  12954. TransferUsedRegs(TmpUsedRegs);
  12955. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12956. if AndTest then
  12957. begin
  12958. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12959. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12960. end
  12961. else
  12962. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12963. if not RegUsed then
  12964. begin
  12965. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12966. if taicpu(p).oper[0]^.typ=top_reg then
  12967. begin
  12968. case taicpu(hp1).opsize of
  12969. S_B:
  12970. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12971. S_W:
  12972. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12973. S_L:
  12974. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12975. else
  12976. Internalerror(2020102301);
  12977. end;
  12978. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12979. end
  12980. else
  12981. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12982. RemoveCurrentP(p);
  12983. if AndTest then
  12984. RemoveInstruction(hp2);
  12985. result:=true;
  12986. exit;
  12987. end;
  12988. end
  12989. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12990. (
  12991. { Bitwise operations only }
  12992. (taicpu(hp1).opcode=A_AND) or
  12993. (taicpu(hp1).opcode=A_TEST) or
  12994. (
  12995. (taicpu(hp1).oper[0]^.typ = top_const) and
  12996. (
  12997. (taicpu(hp1).opcode=A_OR) or
  12998. (taicpu(hp1).opcode=A_XOR)
  12999. )
  13000. )
  13001. ) and
  13002. (
  13003. (taicpu(hp1).oper[0]^.typ = top_const) or
  13004. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  13005. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13006. ) then
  13007. begin
  13008. { change
  13009. movx %reg2,%reg2
  13010. op const,%reg2
  13011. into
  13012. op const,%reg2 (smaller version)
  13013. movx %reg2,%reg2
  13014. also change
  13015. movx %reg1,%reg2
  13016. and/test (oper),%reg2
  13017. dealloc %reg2
  13018. into
  13019. and/test (oper),%reg1
  13020. }
  13021. case taicpu(p).opsize of
  13022. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13023. begin
  13024. NewSize := S_B;
  13025. NewRegSize := R_SUBL;
  13026. Limit := $FF;
  13027. end;
  13028. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13029. begin
  13030. NewSize := S_W;
  13031. NewRegSize := R_SUBW;
  13032. Limit := $FFFF;
  13033. end;
  13034. {$ifdef x86_64}
  13035. S_LQ:
  13036. begin
  13037. NewSize := S_L;
  13038. NewRegSize := R_SUBD;
  13039. Limit := $FFFFFFFF;
  13040. end;
  13041. {$endif x86_64}
  13042. else
  13043. Internalerror(2021120302);
  13044. end;
  13045. TransferUsedRegs(TmpUsedRegs);
  13046. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13047. if AndTest then
  13048. begin
  13049. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13050. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13051. end
  13052. else
  13053. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13054. if
  13055. (
  13056. (taicpu(p).opcode = A_MOVZX) and
  13057. (
  13058. (taicpu(hp1).opcode=A_AND) or
  13059. (taicpu(hp1).opcode=A_TEST)
  13060. ) and
  13061. not (
  13062. { If both are references, then the final instruction will have
  13063. both operands as references, which is not allowed }
  13064. (taicpu(p).oper[0]^.typ = top_ref) and
  13065. (taicpu(hp1).oper[0]^.typ = top_ref)
  13066. ) and
  13067. not RegUsed
  13068. ) or
  13069. (
  13070. (
  13071. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13072. not RegUsed
  13073. ) and
  13074. (taicpu(p).oper[0]^.typ = top_reg) and
  13075. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13076. (taicpu(hp1).oper[0]^.typ = top_const) and
  13077. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13078. ) then
  13079. begin
  13080. {$if defined(i386) or defined(i8086)}
  13081. { If the target size is 8-bit, make sure we can actually encode it }
  13082. 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
  13083. Exit;
  13084. {$endif i386 or i8086}
  13085. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13086. taicpu(hp1).opsize := NewSize;
  13087. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13088. if AndTest then
  13089. begin
  13090. RemoveInstruction(hp2);
  13091. if not RegUsed then
  13092. begin
  13093. taicpu(hp1).opcode := A_TEST;
  13094. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13095. begin
  13096. { Make sure the reference is the second operand }
  13097. SwapOper := taicpu(hp1).oper[0];
  13098. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13099. taicpu(hp1).oper[1] := SwapOper;
  13100. end;
  13101. end;
  13102. end;
  13103. case taicpu(hp1).oper[0]^.typ of
  13104. top_reg:
  13105. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13106. top_const:
  13107. { For the AND/TEST case }
  13108. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13109. else
  13110. ;
  13111. end;
  13112. if RegUsed then
  13113. begin
  13114. AsmL.Remove(p);
  13115. AsmL.InsertAfter(p, hp1);
  13116. p := hp1;
  13117. end
  13118. else
  13119. RemoveCurrentP(p, hp1);
  13120. result:=true;
  13121. exit;
  13122. end;
  13123. end;
  13124. end;
  13125. if reg_and_hp1_is_instr and
  13126. (taicpu(p).oper[0]^.typ = top_reg) and
  13127. (
  13128. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13129. ) and
  13130. (taicpu(hp1).oper[0]^.typ = top_const) and
  13131. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13132. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13133. { Minimum shift value allowed is the bit difference between the sizes }
  13134. (taicpu(hp1).oper[0]^.val >=
  13135. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13136. 8 * (
  13137. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13138. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13139. )
  13140. ) then
  13141. begin
  13142. { For:
  13143. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13144. shl/sal ##, %reg1
  13145. Remove the movsx/movzx instruction if the shift overwrites the
  13146. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13147. }
  13148. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13149. RemoveCurrentP(p, hp1);
  13150. Result := True;
  13151. Exit;
  13152. end
  13153. else if reg_and_hp1_is_instr and
  13154. (taicpu(p).oper[0]^.typ = top_reg) and
  13155. (
  13156. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13157. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13158. ) and
  13159. (taicpu(hp1).oper[0]^.typ = top_const) and
  13160. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13161. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13162. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13163. (taicpu(hp1).oper[0]^.val <
  13164. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13165. 8 * (
  13166. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13167. )
  13168. ) then
  13169. begin
  13170. { For:
  13171. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13172. sar ##, %reg1 shr ##, %reg1
  13173. Move the shift to before the movx instruction if the shift value
  13174. is not too large.
  13175. }
  13176. asml.Remove(hp1);
  13177. asml.InsertBefore(hp1, p);
  13178. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13179. case taicpu(p).opsize of
  13180. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13181. taicpu(hp1).opsize := S_B;
  13182. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13183. taicpu(hp1).opsize := S_W;
  13184. {$ifdef x86_64}
  13185. S_LQ:
  13186. taicpu(hp1).opsize := S_L;
  13187. {$endif}
  13188. else
  13189. InternalError(2020112401);
  13190. end;
  13191. if (taicpu(hp1).opcode = A_SHR) then
  13192. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13193. else
  13194. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13195. Result := True;
  13196. end;
  13197. if reg_and_hp1_is_instr and
  13198. (taicpu(p).oper[0]^.typ = top_reg) and
  13199. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13200. (
  13201. (taicpu(hp1).opcode = taicpu(p).opcode)
  13202. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13203. {$ifdef x86_64}
  13204. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13205. {$endif x86_64}
  13206. ) then
  13207. begin
  13208. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13209. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13210. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13211. begin
  13212. {
  13213. For example:
  13214. movzbw %al,%ax
  13215. movzwl %ax,%eax
  13216. Compress into:
  13217. movzbl %al,%eax
  13218. }
  13219. RegUsed := False;
  13220. case taicpu(p).opsize of
  13221. S_BW:
  13222. case taicpu(hp1).opsize of
  13223. S_WL:
  13224. begin
  13225. taicpu(p).opsize := S_BL;
  13226. RegUsed := True;
  13227. end;
  13228. {$ifdef x86_64}
  13229. S_WQ:
  13230. begin
  13231. if taicpu(p).opcode = A_MOVZX then
  13232. begin
  13233. taicpu(p).opsize := S_BL;
  13234. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13235. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13236. end
  13237. else
  13238. taicpu(p).opsize := S_BQ;
  13239. RegUsed := True;
  13240. end;
  13241. {$endif x86_64}
  13242. else
  13243. ;
  13244. end;
  13245. {$ifdef x86_64}
  13246. S_BL:
  13247. case taicpu(hp1).opsize of
  13248. S_LQ:
  13249. begin
  13250. if taicpu(p).opcode = A_MOVZX then
  13251. begin
  13252. taicpu(p).opsize := S_BL;
  13253. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13254. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13255. end
  13256. else
  13257. taicpu(p).opsize := S_BQ;
  13258. RegUsed := True;
  13259. end;
  13260. else
  13261. ;
  13262. end;
  13263. S_WL:
  13264. case taicpu(hp1).opsize of
  13265. S_LQ:
  13266. begin
  13267. if taicpu(p).opcode = A_MOVZX then
  13268. begin
  13269. taicpu(p).opsize := S_WL;
  13270. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13271. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13272. end
  13273. else
  13274. taicpu(p).opsize := S_WQ;
  13275. RegUsed := True;
  13276. end;
  13277. else
  13278. ;
  13279. end;
  13280. {$endif x86_64}
  13281. else
  13282. ;
  13283. end;
  13284. if RegUsed then
  13285. begin
  13286. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13287. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13288. RemoveInstruction(hp1);
  13289. Result := True;
  13290. Exit;
  13291. end;
  13292. end;
  13293. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13294. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13295. GetNextInstruction(hp1, hp2) and
  13296. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13297. (
  13298. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13299. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13300. {$ifdef x86_64}
  13301. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13302. {$endif x86_64}
  13303. ) and
  13304. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13305. (
  13306. (
  13307. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13308. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13309. ) or
  13310. (
  13311. { Only allow the operands in reverse order for TEST instructions }
  13312. (taicpu(hp2).opcode = A_TEST) and
  13313. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13314. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13315. )
  13316. ) then
  13317. begin
  13318. {
  13319. For example:
  13320. movzbl %al,%eax
  13321. movzbl (ref),%edx
  13322. andl %edx,%eax
  13323. (%edx deallocated)
  13324. Change to:
  13325. andb (ref),%al
  13326. movzbl %al,%eax
  13327. Rules are:
  13328. - First two instructions have the same opcode and opsize
  13329. - First instruction's operands are the same super-register
  13330. - Second instruction operates on a different register
  13331. - Third instruction is AND, OR, XOR or TEST
  13332. - Third instruction's operands are the destination registers of the first two instructions
  13333. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13334. - Second instruction's destination register is deallocated afterwards
  13335. }
  13336. TransferUsedRegs(TmpUsedRegs);
  13337. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13338. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13339. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13340. begin
  13341. case taicpu(p).opsize of
  13342. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13343. NewSize := S_B;
  13344. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13345. NewSize := S_W;
  13346. {$ifdef x86_64}
  13347. S_LQ:
  13348. NewSize := S_L;
  13349. {$endif x86_64}
  13350. else
  13351. InternalError(2021120301);
  13352. end;
  13353. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13354. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13355. taicpu(hp2).opsize := NewSize;
  13356. RemoveInstruction(hp1);
  13357. { With TEST, it's best to keep the MOVX instruction at the top }
  13358. if (taicpu(hp2).opcode <> A_TEST) then
  13359. begin
  13360. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13361. asml.Remove(p);
  13362. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13363. asml.InsertAfter(p, hp2);
  13364. p := hp2;
  13365. end
  13366. else
  13367. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13368. Result := True;
  13369. Exit;
  13370. end;
  13371. end;
  13372. end;
  13373. if taicpu(p).opcode=A_MOVZX then
  13374. begin
  13375. { removes superfluous And's after movzx's }
  13376. if reg_and_hp1_is_instr and
  13377. (taicpu(hp1).opcode = A_AND) and
  13378. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13379. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13380. {$ifdef x86_64}
  13381. { check for implicit extension to 64 bit }
  13382. or
  13383. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13384. (taicpu(hp1).opsize=S_Q) and
  13385. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13386. )
  13387. {$endif x86_64}
  13388. )
  13389. then
  13390. begin
  13391. case taicpu(p).opsize Of
  13392. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13393. if (taicpu(hp1).oper[0]^.val = $ff) then
  13394. begin
  13395. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13396. RemoveInstruction(hp1);
  13397. Result:=true;
  13398. exit;
  13399. end;
  13400. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13401. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13402. begin
  13403. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13404. RemoveInstruction(hp1);
  13405. Result:=true;
  13406. exit;
  13407. end;
  13408. {$ifdef x86_64}
  13409. S_LQ:
  13410. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13411. begin
  13412. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13413. RemoveInstruction(hp1);
  13414. Result:=true;
  13415. exit;
  13416. end;
  13417. {$endif x86_64}
  13418. else
  13419. ;
  13420. end;
  13421. { we cannot get rid of the and, but can we get rid of the movz ?}
  13422. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13423. begin
  13424. case taicpu(p).opsize Of
  13425. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13426. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13427. begin
  13428. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13429. RemoveCurrentP(p,hp1);
  13430. Result:=true;
  13431. exit;
  13432. end;
  13433. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13434. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13435. begin
  13436. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13437. RemoveCurrentP(p,hp1);
  13438. Result:=true;
  13439. exit;
  13440. end;
  13441. {$ifdef x86_64}
  13442. S_LQ:
  13443. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13444. begin
  13445. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13446. RemoveCurrentP(p,hp1);
  13447. Result:=true;
  13448. exit;
  13449. end;
  13450. {$endif x86_64}
  13451. else
  13452. ;
  13453. end;
  13454. end;
  13455. end;
  13456. { changes some movzx constructs to faster synonyms (all examples
  13457. are given with eax/ax, but are also valid for other registers)}
  13458. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13459. begin
  13460. case taicpu(p).opsize of
  13461. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13462. (the machine code is equivalent to movzbl %al,%eax), but the
  13463. code generator still generates that assembler instruction and
  13464. it is silently converted. This should probably be checked.
  13465. [Kit] }
  13466. S_BW:
  13467. begin
  13468. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13469. (
  13470. not IsMOVZXAcceptable
  13471. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13472. or (
  13473. (cs_opt_size in current_settings.optimizerswitches) and
  13474. (taicpu(p).oper[1]^.reg = NR_AX)
  13475. )
  13476. ) then
  13477. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13478. begin
  13479. DebugMsg(SPeepholeOptimization + 'var7',p);
  13480. taicpu(p).opcode := A_AND;
  13481. taicpu(p).changeopsize(S_W);
  13482. taicpu(p).loadConst(0,$ff);
  13483. Result := True;
  13484. end
  13485. else if not IsMOVZXAcceptable and
  13486. GetNextInstruction(p, hp1) and
  13487. (tai(hp1).typ = ait_instruction) and
  13488. (taicpu(hp1).opcode = A_AND) and
  13489. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13490. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13491. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13492. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13493. begin
  13494. DebugMsg(SPeepholeOptimization + 'var8',p);
  13495. taicpu(p).opcode := A_MOV;
  13496. taicpu(p).changeopsize(S_W);
  13497. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13498. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13499. Result := True;
  13500. end;
  13501. end;
  13502. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13503. S_BL:
  13504. if not IsMOVZXAcceptable then
  13505. begin
  13506. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13507. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13508. begin
  13509. DebugMsg(SPeepholeOptimization + 'var9',p);
  13510. taicpu(p).opcode := A_AND;
  13511. taicpu(p).changeopsize(S_L);
  13512. taicpu(p).loadConst(0,$ff);
  13513. Result := True;
  13514. end
  13515. else if GetNextInstruction(p, hp1) and
  13516. (tai(hp1).typ = ait_instruction) and
  13517. (taicpu(hp1).opcode = A_AND) and
  13518. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13519. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13520. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13521. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13522. begin
  13523. DebugMsg(SPeepholeOptimization + 'var10',p);
  13524. taicpu(p).opcode := A_MOV;
  13525. taicpu(p).changeopsize(S_L);
  13526. { do not use R_SUBWHOLE
  13527. as movl %rdx,%eax
  13528. is invalid in assembler PM }
  13529. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13530. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13531. Result := True;
  13532. end;
  13533. end;
  13534. {$endif i8086}
  13535. S_WL:
  13536. if not IsMOVZXAcceptable then
  13537. begin
  13538. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13539. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13540. begin
  13541. DebugMsg(SPeepholeOptimization + 'var11',p);
  13542. taicpu(p).opcode := A_AND;
  13543. taicpu(p).changeopsize(S_L);
  13544. taicpu(p).loadConst(0,$ffff);
  13545. Result := True;
  13546. end
  13547. else if GetNextInstruction(p, hp1) and
  13548. (tai(hp1).typ = ait_instruction) and
  13549. (taicpu(hp1).opcode = A_AND) and
  13550. (taicpu(hp1).oper[0]^.typ = top_const) and
  13551. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13552. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13553. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13554. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13555. begin
  13556. DebugMsg(SPeepholeOptimization + 'var12',p);
  13557. taicpu(p).opcode := A_MOV;
  13558. taicpu(p).changeopsize(S_L);
  13559. { do not use R_SUBWHOLE
  13560. as movl %rdx,%eax
  13561. is invalid in assembler PM }
  13562. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13563. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13564. Result := True;
  13565. end;
  13566. end;
  13567. else
  13568. InternalError(2017050705);
  13569. end;
  13570. end
  13571. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13572. begin
  13573. if GetNextInstruction(p, hp1) and
  13574. (tai(hp1).typ = ait_instruction) and
  13575. (taicpu(hp1).opcode = A_AND) and
  13576. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13577. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13578. begin
  13579. case taicpu(p).opsize Of
  13580. S_BL:
  13581. if (taicpu(hp1).opsize <> S_L) or
  13582. (taicpu(hp1).oper[0]^.val > $FF) then
  13583. begin
  13584. DebugMsg(SPeepholeOptimization + 'var13',p);
  13585. taicpu(hp1).changeopsize(S_L);
  13586. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13587. Include(OptsToCheck, aoc_ForceNewIteration);
  13588. end;
  13589. S_WL:
  13590. if (taicpu(hp1).opsize <> S_L) or
  13591. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13592. begin
  13593. DebugMsg(SPeepholeOptimization + 'var14',p);
  13594. taicpu(hp1).changeopsize(S_L);
  13595. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13596. Include(OptsToCheck, aoc_ForceNewIteration);
  13597. end;
  13598. S_BW:
  13599. if (taicpu(hp1).opsize <> S_W) or
  13600. (taicpu(hp1).oper[0]^.val > $FF) then
  13601. begin
  13602. DebugMsg(SPeepholeOptimization + 'var15',p);
  13603. taicpu(hp1).changeopsize(S_W);
  13604. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13605. Include(OptsToCheck, aoc_ForceNewIteration);
  13606. end;
  13607. else
  13608. Internalerror(2017050704)
  13609. end;
  13610. end;
  13611. end;
  13612. end;
  13613. end;
  13614. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13615. var
  13616. hp1, hp2 : tai;
  13617. MaskLength : Cardinal;
  13618. MaskedBits : TCgInt;
  13619. ActiveReg : TRegister;
  13620. begin
  13621. Result:=false;
  13622. { There are no optimisations for reference targets }
  13623. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13624. Exit;
  13625. while GetNextInstruction(p, hp1) and
  13626. (hp1.typ = ait_instruction) do
  13627. begin
  13628. if (taicpu(p).oper[0]^.typ = top_const) then
  13629. begin
  13630. case taicpu(hp1).opcode of
  13631. A_AND:
  13632. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13633. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13634. { the second register must contain the first one, so compare their subreg types }
  13635. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13636. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13637. { change
  13638. and const1, reg
  13639. and const2, reg
  13640. to
  13641. and (const1 and const2), reg
  13642. }
  13643. begin
  13644. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13645. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13646. RemoveCurrentP(p, hp1);
  13647. Result:=true;
  13648. exit;
  13649. end;
  13650. A_CMP:
  13651. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13652. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13653. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13654. { Just check that the condition on the next instruction is compatible }
  13655. GetNextInstruction(hp1, hp2) and
  13656. (hp2.typ = ait_instruction) and
  13657. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13658. then
  13659. { change
  13660. and 2^n, reg
  13661. cmp 2^n, reg
  13662. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13663. to
  13664. and 2^n, reg
  13665. test reg, reg
  13666. j(~c) / set(~c) / cmov(~c)
  13667. }
  13668. begin
  13669. { Keep TEST instruction in, rather than remove it, because
  13670. it may trigger other optimisations such as MovAndTest2Test }
  13671. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13672. taicpu(hp1).opcode := A_TEST;
  13673. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13674. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13675. Result := True;
  13676. Exit;
  13677. end
  13678. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13679. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13680. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13681. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13682. { change
  13683. and $ff/$ff/$ffff, reg
  13684. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13685. dealloc reg
  13686. to
  13687. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13688. }
  13689. begin
  13690. TransferUsedRegs(TmpUsedRegs);
  13691. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13692. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13693. begin
  13694. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13695. case taicpu(p).oper[0]^.val of
  13696. $ff:
  13697. begin
  13698. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13699. taicpu(hp1).opsize:=S_B;
  13700. end;
  13701. $ffff:
  13702. begin
  13703. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13704. taicpu(hp1).opsize:=S_W;
  13705. end;
  13706. $ffffffff:
  13707. begin
  13708. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13709. taicpu(hp1).opsize:=S_L;
  13710. end;
  13711. else
  13712. Internalerror(2023030401);
  13713. end;
  13714. RemoveCurrentP(p);
  13715. Result := True;
  13716. Exit;
  13717. end;
  13718. end;
  13719. A_MOVZX:
  13720. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13721. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13722. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13723. (
  13724. (
  13725. (taicpu(p).opsize=S_W) and
  13726. (taicpu(hp1).opsize=S_BW)
  13727. ) or
  13728. (
  13729. (taicpu(p).opsize=S_L) and
  13730. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13731. )
  13732. {$ifdef x86_64}
  13733. or
  13734. (
  13735. (taicpu(p).opsize=S_Q) and
  13736. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13737. )
  13738. {$endif x86_64}
  13739. ) then
  13740. begin
  13741. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13742. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13743. ) or
  13744. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13745. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13746. then
  13747. begin
  13748. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13749. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13750. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13751. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13752. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13753. }
  13754. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13755. RemoveInstruction(hp1);
  13756. { See if there are other optimisations possible }
  13757. Continue;
  13758. end;
  13759. end;
  13760. A_SHL:
  13761. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13762. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13763. begin
  13764. {$ifopt R+}
  13765. {$define RANGE_WAS_ON}
  13766. {$R-}
  13767. {$endif}
  13768. { get length of potential and mask }
  13769. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13770. { really a mask? }
  13771. {$ifdef RANGE_WAS_ON}
  13772. {$R+}
  13773. {$endif}
  13774. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13775. { unmasked part shifted out? }
  13776. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13777. begin
  13778. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13779. RemoveCurrentP(p, hp1);
  13780. Result:=true;
  13781. exit;
  13782. end;
  13783. end;
  13784. A_SHR:
  13785. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13786. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13787. (taicpu(hp1).oper[0]^.val <= 63) then
  13788. begin
  13789. { Does SHR combined with the AND cover all the bits?
  13790. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13791. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13792. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13793. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13794. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13795. begin
  13796. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13797. RemoveCurrentP(p, hp1);
  13798. Result := True;
  13799. Exit;
  13800. end;
  13801. end;
  13802. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13803. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13804. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13805. begin
  13806. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13807. (
  13808. (
  13809. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13810. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13811. ) or (
  13812. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13813. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13814. {$ifdef x86_64}
  13815. ) or (
  13816. (taicpu(hp1).opsize = S_LQ) and
  13817. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13818. {$endif x86_64}
  13819. )
  13820. ) then
  13821. begin
  13822. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13823. begin
  13824. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13825. RemoveInstruction(hp1);
  13826. { See if there are other optimisations possible }
  13827. Continue;
  13828. end;
  13829. { The super-registers are the same though.
  13830. Note that this change by itself doesn't improve
  13831. code speed, but it opens up other optimisations. }
  13832. {$ifdef x86_64}
  13833. { Convert 64-bit register to 32-bit }
  13834. case taicpu(hp1).opsize of
  13835. S_BQ:
  13836. begin
  13837. taicpu(hp1).opsize := S_BL;
  13838. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13839. end;
  13840. S_WQ:
  13841. begin
  13842. taicpu(hp1).opsize := S_WL;
  13843. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13844. end
  13845. else
  13846. ;
  13847. end;
  13848. {$endif x86_64}
  13849. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13850. taicpu(hp1).opcode := A_MOVZX;
  13851. { See if there are other optimisations possible }
  13852. Continue;
  13853. end;
  13854. end;
  13855. else
  13856. ;
  13857. end;
  13858. end
  13859. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13860. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13861. begin
  13862. {$ifdef x86_64}
  13863. if (taicpu(p).opsize = S_Q) then
  13864. begin
  13865. { Never necessary }
  13866. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13867. RemoveCurrentP(p, hp1);
  13868. Result := True;
  13869. Exit;
  13870. end;
  13871. {$endif x86_64}
  13872. { Forward check to determine necessity of and %reg,%reg }
  13873. TransferUsedRegs(TmpUsedRegs);
  13874. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13875. { Saves on a bunch of dereferences }
  13876. ActiveReg := taicpu(p).oper[1]^.reg;
  13877. case taicpu(hp1).opcode of
  13878. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13879. if (
  13880. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13881. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13882. ) and
  13883. (
  13884. (taicpu(hp1).opcode <> A_MOV) or
  13885. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13886. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13887. ) and
  13888. not (
  13889. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13890. (taicpu(hp1).opcode = A_MOV) and
  13891. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13892. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13893. ) and
  13894. (
  13895. (
  13896. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13897. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13898. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13899. ) or
  13900. (
  13901. {$ifdef x86_64}
  13902. (
  13903. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13904. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13905. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13906. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13907. ) and
  13908. {$endif x86_64}
  13909. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13910. )
  13911. ) then
  13912. begin
  13913. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13914. RemoveCurrentP(p, hp1);
  13915. Result := True;
  13916. Exit;
  13917. end;
  13918. A_ADD,
  13919. A_AND,
  13920. A_BSF,
  13921. A_BSR,
  13922. A_BTC,
  13923. A_BTR,
  13924. A_BTS,
  13925. A_OR,
  13926. A_SUB,
  13927. A_XOR:
  13928. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13929. if (
  13930. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13931. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13932. ) and
  13933. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13934. begin
  13935. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13936. RemoveCurrentP(p, hp1);
  13937. Result := True;
  13938. Exit;
  13939. end;
  13940. A_CMP,
  13941. A_TEST:
  13942. if (
  13943. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13944. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13945. ) and
  13946. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13947. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13948. begin
  13949. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13950. RemoveCurrentP(p, hp1);
  13951. Result := True;
  13952. Exit;
  13953. end;
  13954. A_BSWAP,
  13955. A_NEG,
  13956. A_NOT:
  13957. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13958. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13959. begin
  13960. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13961. RemoveCurrentP(p, hp1);
  13962. Result := True;
  13963. Exit;
  13964. end;
  13965. else
  13966. ;
  13967. end;
  13968. end;
  13969. if (taicpu(hp1).is_jmp) and
  13970. (taicpu(hp1).opcode<>A_JMP) and
  13971. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13972. begin
  13973. { change
  13974. and x, reg
  13975. jxx
  13976. to
  13977. test x, reg
  13978. jxx
  13979. if reg is deallocated before the
  13980. jump, but only if it's a conditional jump (PFV)
  13981. }
  13982. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13983. taicpu(p).opcode := A_TEST;
  13984. Exit;
  13985. end;
  13986. Break;
  13987. end;
  13988. { Lone AND tests }
  13989. if (taicpu(p).oper[0]^.typ = top_const) then
  13990. begin
  13991. {
  13992. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13993. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13994. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13995. }
  13996. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13997. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13998. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13999. begin
  14000. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  14001. if taicpu(p).opsize = S_L then
  14002. begin
  14003. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  14004. Result := True;
  14005. end;
  14006. end;
  14007. end;
  14008. { Backward check to determine necessity of and %reg,%reg }
  14009. if (taicpu(p).oper[0]^.typ = top_reg) and
  14010. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  14011. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14012. GetLastInstruction(p, hp2) and
  14013. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  14014. { Check size of adjacent instruction to determine if the AND is
  14015. effectively a null operation }
  14016. (
  14017. (taicpu(p).opsize = taicpu(hp2).opsize) or
  14018. { Note: Don't include S_Q }
  14019. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  14020. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  14021. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  14022. ) then
  14023. begin
  14024. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  14025. { If GetNextInstruction returned False, hp1 will be nil }
  14026. RemoveCurrentP(p, hp1);
  14027. Result := True;
  14028. Exit;
  14029. end;
  14030. end;
  14031. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14032. var
  14033. hp1, hp2: tai;
  14034. NewRef: TReference;
  14035. Distance: Cardinal;
  14036. TempTracking: TAllUsedRegs;
  14037. DoAddMov2Lea: Boolean;
  14038. { This entire nested function is used in an if-statement below, but we
  14039. want to avoid all the used reg transfers and GetNextInstruction calls
  14040. until we really have to check }
  14041. function MemRegisterNotUsedLater: Boolean; inline;
  14042. var
  14043. hp2: tai;
  14044. begin
  14045. TransferUsedRegs(TmpUsedRegs);
  14046. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14047. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14048. else
  14049. { p and hp1 will be adjacent }
  14050. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14051. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14052. end;
  14053. begin
  14054. Result := False;
  14055. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14056. (taicpu(p).oper[1]^.typ = top_reg) then
  14057. begin
  14058. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14059. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14060. (hp1.typ <> ait_instruction) or
  14061. not
  14062. (
  14063. (cs_opt_level3 in current_settings.optimizerswitches) or
  14064. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14065. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14066. ) then
  14067. Exit;
  14068. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14069. addq $x, %rax
  14070. movq %rax, %rdx
  14071. sarq $63, %rdx
  14072. (%rax still in use)
  14073. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14074. leaq $x(%rax),%rdx
  14075. addq $x, %rax
  14076. sarq $63, %rdx
  14077. ...which is okay since it breaks the dependency chain between
  14078. addq and movq, but if OptPass2MOV is called first:
  14079. addq $x, %rax
  14080. cqto
  14081. ...which is better in all ways, taking only 2 cycles to execute
  14082. and much smaller in code size.
  14083. }
  14084. { The extra register tracking is quite strenuous }
  14085. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14086. MatchInstruction(hp1, A_MOV, []) then
  14087. begin
  14088. { Update the register tracking to the MOV instruction }
  14089. CopyUsedRegs(TempTracking);
  14090. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14091. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14092. else
  14093. { p and hp1 will be adjacent }
  14094. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14095. hp2 := hp1;
  14096. if OptPass2MOV(hp1) then
  14097. Include(OptsToCheck, aoc_ForceNewIteration);
  14098. { Reset the tracking to the current instruction }
  14099. RestoreUsedRegs(TempTracking);
  14100. ReleaseUsedRegs(TempTracking);
  14101. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14102. OptPass2ADD get called again }
  14103. if (hp1 <> hp2) then
  14104. begin
  14105. Result := True;
  14106. Exit;
  14107. end;
  14108. end;
  14109. { Change:
  14110. add %reg2,%reg1
  14111. (%reg2 not modified in between)
  14112. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14113. To:
  14114. mov/s/z #(%reg1,%reg2),%reg1
  14115. }
  14116. if (taicpu(p).oper[0]^.typ = top_reg) and
  14117. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14118. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14119. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14120. (
  14121. (
  14122. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14123. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14124. { r/esp cannot be an index }
  14125. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14126. ) or (
  14127. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14128. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14129. )
  14130. ) and (
  14131. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14132. (
  14133. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14134. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14135. MemRegisterNotUsedLater
  14136. )
  14137. ) then
  14138. begin
  14139. if (
  14140. { Instructions are guaranteed to be adjacent on -O2 and under }
  14141. (cs_opt_level3 in current_settings.optimizerswitches) and
  14142. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14143. ) then
  14144. begin
  14145. { If the other register is used in between, move the MOV
  14146. instruction to right after the ADD instruction so a
  14147. saving can still be made }
  14148. Asml.Remove(hp1);
  14149. Asml.InsertAfter(hp1, p);
  14150. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14151. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14152. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14153. RemoveCurrentp(p, hp1);
  14154. end
  14155. else
  14156. begin
  14157. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14158. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14159. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14160. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14161. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14162. { hp1 may not be the immediate next instruction under -O3 }
  14163. RemoveCurrentp(p)
  14164. else
  14165. RemoveCurrentp(p, hp1);
  14166. end;
  14167. Result := True;
  14168. Exit;
  14169. end;
  14170. { Change:
  14171. addl/q $x,%reg1
  14172. movl/q %reg1,%reg2
  14173. To:
  14174. leal/q $x(%reg1),%reg2
  14175. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14176. Breaks the dependency chain.
  14177. }
  14178. if (taicpu(p).oper[0]^.typ = top_const) and
  14179. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14180. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14181. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14182. (
  14183. { Instructions are guaranteed to be adjacent on -O2 and under }
  14184. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14185. (
  14186. { If the flags are used, don't make the optimisation,
  14187. otherwise they will be scrambled. Fixes #41148 }
  14188. (
  14189. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14190. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14191. ) and
  14192. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14193. )
  14194. ) then
  14195. begin
  14196. TransferUsedRegs(TmpUsedRegs);
  14197. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14198. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14199. else
  14200. { p and hp1 will be adjacent }
  14201. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14202. if (
  14203. SetAndTest(
  14204. (
  14205. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14206. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14207. ),
  14208. DoAddMov2Lea
  14209. ) or
  14210. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14211. not (cs_opt_size in current_settings.optimizerswitches)
  14212. ) then
  14213. begin
  14214. { Change the MOV instruction to a LEA instruction, and update the
  14215. first operand }
  14216. reference_reset(NewRef, 1, []);
  14217. NewRef.base := taicpu(p).oper[1]^.reg;
  14218. NewRef.scalefactor := 1;
  14219. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14220. taicpu(hp1).opcode := A_LEA;
  14221. taicpu(hp1).loadref(0, NewRef);
  14222. if DoAddMov2Lea then
  14223. begin
  14224. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14225. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14226. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14227. { hp1 may not be the immediate next instruction under -O3 }
  14228. RemoveCurrentp(p)
  14229. else
  14230. RemoveCurrentp(p, hp1);
  14231. end
  14232. else
  14233. begin
  14234. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14235. { Move what is now the LEA instruction to before the ADD instruction }
  14236. Asml.Remove(hp1);
  14237. Asml.InsertBefore(hp1, p);
  14238. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14239. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14240. p := hp1;
  14241. end;
  14242. Result := True;
  14243. end;
  14244. end;
  14245. end;
  14246. end;
  14247. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14248. var
  14249. SubReg: TSubRegister;
  14250. hp1, hp2: tai;
  14251. CallJmp: Boolean;
  14252. begin
  14253. Result := False;
  14254. CallJmp := False;
  14255. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14256. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14257. with taicpu(p).oper[0]^.ref^ do
  14258. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14259. if (offset = 0) then
  14260. begin
  14261. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14262. begin
  14263. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14264. taicpu(p).opcode := A_ADD;
  14265. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14266. Result := True;
  14267. end
  14268. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14269. begin
  14270. if (base <> NR_NO) then
  14271. begin
  14272. if (scalefactor <= 1) then
  14273. begin
  14274. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14275. taicpu(p).opcode := A_ADD;
  14276. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14277. Result := True;
  14278. end;
  14279. end
  14280. else
  14281. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14282. if (scalefactor in [2, 4, 8]) then
  14283. begin
  14284. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14285. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14286. taicpu(p).opcode := A_SHL;
  14287. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14288. Result := True;
  14289. end;
  14290. end;
  14291. end
  14292. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14293. lot of latency, so break off the offset if %reg3 is used soon
  14294. afterwards }
  14295. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14296. { If 3-component addresses don't have additional latency, don't
  14297. perform this optimisation }
  14298. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14299. GetNextInstruction(p, hp1) and
  14300. (hp1.typ = ait_instruction) and
  14301. (
  14302. (
  14303. { Permit jumps and calls since they have a larger degree of overhead }
  14304. (
  14305. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14306. (
  14307. { ... unless the register specifies the location }
  14308. (taicpu(hp1).ops > 0) and
  14309. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14310. )
  14311. ) and
  14312. (
  14313. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14314. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14315. )
  14316. )
  14317. or
  14318. (
  14319. { Check up to two instructions ahead }
  14320. GetNextInstruction(hp1, hp2) and
  14321. (hp2.typ = ait_instruction) and
  14322. (
  14323. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14324. (
  14325. { Same as above }
  14326. (taicpu(hp2).ops > 0) and
  14327. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14328. )
  14329. ) and
  14330. (
  14331. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14332. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14333. )
  14334. )
  14335. ) then
  14336. begin
  14337. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14338. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14339. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14340. offset := 0;
  14341. if Assigned(symbol) or Assigned(relsymbol) then
  14342. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14343. else
  14344. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14345. { Inserting before the next instruction rather than after the
  14346. current instruction gives more accurate register tracking }
  14347. asml.InsertBefore(hp2, hp1);
  14348. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14349. Result := True;
  14350. end;
  14351. end;
  14352. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14353. var
  14354. hp1, hp2: tai;
  14355. NewRef: TReference;
  14356. Distance: Cardinal;
  14357. TempTracking: TAllUsedRegs;
  14358. DoSubMov2Lea: Boolean;
  14359. begin
  14360. Result := False;
  14361. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14362. MatchOpType(taicpu(p),top_const,top_reg) then
  14363. begin
  14364. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14365. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14366. (hp1.typ <> ait_instruction) or
  14367. not
  14368. (
  14369. (cs_opt_level3 in current_settings.optimizerswitches) or
  14370. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14371. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14372. ) then
  14373. Exit;
  14374. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14375. subq $x, %rax
  14376. movq %rax, %rdx
  14377. sarq $63, %rdx
  14378. (%rax still in use)
  14379. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14380. leaq $-x(%rax),%rdx
  14381. movq $x, %rax
  14382. sarq $63, %rdx
  14383. ...which is okay since it breaks the dependency chain between
  14384. subq and movq, but if OptPass2MOV is called first:
  14385. subq $x, %rax
  14386. cqto
  14387. ...which is better in all ways, taking only 2 cycles to execute
  14388. and much smaller in code size.
  14389. }
  14390. { The extra register tracking is quite strenuous }
  14391. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14392. MatchInstruction(hp1, A_MOV, []) then
  14393. begin
  14394. { Update the register tracking to the MOV instruction }
  14395. CopyUsedRegs(TempTracking);
  14396. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14397. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14398. else
  14399. { p and hp1 will be adjacent }
  14400. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14401. hp2 := hp1;
  14402. if OptPass2MOV(hp1) then
  14403. Include(OptsToCheck, aoc_ForceNewIteration);
  14404. { Reset the tracking to the current instruction }
  14405. RestoreUsedRegs(TempTracking);
  14406. ReleaseUsedRegs(TempTracking);
  14407. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14408. OptPass2SUB get called again }
  14409. if (hp1 <> hp2) then
  14410. begin
  14411. Result := True;
  14412. Exit;
  14413. end;
  14414. end;
  14415. { Change:
  14416. subl/q $x,%reg1
  14417. movl/q %reg1,%reg2
  14418. To:
  14419. leal/q $-x(%reg1),%reg2
  14420. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14421. Breaks the dependency chain and potentially permits the removal of
  14422. a CMP instruction if one follows.
  14423. }
  14424. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14425. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14426. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14427. (
  14428. { Instructions are guaranteed to be adjacent on -O2 and under }
  14429. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14430. (
  14431. { If the flags are used, don't make the optimisation,
  14432. otherwise they will be scrambled. Fixes #41148 }
  14433. (
  14434. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14435. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14436. ) and
  14437. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14438. )
  14439. ) then
  14440. begin
  14441. TransferUsedRegs(TmpUsedRegs);
  14442. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14443. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14444. else
  14445. { p and hp1 will be adjacent }
  14446. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14447. if (
  14448. SetAndTest(
  14449. (
  14450. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14451. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14452. ),
  14453. DoSubMov2Lea
  14454. ) or
  14455. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14456. not (cs_opt_size in current_settings.optimizerswitches)
  14457. ) then
  14458. begin
  14459. { Change the MOV instruction to a LEA instruction, and update the
  14460. first operand }
  14461. reference_reset(NewRef, 1, []);
  14462. NewRef.base := taicpu(p).oper[1]^.reg;
  14463. NewRef.scalefactor := 1;
  14464. NewRef.offset := -taicpu(p).oper[0]^.val;
  14465. taicpu(hp1).opcode := A_LEA;
  14466. taicpu(hp1).loadref(0, NewRef);
  14467. if DoSubMov2Lea then
  14468. begin
  14469. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14470. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14471. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14472. { hp1 may not be the immediate next instruction under -O3 }
  14473. RemoveCurrentp(p)
  14474. else
  14475. RemoveCurrentp(p, hp1);
  14476. end
  14477. else
  14478. begin
  14479. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14480. { Move what is now the LEA instruction to before the SUB instruction }
  14481. Asml.Remove(hp1);
  14482. Asml.InsertBefore(hp1, p);
  14483. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14484. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14485. p := hp1;
  14486. end;
  14487. Result := True;
  14488. end;
  14489. end;
  14490. end;
  14491. end;
  14492. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14493. begin
  14494. { we can skip all instructions not messing with the stack pointer }
  14495. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14496. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14497. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14498. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14499. ({(taicpu(hp1).ops=0) or }
  14500. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14501. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14502. ) and }
  14503. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14504. )
  14505. ) do
  14506. GetNextInstruction(hp1,hp1);
  14507. Result:=assigned(hp1);
  14508. end;
  14509. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14510. var
  14511. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14512. begin
  14513. Result:=false;
  14514. hp5:=nil;
  14515. hp6:=nil;
  14516. hp7:=nil;
  14517. hp8:=nil;
  14518. { replace
  14519. leal(q) x(<stackpointer>),<stackpointer>
  14520. <optional .seh_stackalloc ...>
  14521. <optional .seh_endprologue ...>
  14522. call procname
  14523. <optional NOP>
  14524. leal(q) -x(<stackpointer>),<stackpointer>
  14525. <optional VZEROUPPER>
  14526. ret
  14527. by
  14528. jmp procname
  14529. but do it only on level 4 because it destroys stack back traces
  14530. }
  14531. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14532. MatchOpType(taicpu(p),top_ref,top_reg) and
  14533. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14534. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14535. { the -8, -24, -40 are not required, but bail out early if possible,
  14536. higher values are unlikely }
  14537. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14538. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14539. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14540. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14541. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14542. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14543. GetNextInstruction(p, hp1) and
  14544. { Take a copy of hp1 }
  14545. SetAndTest(hp1, hp4) and
  14546. { trick to skip label }
  14547. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14548. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14549. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14550. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14551. SkipSimpleInstructions(hp1) and
  14552. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14553. GetNextInstruction(hp1, hp2) and
  14554. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14555. { skip nop instruction on win64 }
  14556. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14557. SetAndTest(hp2,hp6) and
  14558. GetNextInstruction(hp2,hp2) and
  14559. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14560. ) and
  14561. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14562. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14563. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14564. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14565. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14566. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14567. { Segment register will be NR_NO }
  14568. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14569. GetNextInstruction(hp2, hp3) and
  14570. { trick to skip label }
  14571. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14572. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14573. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14574. SetAndTest(hp3,hp5) and
  14575. GetNextInstruction(hp3,hp3) and
  14576. MatchInstruction(hp3,A_RET,[S_NO])
  14577. )
  14578. ) and
  14579. (taicpu(hp3).ops=0) then
  14580. begin
  14581. taicpu(hp1).opcode := A_JMP;
  14582. taicpu(hp1).is_jmp := true;
  14583. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14584. { search for the stackalloc directive and remove it }
  14585. hp7:=tai(p.next);
  14586. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14587. begin
  14588. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14589. begin
  14590. { sanity check }
  14591. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14592. Internalerror(2024012201);
  14593. hp8:=tai(hp7.next);
  14594. RemoveInstruction(tai(hp7));
  14595. hp7:=hp8;
  14596. break;
  14597. end
  14598. else
  14599. hp7:=tai(hp7.next);
  14600. end;
  14601. RemoveCurrentP(p, hp4);
  14602. RemoveInstruction(hp2);
  14603. RemoveInstruction(hp3);
  14604. { if there is a vzeroupper instruction then move it before the jmp }
  14605. if Assigned(hp5) then
  14606. begin
  14607. AsmL.Remove(hp5);
  14608. ASmL.InsertBefore(hp5,hp1)
  14609. end;
  14610. { remove nop on win64 }
  14611. if Assigned(hp6) then
  14612. RemoveInstruction(hp6);
  14613. Result:=true;
  14614. end;
  14615. end;
  14616. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14617. {$ifdef x86_64}
  14618. var
  14619. hp1, hp2, hp3, hp4, hp5: tai;
  14620. {$endif x86_64}
  14621. begin
  14622. Result:=false;
  14623. {$ifdef x86_64}
  14624. hp5:=nil;
  14625. { replace
  14626. push %rax
  14627. call procname
  14628. pop %rcx
  14629. ret
  14630. by
  14631. jmp procname
  14632. but do it only on level 4 because it destroys stack back traces
  14633. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14634. for all supported calling conventions
  14635. }
  14636. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14637. MatchOpType(taicpu(p),top_reg) and
  14638. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14639. GetNextInstruction(p, hp1) and
  14640. { Take a copy of hp1 }
  14641. SetAndTest(hp1, hp4) and
  14642. { trick to skip label }
  14643. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14644. SkipSimpleInstructions(hp1) and
  14645. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14646. GetNextInstruction(hp1, hp2) and
  14647. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14648. MatchOpType(taicpu(hp2),top_reg) and
  14649. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14650. GetNextInstruction(hp2, hp3) and
  14651. { trick to skip label }
  14652. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14653. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14654. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14655. SetAndTest(hp3,hp5) and
  14656. GetNextInstruction(hp3,hp3) and
  14657. MatchInstruction(hp3,A_RET,[S_NO])
  14658. )
  14659. ) and
  14660. (taicpu(hp3).ops=0) then
  14661. begin
  14662. taicpu(hp1).opcode := A_JMP;
  14663. taicpu(hp1).is_jmp := true;
  14664. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14665. RemoveCurrentP(p, hp4);
  14666. RemoveInstruction(hp2);
  14667. RemoveInstruction(hp3);
  14668. if Assigned(hp5) then
  14669. begin
  14670. AsmL.Remove(hp5);
  14671. ASmL.InsertBefore(hp5,hp1)
  14672. end;
  14673. Result:=true;
  14674. end;
  14675. {$endif x86_64}
  14676. end;
  14677. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14678. var
  14679. Value, RegName: string;
  14680. hp1: tai;
  14681. begin
  14682. Result:=false;
  14683. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14684. begin
  14685. case taicpu(p).oper[0]^.val of
  14686. 0:
  14687. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14688. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14689. (
  14690. { See if we can still convert the instruction }
  14691. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14692. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14693. ) then
  14694. begin
  14695. { change "mov $0,%reg" into "xor %reg,%reg" }
  14696. taicpu(p).opcode := A_XOR;
  14697. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14698. Result := True;
  14699. {$ifdef x86_64}
  14700. end
  14701. else if (taicpu(p).opsize = S_Q) then
  14702. begin
  14703. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14704. { The actual optimization }
  14705. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14706. taicpu(p).changeopsize(S_L);
  14707. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14708. Result := True;
  14709. end;
  14710. $1..$FFFFFFFF:
  14711. begin
  14712. { Code size reduction by J. Gareth "Kit" Moreton }
  14713. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14714. case taicpu(p).opsize of
  14715. S_Q:
  14716. begin
  14717. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14718. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14719. { The actual optimization }
  14720. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14721. taicpu(p).changeopsize(S_L);
  14722. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14723. Result := True;
  14724. end;
  14725. else
  14726. { Do nothing };
  14727. end;
  14728. {$endif x86_64}
  14729. end;
  14730. -1:
  14731. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14732. if (cs_opt_size in current_settings.optimizerswitches) and
  14733. (taicpu(p).opsize <> S_B) and
  14734. (
  14735. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14736. (
  14737. { See if we can still convert the instruction }
  14738. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14739. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14740. )
  14741. ) then
  14742. begin
  14743. { change "mov $-1,%reg" into "or $-1,%reg" }
  14744. { NOTES:
  14745. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14746. - This operation creates a false dependency on the register, so only do it when optimising for size
  14747. - 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
  14748. }
  14749. taicpu(p).opcode := A_OR;
  14750. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14751. Result := True;
  14752. end;
  14753. else
  14754. { Do nothing };
  14755. end;
  14756. end;
  14757. end;
  14758. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14759. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14760. begin
  14761. Result := False;
  14762. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14763. Exit;
  14764. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14765. so don't bother optimising }
  14766. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14767. Exit;
  14768. if (taicpu(p).oper[0]^.typ <> top_const) or
  14769. { If the value can fit into an 8-bit signed integer, a smaller
  14770. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14771. falls within this range }
  14772. (
  14773. (taicpu(p).oper[0]^.val > -128) and
  14774. (taicpu(p).oper[0]^.val <= 127)
  14775. ) then
  14776. Exit;
  14777. { If we're optimising for size, this is acceptable }
  14778. if (cs_opt_size in current_settings.optimizerswitches) then
  14779. Exit(True);
  14780. if (taicpu(p).oper[1]^.typ = top_reg) and
  14781. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14782. Exit(True);
  14783. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14784. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14785. Exit(True);
  14786. end;
  14787. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14788. var
  14789. hp1: tai;
  14790. Value: TCGInt;
  14791. begin
  14792. Result := False;
  14793. if MatchOpType(taicpu(p), top_const, top_reg) then
  14794. begin
  14795. { Detect:
  14796. andw x, %ax (0 <= x < $8000)
  14797. ...
  14798. movzwl %ax,%eax
  14799. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14800. }
  14801. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14802. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14803. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14804. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14805. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14806. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14807. begin
  14808. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14809. taicpu(hp1).opcode := A_CWDE;
  14810. taicpu(hp1).clearop(0);
  14811. taicpu(hp1).clearop(1);
  14812. taicpu(hp1).ops := 0;
  14813. { A change was made, but not with p, so don't set Result, but
  14814. notify the compiler that a change was made }
  14815. Include(OptsToCheck, aoc_ForceNewIteration);
  14816. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14817. end;
  14818. end;
  14819. { If "not x" is a power of 2 (popcnt = 1), change:
  14820. and $x, %reg/ref
  14821. To:
  14822. btr lb(x), %reg/ref
  14823. }
  14824. if IsBTXAcceptable(p) and
  14825. (
  14826. { Make sure a TEST doesn't follow that plays with the register }
  14827. not GetNextInstruction(p, hp1) or
  14828. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14829. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14830. ) then
  14831. begin
  14832. {$push}{$R-}{$Q-}
  14833. { Value is a sign-extended 32-bit integer - just correct it
  14834. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14835. checks to see if this operand is an immediate. }
  14836. Value := not taicpu(p).oper[0]^.val;
  14837. {$pop}
  14838. {$ifdef x86_64}
  14839. if taicpu(p).opsize = S_L then
  14840. {$endif x86_64}
  14841. Value := Value and $FFFFFFFF;
  14842. if (PopCnt(QWord(Value)) = 1) then
  14843. begin
  14844. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14845. taicpu(p).opcode := A_BTR;
  14846. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14847. Result := True;
  14848. Exit;
  14849. end;
  14850. end;
  14851. end;
  14852. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14853. begin
  14854. Result := False;
  14855. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14856. Exit;
  14857. { Convert:
  14858. movswl %ax,%eax -> cwtl
  14859. movslq %eax,%rax -> cdqe
  14860. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14861. refer to the same opcode and depends only on the assembler's
  14862. current operand-size attribute. [Kit]
  14863. }
  14864. with taicpu(p) do
  14865. case opsize of
  14866. S_WL:
  14867. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14868. begin
  14869. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14870. opcode := A_CWDE;
  14871. clearop(0);
  14872. clearop(1);
  14873. ops := 0;
  14874. Result := True;
  14875. end;
  14876. {$ifdef x86_64}
  14877. S_LQ:
  14878. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14879. begin
  14880. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14881. opcode := A_CDQE;
  14882. clearop(0);
  14883. clearop(1);
  14884. ops := 0;
  14885. Result := True;
  14886. end;
  14887. {$endif x86_64}
  14888. else
  14889. ;
  14890. end;
  14891. end;
  14892. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14893. var
  14894. hp1, hp2: tai;
  14895. IdentityMask, Shift: TCGInt;
  14896. LimitSize: Topsize;
  14897. DoNotMerge: Boolean;
  14898. begin
  14899. Result := False;
  14900. { All these optimisations work on "shr const,%reg" }
  14901. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14902. Exit;
  14903. DoNotMerge := False;
  14904. Shift := taicpu(p).oper[0]^.val;
  14905. LimitSize := taicpu(p).opsize;
  14906. hp1 := p;
  14907. repeat
  14908. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14909. Break;
  14910. { Detect:
  14911. shr x, %reg
  14912. and y, %reg
  14913. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14914. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14915. }
  14916. case taicpu(hp1).opcode of
  14917. A_AND:
  14918. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14919. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14920. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14921. begin
  14922. { Make sure the FLAGS register isn't in use }
  14923. TransferUsedRegs(TmpUsedRegs);
  14924. hp2 := p;
  14925. repeat
  14926. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14927. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14928. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14929. begin
  14930. { Generate the identity mask }
  14931. case taicpu(p).opsize of
  14932. S_B:
  14933. IdentityMask := $FF shr Shift;
  14934. S_W:
  14935. IdentityMask := $FFFF shr Shift;
  14936. S_L:
  14937. IdentityMask := $FFFFFFFF shr Shift;
  14938. {$ifdef x86_64}
  14939. S_Q:
  14940. { We need to force the operands to be unsigned 64-bit
  14941. integers otherwise the wrong value is generated }
  14942. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14943. {$endif x86_64}
  14944. else
  14945. InternalError(2022081501);
  14946. end;
  14947. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14948. begin
  14949. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14950. { All the possible 1 bits are covered, so we can remove the AND }
  14951. hp2 := tai(hp1.Previous);
  14952. RemoveInstruction(hp1);
  14953. { p wasn't actually changed, so don't set Result to True,
  14954. but a change was nonetheless made elsewhere }
  14955. Include(OptsToCheck, aoc_ForceNewIteration);
  14956. { Do another pass in case other AND or MOVZX instructions
  14957. follow }
  14958. hp1 := hp2;
  14959. Continue;
  14960. end;
  14961. end;
  14962. end;
  14963. A_TEST, A_CMP, A_Jcc:
  14964. { Skip over conditional jumps and relevant comparisons }
  14965. Continue;
  14966. A_MOVZX:
  14967. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14968. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14969. begin
  14970. { Since the original register is being read as is, subsequent
  14971. SHRs must not be merged at this point }
  14972. DoNotMerge := True;
  14973. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14974. begin
  14975. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14976. begin
  14977. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14978. { All the possible 1 bits are covered, so we can remove the AND }
  14979. hp2 := tai(hp1.Previous);
  14980. RemoveInstruction(hp1);
  14981. hp1 := hp2;
  14982. end
  14983. else { Different register target }
  14984. begin
  14985. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14986. taicpu(hp1).opcode := A_MOV;
  14987. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14988. case taicpu(hp1).opsize of
  14989. S_BW:
  14990. taicpu(hp1).opsize := S_W;
  14991. S_BL, S_WL:
  14992. taicpu(hp1).opsize := S_L;
  14993. else
  14994. InternalError(2022081503);
  14995. end;
  14996. end;
  14997. end
  14998. else if (Shift > 0) and
  14999. (taicpu(p).opsize = S_W) and
  15000. (taicpu(hp1).opsize = S_WL) and
  15001. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  15002. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  15003. begin
  15004. { Detect:
  15005. shr x, %ax (x > 0)
  15006. ...
  15007. movzwl %ax,%eax
  15008. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  15009. }
  15010. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  15011. taicpu(hp1).opcode := A_CWDE;
  15012. taicpu(hp1).clearop(0);
  15013. taicpu(hp1).clearop(1);
  15014. taicpu(hp1).ops := 0;
  15015. end;
  15016. { Move onto the next instruction }
  15017. Continue;
  15018. end;
  15019. A_SHL, A_SAL, A_SHR:
  15020. if (taicpu(hp1).opsize <= LimitSize) and
  15021. MatchOpType(taicpu(hp1), top_const, top_reg) and
  15022. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  15023. begin
  15024. { Make sure the sizes don't exceed the register size limit
  15025. (measured by the shift value falling below the limit) }
  15026. if taicpu(hp1).opsize < LimitSize then
  15027. LimitSize := taicpu(hp1).opsize;
  15028. if taicpu(hp1).opcode = A_SHR then
  15029. Inc(Shift, taicpu(hp1).oper[0]^.val)
  15030. else
  15031. begin
  15032. Dec(Shift, taicpu(hp1).oper[0]^.val);
  15033. DoNotMerge := True;
  15034. end;
  15035. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  15036. Break;
  15037. { Since we've established that the combined shift is within
  15038. limits, we can actually combine the adjacent SHR
  15039. instructions even if they're different sizes }
  15040. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  15041. begin
  15042. hp2 := tai(hp1.Previous);
  15043. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  15044. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  15045. RemoveInstruction(hp1);
  15046. hp1 := hp2;
  15047. end;
  15048. { Move onto the next instruction }
  15049. Continue;
  15050. end;
  15051. else
  15052. { If the register isn't actually modified, move onto the next instruction,
  15053. but set DoNotMerge to True since the register is being read }
  15054. if (
  15055. { Under -O2 and below, GetNextInstructionUsingReg only returns
  15056. the next instruction, whether or not it contains the register }
  15057. (cs_opt_level3 in current_settings.optimizerswitches) or
  15058. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1)
  15059. ) and not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  15060. begin
  15061. DoNotMerge := True;
  15062. Continue;
  15063. end;
  15064. end;
  15065. Break;
  15066. until False;
  15067. { Detect the following (looking backwards):
  15068. shr %cl,%reg
  15069. shr x, %reg
  15070. Swap the two SHR instructions to minimise a pipeline stall.
  15071. }
  15072. if GetLastInstruction(p, hp1) and
  15073. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15074. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15075. { First operand will be %cl }
  15076. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15077. { Just to be sure }
  15078. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15079. begin
  15080. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15081. { Moving the entries this way ensures the register tracking remains correct }
  15082. Asml.Remove(p);
  15083. Asml.InsertBefore(p, hp1);
  15084. p := hp1;
  15085. { Don't set Result to True because the current instruction is now
  15086. "shr %cl,%reg" and there's nothing more we can do with it }
  15087. end;
  15088. end;
  15089. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15090. var
  15091. hp1, hp2: tai;
  15092. Opposite, SecondOpposite: TAsmOp;
  15093. NewCond: TAsmCond;
  15094. begin
  15095. Result := False;
  15096. { Change:
  15097. add/sub 128,(dest)
  15098. To:
  15099. sub/add -128,(dest)
  15100. This generaally takes fewer bytes to encode because -128 can be stored
  15101. in a signed byte, whereas +128 cannot.
  15102. }
  15103. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15104. begin
  15105. if taicpu(p).opcode = A_ADD then
  15106. Opposite := A_SUB
  15107. else
  15108. Opposite := A_ADD;
  15109. { Be careful if the flags are in use, because the CF flag inverts
  15110. when changing from ADD to SUB and vice versa }
  15111. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15112. GetNextInstruction(p, hp1) then
  15113. begin
  15114. TransferUsedRegs(TmpUsedRegs);
  15115. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15116. hp2 := hp1;
  15117. { Scan ahead to check if everything's safe }
  15118. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15119. begin
  15120. if (hp1.typ <> ait_instruction) then
  15121. { Probably unsafe since the flags are still in use }
  15122. Exit;
  15123. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15124. { Stop searching at an unconditional jump }
  15125. Break;
  15126. if not
  15127. (
  15128. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15129. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15130. ) and
  15131. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15132. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15133. Exit;
  15134. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15135. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15136. { Move to the next instruction }
  15137. GetNextInstruction(hp1, hp1);
  15138. end;
  15139. while Assigned(hp2) and (hp2 <> hp1) do
  15140. begin
  15141. NewCond := C_None;
  15142. case taicpu(hp2).condition of
  15143. C_A, C_NBE:
  15144. NewCond := C_BE;
  15145. C_B, C_C, C_NAE:
  15146. NewCond := C_AE;
  15147. C_AE, C_NB, C_NC:
  15148. NewCond := C_B;
  15149. C_BE, C_NA:
  15150. NewCond := C_A;
  15151. else
  15152. { No change needed };
  15153. end;
  15154. if NewCond <> C_None then
  15155. begin
  15156. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15157. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15158. taicpu(hp2).condition := NewCond;
  15159. end
  15160. else
  15161. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15162. begin
  15163. { Because of the flipping of the carry bit, to ensure
  15164. the operation remains equivalent, ADC becomes SBB
  15165. and vice versa, and the constant is not-inverted.
  15166. If multiple ADCs or SBBs appear in a row, each one
  15167. changed causes the carry bit to invert, so they all
  15168. need to be flipped }
  15169. if taicpu(hp2).opcode = A_ADC then
  15170. SecondOpposite := A_SBB
  15171. else
  15172. SecondOpposite := A_ADC;
  15173. if taicpu(hp2).oper[0]^.typ <> top_const then
  15174. { Should have broken out of this optimisation already }
  15175. InternalError(2021112901);
  15176. 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]^) + ' -> ' +
  15177. 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);
  15178. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15179. taicpu(hp2).opcode := SecondOpposite;
  15180. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15181. end;
  15182. { Move to the next instruction }
  15183. GetNextInstruction(hp2, hp2);
  15184. end;
  15185. if (hp2 <> hp1) then
  15186. InternalError(2021111501);
  15187. end;
  15188. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15189. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15190. taicpu(p).opcode := Opposite;
  15191. taicpu(p).oper[0]^.val := -128;
  15192. { No further optimisations can be made on this instruction, so move
  15193. onto the next one to save time }
  15194. p := tai(p.Next);
  15195. UpdateUsedRegs(p);
  15196. Result := True;
  15197. Exit;
  15198. end;
  15199. { Detect:
  15200. add/sub %reg2,(dest)
  15201. add/sub x, (dest)
  15202. (dest can be a register or a reference)
  15203. Swap the instructions to minimise a pipeline stall. This reverses the
  15204. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15205. optimisations could be made.
  15206. }
  15207. if (taicpu(p).oper[0]^.typ = top_reg) and
  15208. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15209. (
  15210. (
  15211. (taicpu(p).oper[1]^.typ = top_reg) and
  15212. { We can try searching further ahead if we're writing to a register }
  15213. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15214. ) or
  15215. (
  15216. (taicpu(p).oper[1]^.typ = top_ref) and
  15217. GetNextInstruction(p, hp1)
  15218. )
  15219. ) and
  15220. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15221. (taicpu(hp1).oper[0]^.typ = top_const) and
  15222. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15223. begin
  15224. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15225. TransferUsedRegs(TmpUsedRegs);
  15226. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15227. hp2 := p;
  15228. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15229. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15230. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15231. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15232. begin
  15233. asml.remove(hp1);
  15234. asml.InsertBefore(hp1, p);
  15235. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15236. Result := True;
  15237. end;
  15238. end;
  15239. end;
  15240. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15241. var
  15242. hp1: tai;
  15243. begin
  15244. Result:=false;
  15245. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15246. while GetNextInstruction(p, hp1) and
  15247. TrySwapMovCmp(p, hp1) do
  15248. begin
  15249. if MatchInstruction(hp1, A_MOV, []) then
  15250. begin
  15251. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15252. begin
  15253. { A little hacky, but since CMP doesn't read the flags, only
  15254. modify them, it's safe if they get scrambled by MOV -> XOR }
  15255. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15256. Result := PostPeepholeOptMov(hp1);
  15257. {$ifdef x86_64}
  15258. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15259. { Used to shrink instruction size }
  15260. PostPeepholeOptXor(hp1);
  15261. {$endif x86_64}
  15262. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15263. end
  15264. else
  15265. begin
  15266. Result := PostPeepholeOptMov(hp1);
  15267. {$ifdef x86_64}
  15268. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15269. { Used to shrink instruction size }
  15270. PostPeepholeOptXor(hp1);
  15271. {$endif x86_64}
  15272. end;
  15273. end;
  15274. { Enabling this flag is actually a null operation, but it marks
  15275. the code as 'modified' during this pass }
  15276. Include(OptsToCheck, aoc_ForceNewIteration);
  15277. end;
  15278. { change "cmp $0, %reg" to "test %reg, %reg" }
  15279. if MatchOpType(taicpu(p),top_const,top_reg) and
  15280. (taicpu(p).oper[0]^.val = 0) then
  15281. begin
  15282. taicpu(p).opcode := A_TEST;
  15283. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15284. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15285. Result:=true;
  15286. end;
  15287. end;
  15288. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15289. var
  15290. IsTestConstX, IsValid : Boolean;
  15291. hp1,hp2 : tai;
  15292. begin
  15293. Result:=false;
  15294. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15295. if (taicpu(p).opcode = A_TEST) then
  15296. while GetNextInstruction(p, hp1) and
  15297. TrySwapMovCmp(p, hp1) do
  15298. begin
  15299. if MatchInstruction(hp1, A_MOV, []) then
  15300. begin
  15301. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15302. begin
  15303. { A little hacky, but since TEST doesn't read the flags, only
  15304. modify them, it's safe if they get scrambled by MOV -> XOR }
  15305. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15306. Result := PostPeepholeOptMov(hp1);
  15307. {$ifdef x86_64}
  15308. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15309. { Used to shrink instruction size }
  15310. PostPeepholeOptXor(hp1);
  15311. {$endif x86_64}
  15312. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15313. end
  15314. else
  15315. begin
  15316. Result := PostPeepholeOptMov(hp1);
  15317. {$ifdef x86_64}
  15318. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15319. { Used to shrink instruction size }
  15320. PostPeepholeOptXor(hp1);
  15321. {$endif x86_64}
  15322. end;
  15323. end;
  15324. { Enabling this flag is actually a null operation, but it marks
  15325. the code as 'modified' during this pass }
  15326. Include(OptsToCheck, aoc_ForceNewIteration);
  15327. end;
  15328. { If x is a power of 2 (popcnt = 1), change:
  15329. or $x, %reg/ref
  15330. To:
  15331. bts lb(x), %reg/ref
  15332. }
  15333. if (taicpu(p).opcode = A_OR) and
  15334. IsBTXAcceptable(p) and
  15335. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15336. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15337. (
  15338. { Don't optimise if a test instruction follows }
  15339. not GetNextInstruction(p, hp1) or
  15340. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15341. ) then
  15342. begin
  15343. 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);
  15344. taicpu(p).opcode := A_BTS;
  15345. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15346. Result := True;
  15347. Exit;
  15348. end;
  15349. { If x is a power of 2 (popcnt = 1), change:
  15350. test $x, %reg/ref
  15351. je / sete / cmove (or jne / setne)
  15352. To:
  15353. bt lb(x), %reg/ref
  15354. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15355. }
  15356. if (taicpu(p).opcode = A_TEST) and
  15357. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15358. (taicpu(p).oper[0]^.typ = top_const) and
  15359. (
  15360. (cs_opt_size in current_settings.optimizerswitches) or
  15361. (
  15362. (taicpu(p).oper[1]^.typ = top_reg) and
  15363. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15364. ) or
  15365. (
  15366. (taicpu(p).oper[1]^.typ <> top_reg) and
  15367. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15368. )
  15369. ) and
  15370. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15371. { For sizes less than S_L, the byte size is equal or larger with BT,
  15372. so don't bother optimising }
  15373. (taicpu(p).opsize >= S_L) then
  15374. begin
  15375. IsValid := True;
  15376. { Check the next set of instructions, watching the FLAGS register
  15377. and the conditions used }
  15378. TransferUsedRegs(TmpUsedRegs);
  15379. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15380. hp1 := p;
  15381. hp2 := nil;
  15382. while GetNextInstruction(hp1, hp1) do
  15383. begin
  15384. if not Assigned(hp2) then
  15385. { The first instruction after TEST }
  15386. hp2 := hp1;
  15387. if (hp1.typ <> ait_instruction) then
  15388. begin
  15389. { If the flags are no longer in use, everything is fine }
  15390. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15391. IsValid := False;
  15392. Break;
  15393. end;
  15394. case taicpu(hp1).condition of
  15395. C_None:
  15396. begin
  15397. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15398. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15399. { Something is not quite normal, so play safe and don't change }
  15400. IsValid := False;
  15401. Break;
  15402. end;
  15403. C_E, C_Z, C_NE, C_NZ:
  15404. { This is fine };
  15405. else
  15406. begin
  15407. { Unsupported condition }
  15408. IsValid := False;
  15409. Break;
  15410. end;
  15411. end;
  15412. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15413. end;
  15414. if IsValid then
  15415. begin
  15416. while hp2 <> hp1 do
  15417. begin
  15418. case taicpu(hp2).condition of
  15419. C_Z, C_E:
  15420. taicpu(hp2).condition := C_NC;
  15421. C_NZ, C_NE:
  15422. taicpu(hp2).condition := C_C;
  15423. else
  15424. { Should not get this by this point }
  15425. InternalError(2022110701);
  15426. end;
  15427. GetNextInstruction(hp2, hp2);
  15428. end;
  15429. 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);
  15430. taicpu(p).opcode := A_BT;
  15431. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15432. Result := True;
  15433. Exit;
  15434. end;
  15435. end;
  15436. { removes the line marked with (x) from the sequence
  15437. and/or/xor/add/sub/... $x, %y
  15438. test/or %y, %y | test $-1, %y (x)
  15439. j(n)z _Label
  15440. as the first instruction already adjusts the ZF
  15441. %y operand may also be a reference }
  15442. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15443. MatchOperand(taicpu(p).oper[0]^,-1);
  15444. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15445. GetLastInstruction(p, hp1) and
  15446. (tai(hp1).typ = ait_instruction) and
  15447. GetNextInstruction(p,hp2) and
  15448. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15449. case taicpu(hp1).opcode Of
  15450. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15451. { These two instructions set the zero flag if the result is zero }
  15452. A_POPCNT, A_LZCNT:
  15453. begin
  15454. if (
  15455. { With POPCNT, an input of zero will set the zero flag
  15456. because the population count of zero is zero }
  15457. (taicpu(hp1).opcode = A_POPCNT) and
  15458. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15459. (
  15460. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15461. { Faster than going through the second half of the 'or'
  15462. condition below }
  15463. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15464. )
  15465. ) or (
  15466. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15467. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15468. { and in case of carry for A(E)/B(E)/C/NC }
  15469. (
  15470. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15471. (
  15472. (taicpu(hp1).opcode <> A_ADD) and
  15473. (taicpu(hp1).opcode <> A_SUB) and
  15474. (taicpu(hp1).opcode <> A_LZCNT)
  15475. )
  15476. )
  15477. ) then
  15478. begin
  15479. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15480. RemoveCurrentP(p, hp2);
  15481. Result:=true;
  15482. Exit;
  15483. end;
  15484. end;
  15485. A_SHL, A_SAL, A_SHR, A_SAR:
  15486. begin
  15487. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15488. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15489. { therefore, it's only safe to do this optimization for }
  15490. { shifts by a (nonzero) constant }
  15491. (taicpu(hp1).oper[0]^.typ = top_const) and
  15492. (taicpu(hp1).oper[0]^.val <> 0) and
  15493. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15494. { and in case of carry for A(E)/B(E)/C/NC }
  15495. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15496. begin
  15497. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15498. RemoveCurrentP(p, hp2);
  15499. Result:=true;
  15500. Exit;
  15501. end;
  15502. end;
  15503. A_DEC, A_INC, A_NEG:
  15504. begin
  15505. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15506. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15507. { and in case of carry for A(E)/B(E)/C/NC }
  15508. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15509. begin
  15510. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15511. RemoveCurrentP(p, hp2);
  15512. Result:=true;
  15513. Exit;
  15514. end;
  15515. end;
  15516. A_ANDN, A_BZHI:
  15517. begin
  15518. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15519. { Only the zero and sign flags are consistent with what the result is }
  15520. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15521. begin
  15522. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15523. RemoveCurrentP(p, hp2);
  15524. Result:=true;
  15525. Exit;
  15526. end;
  15527. end;
  15528. A_BEXTR:
  15529. begin
  15530. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15531. { Only the zero flag is set }
  15532. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15533. begin
  15534. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15535. RemoveCurrentP(p, hp2);
  15536. Result:=true;
  15537. Exit;
  15538. end;
  15539. end;
  15540. else
  15541. ;
  15542. end; { case }
  15543. { change "test $-1,%reg" into "test %reg,%reg" }
  15544. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15545. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15546. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15547. if MatchInstruction(p, A_OR, []) and
  15548. { Can only match if they're both registers }
  15549. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15550. begin
  15551. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15552. taicpu(p).opcode := A_TEST;
  15553. { No need to set Result to True, as we've done all the optimisations we can }
  15554. end;
  15555. end;
  15556. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15557. var
  15558. hp1,hp3 : tai;
  15559. {$ifndef x86_64}
  15560. hp2 : taicpu;
  15561. {$endif x86_64}
  15562. begin
  15563. Result:=false;
  15564. hp3:=nil;
  15565. {$ifndef x86_64}
  15566. { don't do this on modern CPUs, this really hurts them due to
  15567. broken call/ret pairing }
  15568. if (current_settings.optimizecputype < cpu_Pentium2) and
  15569. not(cs_create_pic in current_settings.moduleswitches) and
  15570. GetNextInstruction(p, hp1) and
  15571. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15572. MatchOpType(taicpu(hp1),top_ref) and
  15573. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15574. begin
  15575. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15576. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15577. InsertLLItem(p.previous, p, hp2);
  15578. taicpu(p).opcode := A_JMP;
  15579. taicpu(p).is_jmp := true;
  15580. RemoveInstruction(hp1);
  15581. Result:=true;
  15582. end
  15583. else
  15584. {$endif x86_64}
  15585. { replace
  15586. call procname
  15587. ret
  15588. by
  15589. jmp procname
  15590. but do it only on level 4 because it destroys stack back traces
  15591. else if the subroutine is marked as no return, remove the ret
  15592. }
  15593. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15594. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15595. GetNextInstruction(p, hp1) and
  15596. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15597. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15598. SetAndTest(hp1,hp3) and
  15599. GetNextInstruction(hp1,hp1) and
  15600. MatchInstruction(hp1,A_RET,[S_NO])
  15601. )
  15602. ) and
  15603. (taicpu(hp1).ops=0) then
  15604. begin
  15605. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15606. { we might destroy stack alignment here if we do not do a call }
  15607. (target_info.stackalign<=sizeof(SizeUInt)) then
  15608. begin
  15609. taicpu(p).opcode := A_JMP;
  15610. taicpu(p).is_jmp := true;
  15611. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15612. end
  15613. else
  15614. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15615. RemoveInstruction(hp1);
  15616. if Assigned(hp3) then
  15617. begin
  15618. AsmL.Remove(hp3);
  15619. AsmL.InsertBefore(hp3,p)
  15620. end;
  15621. Result:=true;
  15622. end;
  15623. end;
  15624. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15625. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15626. begin
  15627. case OpSize of
  15628. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15629. Result := (Val <= $FF) and (Val >= -128);
  15630. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15631. Result := (Val <= $FFFF) and (Val >= -32768);
  15632. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15633. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15634. else
  15635. Result := True;
  15636. end;
  15637. end;
  15638. var
  15639. hp1, hp2 : tai;
  15640. SizeChange: Boolean;
  15641. PreMessage: string;
  15642. begin
  15643. Result := False;
  15644. if (taicpu(p).oper[0]^.typ = top_reg) and
  15645. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15646. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15647. begin
  15648. { Change (using movzbl %al,%eax as an example):
  15649. movzbl %al, %eax movzbl %al, %eax
  15650. cmpl x, %eax testl %eax,%eax
  15651. To:
  15652. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15653. movzbl %al, %eax movzbl %al, %eax
  15654. Smaller instruction and minimises pipeline stall as the CPU
  15655. doesn't have to wait for the register to get zero-extended. [Kit]
  15656. Also allow if the smaller of the two registers is being checked,
  15657. as this still removes the false dependency.
  15658. }
  15659. if
  15660. (
  15661. (
  15662. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15663. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15664. ) or (
  15665. { If MatchOperand returns True, they must both be registers }
  15666. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15667. )
  15668. ) and
  15669. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15670. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15671. begin
  15672. 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);
  15673. asml.Remove(hp1);
  15674. asml.InsertBefore(hp1, p);
  15675. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15676. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15677. begin
  15678. taicpu(hp1).opcode := A_TEST;
  15679. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15680. end;
  15681. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15682. case taicpu(p).opsize of
  15683. S_BW, S_BL:
  15684. begin
  15685. SizeChange := taicpu(hp1).opsize <> S_B;
  15686. taicpu(hp1).changeopsize(S_B);
  15687. end;
  15688. S_WL:
  15689. begin
  15690. SizeChange := taicpu(hp1).opsize <> S_W;
  15691. taicpu(hp1).changeopsize(S_W);
  15692. end
  15693. else
  15694. InternalError(2020112701);
  15695. end;
  15696. UpdateUsedRegs(tai(p.Next));
  15697. { Check if the register is used aferwards - if not, we can
  15698. remove the movzx instruction completely }
  15699. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15700. begin
  15701. { Hp1 is a better position than p for debugging purposes }
  15702. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15703. RemoveCurrentp(p, hp1);
  15704. Result := True;
  15705. end;
  15706. if SizeChange then
  15707. DebugMsg(SPeepholeOptimization + PreMessage +
  15708. 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)
  15709. else
  15710. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15711. Exit;
  15712. end;
  15713. { Change (using movzwl %ax,%eax as an example):
  15714. movzwl %ax, %eax
  15715. movb %al, (dest) (Register is smaller than read register in movz)
  15716. To:
  15717. movb %al, (dest) (Move one back to avoid a false dependency)
  15718. movzwl %ax, %eax
  15719. }
  15720. if (taicpu(hp1).opcode = A_MOV) and
  15721. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15722. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15723. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15724. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15725. begin
  15726. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15727. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15728. asml.Remove(hp1);
  15729. asml.InsertBefore(hp1, p);
  15730. if taicpu(hp1).oper[1]^.typ = top_reg then
  15731. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15732. { Check if the register is used aferwards - if not, we can
  15733. remove the movzx instruction completely }
  15734. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15735. begin
  15736. { Hp1 is a better position than p for debugging purposes }
  15737. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15738. RemoveCurrentp(p, hp1);
  15739. Result := True;
  15740. end;
  15741. Exit;
  15742. end;
  15743. end;
  15744. end;
  15745. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15746. var
  15747. hp1: tai;
  15748. {$ifdef x86_64}
  15749. PreMessage, RegName: string;
  15750. {$endif x86_64}
  15751. begin
  15752. Result := False;
  15753. { If x is a power of 2 (popcnt = 1), change:
  15754. xor $x, %reg/ref
  15755. To:
  15756. btc lb(x), %reg/ref
  15757. }
  15758. if IsBTXAcceptable(p) and
  15759. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15760. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15761. (
  15762. { Don't optimise if a test instruction follows }
  15763. not GetNextInstruction(p, hp1) or
  15764. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15765. ) then
  15766. begin
  15767. 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);
  15768. taicpu(p).opcode := A_BTC;
  15769. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15770. Result := True;
  15771. Exit;
  15772. end;
  15773. {$ifdef x86_64}
  15774. { Code size reduction by J. Gareth "Kit" Moreton }
  15775. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15776. as this removes the REX prefix }
  15777. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15778. Exit;
  15779. if taicpu(p).oper[0]^.typ <> top_reg then
  15780. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15781. InternalError(2018011500);
  15782. case taicpu(p).opsize of
  15783. S_Q:
  15784. begin
  15785. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15786. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15787. { The actual optimization }
  15788. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15789. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15790. taicpu(p).changeopsize(S_L);
  15791. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15792. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15793. end;
  15794. else
  15795. ;
  15796. end;
  15797. {$endif x86_64}
  15798. end;
  15799. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15800. var
  15801. XReg: TRegister;
  15802. begin
  15803. Result := False;
  15804. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15805. Smaller encoding and slightly faster on some platforms (also works for
  15806. ZMM-sized registers) }
  15807. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15808. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15809. begin
  15810. XReg := taicpu(p).oper[0]^.reg;
  15811. if (taicpu(p).oper[1]^.reg = XReg) then
  15812. begin
  15813. taicpu(p).changeopsize(S_XMM);
  15814. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15815. if (cs_opt_size in current_settings.optimizerswitches) then
  15816. begin
  15817. { Change input registers to %xmm0 to reduce size. Note that
  15818. there's a risk of a false dependency doing this, so only
  15819. optimise for size here }
  15820. XReg := NR_XMM0;
  15821. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15822. end
  15823. else
  15824. begin
  15825. setsubreg(XReg, R_SUBMMX);
  15826. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15827. end;
  15828. taicpu(p).oper[0]^.reg := XReg;
  15829. taicpu(p).oper[1]^.reg := XReg;
  15830. Result := True;
  15831. end;
  15832. end;
  15833. end;
  15834. function TX86AsmOptimizer.PostPeepholeOptRET(var p: tai): Boolean;
  15835. var
  15836. hp1, p_new: tai;
  15837. begin
  15838. Result := False;
  15839. { Check for:
  15840. ret
  15841. .Lbl:
  15842. ret
  15843. Remove first 'ret'
  15844. }
  15845. if GetNextInstruction(p, hp1) and
  15846. { Remember where the label is }
  15847. SetAndTest(hp1, p_new) and
  15848. (hp1.typ in [ait_align, ait_label]) and
  15849. SkipLabels(hp1, hp1) and
  15850. MatchInstruction(hp1, A_RET, []) and
  15851. { To be safe, make sure the RET instructions are identical }
  15852. (taicpu(p).ops = taicpu(hp1).ops) and
  15853. (
  15854. (taicpu(p).ops = 0) or
  15855. (
  15856. (taicpu(p).ops = 1) and
  15857. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^)
  15858. )
  15859. ) then
  15860. begin
  15861. DebugMsg(SPeepholeOptimization + 'Removed superfluous RET', p);
  15862. UpdateUsedRegs(tai(p.Next));
  15863. RemoveCurrentP(p, p_new);
  15864. Result := True;
  15865. Exit;
  15866. end;
  15867. end;
  15868. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15869. var
  15870. OperIdx: Integer;
  15871. begin
  15872. for OperIdx := 0 to p.ops - 1 do
  15873. if p.oper[OperIdx]^.typ = top_ref then
  15874. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15875. end;
  15876. end.