aoptx86.pas 756 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617
  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<>[] then
  762. begin
  763. RegReadByInstruction := true;
  764. exit
  765. end;
  766. RS_ECX:
  767. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  768. begin
  769. RegReadByInstruction := true;
  770. exit
  771. end;
  772. RS_EDX:
  773. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  774. begin
  775. RegReadByInstruction := true;
  776. exit
  777. end;
  778. RS_EBX:
  779. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  780. begin
  781. RegReadByInstruction := true;
  782. exit
  783. end;
  784. RS_ESP:
  785. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  786. begin
  787. RegReadByInstruction := true;
  788. exit
  789. end;
  790. RS_EBP:
  791. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  792. begin
  793. RegReadByInstruction := true;
  794. exit
  795. end;
  796. RS_ESI:
  797. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. RS_EDI:
  803. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*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. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3952. Result := True;
  3953. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3954. begin
  3955. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3956. RemoveCurrentP(p);
  3957. Exit;
  3958. end
  3959. else
  3960. begin
  3961. { Check to see if %reg2 is no longer in use }
  3962. TransferUsedRegs(TmpUsedRegs);
  3963. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3964. UpdateUsedRegsBetween(TmpUsedRegs, tai(hp1.Next), hp2);
  3965. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3966. begin
  3967. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3968. RemoveCurrentP(p);
  3969. Exit;
  3970. end;
  3971. end;
  3972. { If we reach this point, p and hp1 weren't actually modified,
  3973. so we can do a bit more work on this pass }
  3974. end;
  3975. end;
  3976. end;
  3977. end;
  3978. end;
  3979. end;
  3980. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  3981. { All the next optimisations require a next instruction }
  3982. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  3983. Exit;
  3984. { Next instruction is also a MOV ? }
  3985. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3986. begin
  3987. if MatchOpType(taicpu(p), top_const, top_ref) and
  3988. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3989. TryConstMerge(p, hp1) then
  3990. begin
  3991. Result := True;
  3992. { In case we have four byte writes in a row, check for 2 more
  3993. right now so we don't have to wait for another iteration of
  3994. pass 1
  3995. }
  3996. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3997. case taicpu(p).opsize of
  3998. S_W:
  3999. begin
  4000. if GetNextInstruction(p, hp1) and
  4001. MatchInstruction(hp1, A_MOV, [S_B]) and
  4002. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4003. GetNextInstruction(hp1, hp2) and
  4004. MatchInstruction(hp2, A_MOV, [S_B]) and
  4005. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4006. { Try to merge the two bytes }
  4007. TryConstMerge(hp1, hp2) then
  4008. { Now try to merge the two words (hp2 will get deleted) }
  4009. TryConstMerge(p, hp1);
  4010. end;
  4011. S_L:
  4012. begin
  4013. { Though this only really benefits x86_64 and not i386, it
  4014. gets a potential optimisation done faster and hence
  4015. reduces the number of times OptPass1MOV is entered }
  4016. if GetNextInstruction(p, hp1) and
  4017. MatchInstruction(hp1, A_MOV, [S_W]) and
  4018. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4019. GetNextInstruction(hp1, hp2) and
  4020. MatchInstruction(hp2, A_MOV, [S_W]) and
  4021. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4022. { Try to merge the two words }
  4023. TryConstMerge(hp1, hp2) then
  4024. { This will always fail on i386, so don't bother
  4025. calling it unless we're doing x86_64 }
  4026. {$ifdef x86_64}
  4027. { Now try to merge the two longwords (hp2 will get deleted) }
  4028. TryConstMerge(p, hp1)
  4029. {$endif x86_64}
  4030. ;
  4031. end;
  4032. else
  4033. ;
  4034. end;
  4035. Exit;
  4036. end;
  4037. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4038. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4039. { mov reg1, mem1 or mov mem1, reg1
  4040. mov mem2, reg2 mov reg2, mem2}
  4041. begin
  4042. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4043. { mov reg1, mem1 or mov mem1, reg1
  4044. mov mem2, reg1 mov reg2, mem1}
  4045. begin
  4046. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4047. { Removes the second statement from
  4048. mov reg1, mem1/reg2
  4049. mov mem1/reg2, reg1 }
  4050. begin
  4051. if taicpu(p).oper[0]^.typ=top_reg then
  4052. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4053. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  4054. RemoveInstruction(hp1);
  4055. Result:=true;
  4056. exit;
  4057. end
  4058. else
  4059. begin
  4060. TransferUsedRegs(TmpUsedRegs);
  4061. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4062. if (taicpu(p).oper[1]^.typ = top_ref) and
  4063. { mov reg1, mem1
  4064. mov mem2, reg1 }
  4065. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4066. GetNextInstruction(hp1, hp2) and
  4067. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4068. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4069. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4070. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4071. { change to
  4072. mov reg1, mem1 mov reg1, mem1
  4073. mov mem2, reg1 cmp reg1, mem2
  4074. cmp mem1, reg1
  4075. }
  4076. begin
  4077. RemoveInstruction(hp2);
  4078. taicpu(hp1).opcode := A_CMP;
  4079. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4080. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4081. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4082. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4083. end;
  4084. end;
  4085. end
  4086. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4087. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4088. begin
  4089. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4090. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4091. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4092. end
  4093. else
  4094. begin
  4095. TransferUsedRegs(TmpUsedRegs);
  4096. if GetNextInstruction(hp1, hp2) and
  4097. MatchOpType(taicpu(p),top_ref,top_reg) and
  4098. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4099. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4100. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4101. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4102. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4103. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4104. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4105. { mov mem1, %reg1
  4106. mov %reg1, mem2
  4107. mov mem2, reg2
  4108. to:
  4109. mov mem1, reg2
  4110. mov reg2, mem2}
  4111. begin
  4112. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4113. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4114. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4115. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4116. RemoveInstruction(hp2);
  4117. Result := True;
  4118. end
  4119. {$ifdef i386}
  4120. { this is enabled for i386 only, as the rules to create the reg sets below
  4121. are too complicated for x86-64, so this makes this code too error prone
  4122. on x86-64
  4123. }
  4124. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4125. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4126. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4127. { mov mem1, reg1 mov mem1, reg1
  4128. mov reg1, mem2 mov reg1, mem2
  4129. mov mem2, reg2 mov mem2, reg1
  4130. to: to:
  4131. mov mem1, reg1 mov mem1, reg1
  4132. mov mem1, reg2 mov reg1, mem2
  4133. mov reg1, mem2
  4134. or (if mem1 depends on reg1
  4135. and/or if mem2 depends on reg2)
  4136. to:
  4137. mov mem1, reg1
  4138. mov reg1, mem2
  4139. mov reg1, reg2
  4140. }
  4141. begin
  4142. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4143. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4144. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4145. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4146. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4147. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4148. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4149. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4150. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4151. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4152. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4153. end
  4154. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4155. begin
  4156. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4157. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4158. end
  4159. else
  4160. begin
  4161. RemoveInstruction(hp2);
  4162. end
  4163. {$endif i386}
  4164. ;
  4165. end;
  4166. end
  4167. { movl [mem1],reg1
  4168. movl [mem1],reg2
  4169. to
  4170. movl [mem1],reg1
  4171. movl reg1,reg2
  4172. }
  4173. else if not CheckMovMov2MovMov2(p, hp1) and
  4174. { movl const1,[mem1]
  4175. movl [mem1],reg1
  4176. to
  4177. movl const1,reg1
  4178. movl reg1,[mem1]
  4179. }
  4180. MatchOpType(Taicpu(p),top_const,top_ref) and
  4181. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4182. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4183. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4184. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4185. begin
  4186. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4187. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4188. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4189. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4190. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4191. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4192. Result:=true;
  4193. exit;
  4194. end;
  4195. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4196. end;
  4197. { search further than the next instruction for a mov (as long as it's not a jump) }
  4198. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4199. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4200. (taicpu(p).oper[1]^.typ = top_reg) and
  4201. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4202. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4203. begin
  4204. { we work with hp2 here, so hp1 can be still used later on when
  4205. checking for GetNextInstruction_p }
  4206. hp3 := hp1;
  4207. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4208. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4209. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4210. TransferUsedRegs(TmpUsedRegs);
  4211. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4212. if NotFirstIteration then
  4213. JumpTracking := TLinkedList.Create
  4214. else
  4215. JumpTracking := nil;
  4216. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4217. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4218. (hp2.typ=ait_instruction) do
  4219. begin
  4220. case taicpu(hp2).opcode of
  4221. A_POP:
  4222. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4223. begin
  4224. if not CrossJump and
  4225. not RegUsedBetween(p_TargetReg, p, hp2) then
  4226. begin
  4227. { We can remove the original MOV since the register
  4228. wasn't used between it and its popping from the stack }
  4229. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4230. RemoveCurrentp(p, hp1);
  4231. Result := True;
  4232. JumpTracking.Free;
  4233. Exit;
  4234. end;
  4235. { Can't go any further }
  4236. Break;
  4237. end;
  4238. A_MOV:
  4239. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4240. ((taicpu(p).oper[0]^.typ=top_const) or
  4241. ((taicpu(p).oper[0]^.typ=top_reg) and
  4242. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4243. )
  4244. ) then
  4245. begin
  4246. { we have
  4247. mov x, %treg
  4248. mov %treg, y
  4249. }
  4250. { We don't need to call UpdateUsedRegs for every instruction between
  4251. p and hp2 because the register we're concerned about will not
  4252. become deallocated (otherwise GetNextInstructionUsingReg would
  4253. have stopped at an earlier instruction). [Kit] }
  4254. TempRegUsed :=
  4255. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4256. RegReadByInstruction(p_TargetReg, hp3) or
  4257. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4258. case taicpu(p).oper[0]^.typ Of
  4259. top_reg:
  4260. begin
  4261. { change
  4262. mov %reg, %treg
  4263. mov %treg, y
  4264. to
  4265. mov %reg, y
  4266. }
  4267. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4268. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4269. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4270. begin
  4271. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4272. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4273. if TempRegUsed then
  4274. begin
  4275. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4276. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4277. { Set the start of the next GetNextInstructionUsingRegCond search
  4278. to start at the entry right before hp2 (which is about to be removed) }
  4279. hp3 := tai(hp2.Previous);
  4280. RemoveInstruction(hp2);
  4281. Include(OptsToCheck, aoc_ForceNewIteration);
  4282. { See if there's more we can optimise }
  4283. Continue;
  4284. end
  4285. else
  4286. begin
  4287. RemoveInstruction(hp2);
  4288. { We can remove the original MOV too }
  4289. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4290. RemoveCurrentP(p, hp1);
  4291. Result:=true;
  4292. JumpTracking.Free;
  4293. Exit;
  4294. end;
  4295. end
  4296. else
  4297. begin
  4298. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4299. taicpu(hp2).loadReg(0, p_SourceReg);
  4300. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4301. { Check to see if the register also appears in the reference }
  4302. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4303. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4304. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4305. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4306. begin
  4307. { Don't remove the first instruction if the temporary register is in use }
  4308. if not TempRegUsed then
  4309. begin
  4310. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4311. RemoveCurrentP(p, hp1);
  4312. Result:=true;
  4313. JumpTracking.Free;
  4314. Exit;
  4315. end;
  4316. { No need to set Result to True here. If there's another instruction later
  4317. on that can be optimised, it will be detected when the main Pass 1 loop
  4318. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4319. hp3 := hp2;
  4320. Continue;
  4321. end;
  4322. end;
  4323. end;
  4324. top_const:
  4325. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4326. begin
  4327. { change
  4328. mov const, %treg
  4329. mov %treg, y
  4330. to
  4331. mov const, y
  4332. }
  4333. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4334. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4335. begin
  4336. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4337. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4338. if TempRegUsed then
  4339. begin
  4340. { Don't remove the first instruction if the temporary register is in use }
  4341. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4342. { No need to set Result to True. If there's another instruction later on
  4343. that can be optimised, it will be detected when the main Pass 1 loop
  4344. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4345. end
  4346. else
  4347. begin
  4348. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4349. RemoveCurrentP(p, hp1);
  4350. Result:=true;
  4351. Exit;
  4352. end;
  4353. end;
  4354. end;
  4355. else
  4356. Internalerror(2019103001);
  4357. end;
  4358. end
  4359. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4360. begin
  4361. if not CrossJump and
  4362. not RegUsedBetween(p_TargetReg, p, hp2) and
  4363. not RegReadByInstruction(p_TargetReg, hp2) then
  4364. begin
  4365. { Register is not used before it is overwritten }
  4366. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4367. RemoveCurrentp(p, hp1);
  4368. Result := True;
  4369. Exit;
  4370. end;
  4371. if (taicpu(p).oper[0]^.typ = top_const) and
  4372. (taicpu(hp2).oper[0]^.typ = top_const) then
  4373. begin
  4374. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4375. begin
  4376. { Same value - register hasn't changed }
  4377. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4378. RemoveInstruction(hp2);
  4379. Include(OptsToCheck, aoc_ForceNewIteration);
  4380. { See if there's more we can optimise }
  4381. Continue;
  4382. end;
  4383. end;
  4384. {$ifdef x86_64}
  4385. end
  4386. { Change:
  4387. movl %reg1l,%reg2l
  4388. ...
  4389. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4390. To:
  4391. movl %reg1l,%reg2l
  4392. ...
  4393. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4394. If %reg1 = %reg3, convert to:
  4395. movl %reg1l,%reg2l
  4396. ...
  4397. andl %reg1l,%reg1l
  4398. }
  4399. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4400. (taicpu(p).oper[0]^.typ = top_reg) and
  4401. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4402. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4403. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4404. begin
  4405. TempRegUsed :=
  4406. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4407. RegReadByInstruction(p_TargetReg, hp3) or
  4408. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4409. taicpu(hp2).opsize := S_L;
  4410. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4411. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4412. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4413. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4414. begin
  4415. { %reg1 = %reg3 }
  4416. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4417. taicpu(hp2).opcode := A_AND;
  4418. end
  4419. else
  4420. begin
  4421. { %reg1 <> %reg3 }
  4422. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4423. end;
  4424. if not TempRegUsed then
  4425. begin
  4426. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4427. RemoveCurrentP(p, hp1);
  4428. Result := True;
  4429. Exit;
  4430. end
  4431. else
  4432. begin
  4433. { Initial instruction wasn't actually changed }
  4434. Include(OptsToCheck, aoc_ForceNewIteration);
  4435. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4436. appears below since %reg1 has technically changed }
  4437. if taicpu(hp2).opcode = A_AND then
  4438. Break;
  4439. end;
  4440. {$endif x86_64}
  4441. end
  4442. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4443. GetNextInstruction(hp2, hp4) and
  4444. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4445. { Optimise the following first:
  4446. movl [mem1],reg1
  4447. movl [mem1],reg2
  4448. to
  4449. movl [mem1],reg1
  4450. movl reg1,reg2
  4451. If [mem1] contains the target register and reg1 is the
  4452. the source register, this optimisation will get missed
  4453. and produce less efficient code later on.
  4454. }
  4455. if CheckMovMov2MovMov2(hp2, hp4) then
  4456. { Initial instruction wasn't actually changed }
  4457. Include(OptsToCheck, aoc_ForceNewIteration);
  4458. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4459. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4460. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4461. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4462. begin
  4463. {
  4464. Change from:
  4465. mov ###, %reg
  4466. ...
  4467. movs/z %reg,%reg (Same register, just different sizes)
  4468. To:
  4469. movs/z ###, %reg (Longer version)
  4470. ...
  4471. (remove)
  4472. }
  4473. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4474. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4475. { Keep the first instruction as mov if ### is a constant }
  4476. if taicpu(p).oper[0]^.typ = top_const then
  4477. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4478. else
  4479. begin
  4480. taicpu(p).opcode := taicpu(hp2).opcode;
  4481. taicpu(p).opsize := taicpu(hp2).opsize;
  4482. end;
  4483. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4484. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4485. RemoveInstruction(hp2);
  4486. Result := True;
  4487. JumpTracking.Free;
  4488. Exit;
  4489. end;
  4490. else
  4491. { Move down to the if-block below };
  4492. end;
  4493. { Also catches MOV/S/Z instructions that aren't modified }
  4494. if taicpu(p).oper[0]^.typ = top_reg then
  4495. begin
  4496. p_SourceReg := taicpu(p).oper[0]^.reg;
  4497. if
  4498. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4499. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4500. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4501. begin
  4502. Result := True;
  4503. { Just in case something didn't get modified (e.g. an
  4504. implicit register). Also, if it does read from this
  4505. register, then there's no longer an advantage to
  4506. changing the register on subsequent instructions.}
  4507. if not RegReadByInstruction(p_TargetReg, hp2) then
  4508. begin
  4509. { If a conditional jump was crossed, do not delete
  4510. the original MOV no matter what }
  4511. if not CrossJump and
  4512. { RegEndOfLife returns True if the register is
  4513. deallocated before the next instruction or has
  4514. been loaded with a new value }
  4515. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4516. begin
  4517. { We can remove the original MOV }
  4518. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4519. RemoveCurrentp(p, hp1);
  4520. JumpTracking.Free;
  4521. Result := True;
  4522. Exit;
  4523. end;
  4524. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4525. begin
  4526. { See if there's more we can optimise }
  4527. hp3 := hp2;
  4528. Continue;
  4529. end;
  4530. end;
  4531. end;
  4532. end;
  4533. { Break out of the while loop under normal circumstances }
  4534. Break;
  4535. end;
  4536. JumpTracking.Free;
  4537. end;
  4538. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4539. (taicpu(p).oper[1]^.typ = top_reg) and
  4540. (taicpu(p).opsize = S_L) and
  4541. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4542. (hp2.typ = ait_instruction) and
  4543. (taicpu(hp2).opcode = A_AND) and
  4544. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4545. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4546. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4547. ) then
  4548. begin
  4549. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4550. begin
  4551. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4552. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4553. begin
  4554. { Optimize out:
  4555. mov x, %reg
  4556. and ffffffffh, %reg
  4557. }
  4558. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4559. RemoveInstruction(hp2);
  4560. Result:=true;
  4561. exit;
  4562. end;
  4563. end;
  4564. end;
  4565. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4566. x >= RetOffset) as it doesn't do anything (it writes either to a
  4567. parameter or to the temporary storage room for the function
  4568. result)
  4569. }
  4570. if IsExitCode(hp1) and
  4571. (taicpu(p).oper[1]^.typ = top_ref) and
  4572. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4573. (
  4574. (
  4575. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4576. not (
  4577. assigned(current_procinfo.procdef.funcretsym) and
  4578. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4579. )
  4580. ) or
  4581. { Also discard writes to the stack that are below the base pointer,
  4582. as this is temporary storage rather than a function result on the
  4583. stack, say. }
  4584. (
  4585. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4586. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4587. )
  4588. ) then
  4589. begin
  4590. RemoveCurrentp(p, hp1);
  4591. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4592. RemoveLastDeallocForFuncRes(p);
  4593. Result:=true;
  4594. exit;
  4595. end;
  4596. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4597. begin
  4598. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4599. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4600. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4601. begin
  4602. { change
  4603. mov reg1, mem1
  4604. test/cmp x, mem1
  4605. to
  4606. mov reg1, mem1
  4607. test/cmp x, reg1
  4608. }
  4609. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4610. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4611. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4612. Result := True;
  4613. Exit;
  4614. end;
  4615. if DoMovCmpMemOpt(p, hp1) then
  4616. begin
  4617. Result := True;
  4618. Exit;
  4619. end;
  4620. end;
  4621. if (taicpu(p).oper[1]^.typ = top_reg) and
  4622. (hp1.typ = ait_instruction) and
  4623. GetNextInstruction(hp1, hp2) and
  4624. MatchInstruction(hp2,A_MOV,[]) and
  4625. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4626. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4627. (
  4628. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4629. {$ifdef x86_64}
  4630. or
  4631. (
  4632. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4633. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4634. )
  4635. {$endif x86_64}
  4636. ) then
  4637. begin
  4638. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4639. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4640. { change movsX/movzX reg/ref, reg2
  4641. add/sub/or/... reg3/$const, reg2
  4642. mov reg2 reg/ref
  4643. dealloc reg2
  4644. to
  4645. add/sub/or/... reg3/$const, reg/ref }
  4646. begin
  4647. TransferUsedRegs(TmpUsedRegs);
  4648. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4649. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4650. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4651. begin
  4652. { by example:
  4653. movswl %si,%eax movswl %si,%eax p
  4654. decl %eax addl %edx,%eax hp1
  4655. movw %ax,%si movw %ax,%si hp2
  4656. ->
  4657. movswl %si,%eax movswl %si,%eax p
  4658. decw %eax addw %edx,%eax hp1
  4659. movw %ax,%si movw %ax,%si hp2
  4660. }
  4661. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4662. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4663. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4664. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4665. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4666. {
  4667. ->
  4668. movswl %si,%eax movswl %si,%eax p
  4669. decw %si addw %dx,%si hp1
  4670. movw %ax,%si movw %ax,%si hp2
  4671. }
  4672. case taicpu(hp1).ops of
  4673. 1:
  4674. begin
  4675. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4676. if taicpu(hp1).oper[0]^.typ=top_reg then
  4677. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4678. end;
  4679. 2:
  4680. begin
  4681. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4682. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4683. (taicpu(hp1).opcode<>A_SHL) and
  4684. (taicpu(hp1).opcode<>A_SHR) and
  4685. (taicpu(hp1).opcode<>A_SAR) then
  4686. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4687. end;
  4688. else
  4689. internalerror(2008042701);
  4690. end;
  4691. {
  4692. ->
  4693. decw %si addw %dx,%si p
  4694. }
  4695. RemoveInstruction(hp2);
  4696. RemoveCurrentP(p, hp1);
  4697. Result:=True;
  4698. Exit;
  4699. end;
  4700. end;
  4701. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4702. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4703. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4704. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4705. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4706. )
  4707. {$ifdef i386}
  4708. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4709. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4710. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4711. {$endif i386}
  4712. then
  4713. { change movsX/movzX reg/ref, reg2
  4714. add/sub/or/... regX/$const, reg2
  4715. mov reg2, reg3
  4716. dealloc reg2
  4717. to
  4718. movsX/movzX reg/ref, reg3
  4719. add/sub/or/... reg3/$const, reg3
  4720. }
  4721. begin
  4722. TransferUsedRegs(TmpUsedRegs);
  4723. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4724. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4725. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4726. begin
  4727. { by example:
  4728. movswl %si,%eax movswl %si,%eax p
  4729. decl %eax addl %edx,%eax hp1
  4730. movw %ax,%si movw %ax,%si hp2
  4731. ->
  4732. movswl %si,%eax movswl %si,%eax p
  4733. decw %eax addw %edx,%eax hp1
  4734. movw %ax,%si movw %ax,%si hp2
  4735. }
  4736. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4737. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4738. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4739. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4740. { limit size of constants as well to avoid assembler errors, but
  4741. check opsize to avoid overflow when left shifting the 1 }
  4742. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4743. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4744. {$ifdef x86_64}
  4745. { Be careful of, for example:
  4746. movl %reg1,%reg2
  4747. addl %reg3,%reg2
  4748. movq %reg2,%reg4
  4749. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4750. }
  4751. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4752. begin
  4753. taicpu(hp2).changeopsize(S_L);
  4754. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4755. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4756. end;
  4757. {$endif x86_64}
  4758. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4759. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4760. if taicpu(p).oper[0]^.typ=top_reg then
  4761. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4762. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4763. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4764. {
  4765. ->
  4766. movswl %si,%eax movswl %si,%eax p
  4767. decw %si addw %dx,%si hp1
  4768. movw %ax,%si movw %ax,%si hp2
  4769. }
  4770. case taicpu(hp1).ops of
  4771. 1:
  4772. begin
  4773. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4774. if taicpu(hp1).oper[0]^.typ=top_reg then
  4775. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4776. end;
  4777. 2:
  4778. begin
  4779. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4780. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4781. (taicpu(hp1).opcode<>A_SHL) and
  4782. (taicpu(hp1).opcode<>A_SHR) and
  4783. (taicpu(hp1).opcode<>A_SAR) then
  4784. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4785. end;
  4786. else
  4787. internalerror(2018111801);
  4788. end;
  4789. {
  4790. ->
  4791. decw %si addw %dx,%si p
  4792. }
  4793. RemoveInstruction(hp2);
  4794. end;
  4795. end;
  4796. end;
  4797. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4798. GetNextInstruction(hp1, hp2) and
  4799. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4800. MatchOperand(Taicpu(p).oper[0]^,0) and
  4801. (Taicpu(p).oper[1]^.typ = top_reg) and
  4802. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4803. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4804. { mov reg1,0
  4805. bts reg1,operand1 --> mov reg1,operand2
  4806. or reg1,operand2 bts reg1,operand1}
  4807. begin
  4808. Taicpu(hp2).opcode:=A_MOV;
  4809. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4810. asml.remove(hp1);
  4811. insertllitem(hp2,hp2.next,hp1);
  4812. RemoveCurrentp(p, hp1);
  4813. Result:=true;
  4814. exit;
  4815. end;
  4816. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4817. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4818. GetNextInstruction(hp1, hp2) and
  4819. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4820. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4821. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4822. { change
  4823. mov reg1,reg2
  4824. sub reg3,reg2
  4825. cmp reg3,reg1
  4826. into
  4827. mov reg1,reg2
  4828. sub reg3,reg2
  4829. }
  4830. begin
  4831. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4832. RemoveInstruction(hp2);
  4833. Result:=true;
  4834. exit;
  4835. end;
  4836. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4837. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4838. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4839. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4840. begin
  4841. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4842. {$ifdef x86_64}
  4843. { Convert:
  4844. movq x(ref),%reg64
  4845. shrq y,%reg64
  4846. To:
  4847. movl x+4(ref),%reg32
  4848. shrl y-32,%reg32 (Remove if y = 32)
  4849. }
  4850. if (taicpu(p).opsize = S_Q) and
  4851. (taicpu(hp1).opcode = A_SHR) and
  4852. (taicpu(hp1).oper[0]^.val >= 32) then
  4853. begin
  4854. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4855. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4856. { Convert to 32-bit }
  4857. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4858. taicpu(p).opsize := S_L;
  4859. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4860. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4861. if (taicpu(hp1).oper[0]^.val = 32) then
  4862. begin
  4863. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4864. RemoveInstruction(hp1);
  4865. end
  4866. else
  4867. begin
  4868. { This will potentially open up more arithmetic operations since
  4869. the peephole optimizer now has a big hint that only the lower
  4870. 32 bits are currently in use (and opcodes are smaller in size) }
  4871. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4872. taicpu(hp1).opsize := S_L;
  4873. Dec(taicpu(hp1).oper[0]^.val, 32);
  4874. DebugMsg(SPeepholeOptimization + PreMessage +
  4875. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4876. end;
  4877. Result := True;
  4878. Exit;
  4879. end;
  4880. {$endif x86_64}
  4881. { Convert:
  4882. movl x(ref),%reg
  4883. shrl $24,%reg
  4884. To:
  4885. movzbl x+3(ref),%reg
  4886. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4887. Also accept sar instead of shr, but convert to movsx instead of movzx
  4888. }
  4889. if taicpu(hp1).opcode = A_SHR then
  4890. MovUnaligned := A_MOVZX
  4891. else
  4892. MovUnaligned := A_MOVSX;
  4893. NewSize := S_NO;
  4894. NewOffset := 0;
  4895. case taicpu(p).opsize of
  4896. S_B:
  4897. { No valid combinations };
  4898. S_W:
  4899. if (taicpu(hp1).oper[0]^.val = 8) then
  4900. begin
  4901. NewSize := S_BW;
  4902. NewOffset := 1;
  4903. end;
  4904. S_L:
  4905. case taicpu(hp1).oper[0]^.val of
  4906. 16:
  4907. begin
  4908. NewSize := S_WL;
  4909. NewOffset := 2;
  4910. end;
  4911. 24:
  4912. begin
  4913. NewSize := S_BL;
  4914. NewOffset := 3;
  4915. end;
  4916. else
  4917. ;
  4918. end;
  4919. {$ifdef x86_64}
  4920. S_Q:
  4921. case taicpu(hp1).oper[0]^.val of
  4922. 32:
  4923. begin
  4924. if taicpu(hp1).opcode = A_SAR then
  4925. begin
  4926. { 32-bit to 64-bit is a distinct instruction }
  4927. MovUnaligned := A_MOVSXD;
  4928. NewSize := S_LQ;
  4929. NewOffset := 4;
  4930. end
  4931. else
  4932. { Should have been handled by MovShr2Mov above }
  4933. InternalError(2022081811);
  4934. end;
  4935. 48:
  4936. begin
  4937. NewSize := S_WQ;
  4938. NewOffset := 6;
  4939. end;
  4940. 56:
  4941. begin
  4942. NewSize := S_BQ;
  4943. NewOffset := 7;
  4944. end;
  4945. else
  4946. ;
  4947. end;
  4948. {$endif x86_64}
  4949. else
  4950. InternalError(2022081810);
  4951. end;
  4952. if (NewSize <> S_NO) and
  4953. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4954. begin
  4955. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4956. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4957. debug_op2str(MovUnaligned);
  4958. {$ifdef x86_64}
  4959. if MovUnaligned <> A_MOVSXD then
  4960. { Don't add size suffix for MOVSXD }
  4961. {$endif x86_64}
  4962. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4963. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4964. taicpu(p).opcode := MovUnaligned;
  4965. taicpu(p).opsize := NewSize;
  4966. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4967. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4968. RemoveInstruction(hp1);
  4969. Result := True;
  4970. Exit;
  4971. end;
  4972. end;
  4973. { Backward optimisation shared with OptPass2MOV }
  4974. if FuncMov2Func(p, hp1) then
  4975. begin
  4976. Result := True;
  4977. Exit;
  4978. end;
  4979. end;
  4980. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4981. var
  4982. hp1 : tai;
  4983. begin
  4984. Result:=false;
  4985. if taicpu(p).ops <> 2 then
  4986. exit;
  4987. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4988. GetNextInstruction(p,hp1) then
  4989. begin
  4990. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4991. (taicpu(hp1).ops = 2) then
  4992. begin
  4993. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4994. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4995. { movXX reg1, mem1 or movXX mem1, reg1
  4996. movXX mem2, reg2 movXX reg2, mem2}
  4997. begin
  4998. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4999. { movXX reg1, mem1 or movXX mem1, reg1
  5000. movXX mem2, reg1 movXX reg2, mem1}
  5001. begin
  5002. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5003. begin
  5004. { Removes the second statement from
  5005. movXX reg1, mem1/reg2
  5006. movXX mem1/reg2, reg1
  5007. }
  5008. if taicpu(p).oper[0]^.typ=top_reg then
  5009. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  5010. { Removes the second statement from
  5011. movXX mem1/reg1, reg2
  5012. movXX reg2, mem1/reg1
  5013. }
  5014. if (taicpu(p).oper[1]^.typ=top_reg) and
  5015. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  5016. begin
  5017. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  5018. RemoveInstruction(hp1);
  5019. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5020. Result:=true;
  5021. exit;
  5022. end
  5023. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5024. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5025. begin
  5026. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5027. RemoveInstruction(hp1);
  5028. Result:=true;
  5029. exit;
  5030. end;
  5031. end
  5032. end;
  5033. end;
  5034. end;
  5035. end;
  5036. end;
  5037. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5038. var
  5039. hp1 : tai;
  5040. begin
  5041. result:=false;
  5042. { replace
  5043. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5044. MovX %mreg2,%mreg1
  5045. dealloc %mreg2
  5046. by
  5047. <Op>X %mreg2,%mreg1
  5048. ?
  5049. }
  5050. if GetNextInstruction(p,hp1) and
  5051. { we mix single and double opperations here because we assume that the compiler
  5052. generates vmovapd only after double operations and vmovaps only after single operations }
  5053. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5054. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5055. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5056. (taicpu(p).oper[0]^.typ=top_reg) then
  5057. begin
  5058. TransferUsedRegs(TmpUsedRegs);
  5059. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5060. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5061. begin
  5062. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5063. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5064. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5065. RemoveInstruction(hp1);
  5066. result:=true;
  5067. end;
  5068. end;
  5069. end;
  5070. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5071. var
  5072. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5073. JumpLabel, JumpLabel_dist: TAsmLabel;
  5074. FirstValue, SecondValue: TCGInt;
  5075. function OptimizeJump(var InputP: tai): Boolean;
  5076. var
  5077. TempBool: Boolean;
  5078. begin
  5079. Result := False;
  5080. TempBool := True;
  5081. if DoJumpOptimizations(InputP, TempBool) or
  5082. not TempBool then
  5083. begin
  5084. Result := True;
  5085. if Assigned(InputP) then
  5086. begin
  5087. { CollapseZeroDistJump will be set to the label or an align
  5088. before it after the jump if it optimises, whether or not
  5089. the label is live or dead }
  5090. if (InputP.typ = ait_align) or
  5091. (
  5092. (InputP.typ = ait_label) and
  5093. not (tai_label(InputP).labsym.is_used)
  5094. ) then
  5095. GetNextInstruction(InputP, InputP);
  5096. end;
  5097. Exit;
  5098. end;
  5099. end;
  5100. begin
  5101. Result := False;
  5102. if (taicpu(p).oper[0]^.typ = top_const) and
  5103. (taicpu(p).oper[0]^.val <> -1) then
  5104. begin
  5105. { Convert unsigned maximum constants to -1 to aid optimisation }
  5106. case taicpu(p).opsize of
  5107. S_B:
  5108. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5109. begin
  5110. taicpu(p).oper[0]^.val := -1;
  5111. Result := True;
  5112. Exit;
  5113. end;
  5114. S_W:
  5115. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5116. begin
  5117. taicpu(p).oper[0]^.val := -1;
  5118. Result := True;
  5119. Exit;
  5120. end;
  5121. S_L:
  5122. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5123. begin
  5124. taicpu(p).oper[0]^.val := -1;
  5125. Result := True;
  5126. Exit;
  5127. end;
  5128. {$ifdef x86_64}
  5129. S_Q:
  5130. { Storing anything greater than $7FFFFFFF is not possible so do
  5131. nothing };
  5132. {$endif x86_64}
  5133. else
  5134. InternalError(2021121001);
  5135. end;
  5136. end;
  5137. if GetNextInstruction(p, hp1) and
  5138. TrySwapMovCmp(p, hp1) then
  5139. begin
  5140. Result := True;
  5141. Exit;
  5142. end;
  5143. p_label := nil;
  5144. JumpLabel := nil;
  5145. if MatchInstruction(hp1, A_Jcc, []) then
  5146. begin
  5147. if OptimizeJump(hp1) then
  5148. begin
  5149. Result := True;
  5150. if Assigned(hp1) then
  5151. begin
  5152. { CollapseZeroDistJump will be set to the label or an align
  5153. before it after the jump if it optimises, whether or not
  5154. the label is live or dead }
  5155. if (hp1.typ = ait_align) or
  5156. (
  5157. (hp1.typ = ait_label) and
  5158. not (tai_label(hp1).labsym.is_used)
  5159. ) then
  5160. GetNextInstruction(hp1, hp1);
  5161. end;
  5162. TransferUsedRegs(TmpUsedRegs);
  5163. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5164. if not Assigned(hp1) or
  5165. (
  5166. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5167. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5168. ) then
  5169. begin
  5170. { No more conditional jumps; conditional statement is no longer required }
  5171. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5172. RemoveCurrentP(p);
  5173. end;
  5174. Exit;
  5175. end;
  5176. if IsJumpToLabel(taicpu(hp1)) then
  5177. begin
  5178. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5179. if Assigned(JumpLabel) then
  5180. p_label := getlabelwithsym(JumpLabel);
  5181. end;
  5182. end;
  5183. { Search for:
  5184. test $x,(reg/ref)
  5185. jne @lbl1
  5186. test $y,(reg/ref) (same register or reference)
  5187. jne @lbl1
  5188. Change to:
  5189. test $(x or y),(reg/ref)
  5190. jne @lbl1
  5191. (Note, this doesn't work with je instead of jne)
  5192. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5193. Also search for:
  5194. test $x,(reg/ref)
  5195. je @lbl1
  5196. ...
  5197. test $y,(reg/ref)
  5198. je/jne @lbl2
  5199. If (x or y) = x, then the second jump is deterministic
  5200. }
  5201. if (
  5202. (
  5203. (taicpu(p).oper[0]^.typ = top_const) or
  5204. (
  5205. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5206. (taicpu(p).oper[0]^.typ = top_reg) and
  5207. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5208. )
  5209. ) and
  5210. MatchInstruction(hp1, A_JCC, [])
  5211. ) then
  5212. begin
  5213. if (taicpu(p).oper[0]^.typ = top_reg) and
  5214. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5215. FirstValue := -1
  5216. else
  5217. FirstValue := taicpu(p).oper[0]^.val;
  5218. { If we have several test/jne's in a row, it might be the case that
  5219. the second label doesn't go to the same location, but the one
  5220. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5221. so accommodate for this with a while loop.
  5222. }
  5223. hp1_last := hp1;
  5224. while (
  5225. (
  5226. (taicpu(p).oper[1]^.typ = top_reg) and
  5227. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5228. ) or GetNextInstruction(hp1_last, p_dist)
  5229. ) and (p_dist.typ = ait_instruction) do
  5230. begin
  5231. if (
  5232. (
  5233. (taicpu(p_dist).opcode = A_TEST) and
  5234. (
  5235. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5236. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5237. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5238. )
  5239. ) or
  5240. (
  5241. { cmp 0,%reg = test %reg,%reg }
  5242. (taicpu(p_dist).opcode = A_CMP) and
  5243. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5244. )
  5245. ) and
  5246. { Make sure the destination operands are actually the same }
  5247. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5248. GetNextInstruction(p_dist, hp1_dist) and
  5249. MatchInstruction(hp1_dist, A_JCC, []) then
  5250. begin
  5251. if OptimizeJump(hp1_dist) then
  5252. begin
  5253. Result := True;
  5254. Exit;
  5255. end;
  5256. if
  5257. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5258. (
  5259. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5260. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5261. ) then
  5262. SecondValue := -1
  5263. else
  5264. SecondValue := taicpu(p_dist).oper[0]^.val;
  5265. { If both of the TEST constants are identical, delete the
  5266. second TEST that is unnecessary (be careful though, just
  5267. in case the flags are modified in between) }
  5268. if (FirstValue = SecondValue) then
  5269. begin
  5270. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5271. begin
  5272. { Since the second jump's condition is a subset of the first, we
  5273. know it will never branch because the first jump dominates it.
  5274. Get it out of the way now rather than wait for the jump
  5275. optimisations for a speed boost. }
  5276. if IsJumpToLabel(taicpu(hp1_dist)) then
  5277. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5278. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5279. RemoveInstruction(hp1_dist);
  5280. Result := True;
  5281. end
  5282. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5283. begin
  5284. { If the inverse of the first condition is a subset of the second,
  5285. the second one will definitely branch if the first one doesn't }
  5286. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5287. { We can remove the TEST instruction too }
  5288. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5289. RemoveInstruction(p_dist);
  5290. MakeUnconditional(taicpu(hp1_dist));
  5291. RemoveDeadCodeAfterJump(hp1_dist);
  5292. { Since the jump is now unconditional, we can't
  5293. continue any further with this particular
  5294. optimisation. The original TEST is still intact
  5295. though, so there might be something else we can
  5296. do }
  5297. Include(OptsToCheck, aoc_ForceNewIteration);
  5298. Break;
  5299. end;
  5300. if Result or
  5301. { If a jump wasn't removed or made unconditional, only
  5302. remove the identical TEST instruction if the flags
  5303. weren't modified }
  5304. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5305. begin
  5306. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5307. RemoveInstruction(p_dist);
  5308. { If the jump was removed or made unconditional, we
  5309. don't need to allocate NR_DEFAULTFLAGS over the
  5310. entire range }
  5311. if not Result then
  5312. begin
  5313. { Mark the flags as 'in use' over the entire range }
  5314. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5315. { Speed gain - continue search from the Jcc instruction }
  5316. hp1_last := hp1_dist;
  5317. { Only the TEST instruction was removed, and the
  5318. original was unchanged, so we can safely do
  5319. another iteration of the while loop }
  5320. Include(OptsToCheck, aoc_ForceNewIteration);
  5321. Continue;
  5322. end;
  5323. Exit;
  5324. end;
  5325. end;
  5326. hp1_last := nil;
  5327. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5328. (
  5329. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5330. { Always adjacent under -O2 and under }
  5331. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5332. (
  5333. GetNextInstruction(hp1, hp1_last) and
  5334. (hp1_last = p_dist)
  5335. )
  5336. ) and
  5337. (
  5338. (
  5339. { Test the following variant:
  5340. test $x,(reg/ref)
  5341. jne @lbl1
  5342. test $y,(reg/ref)
  5343. je @lbl2
  5344. @lbl1:
  5345. Becomes:
  5346. test $(x or y),(reg/ref)
  5347. je @lbl2
  5348. @lbl1: (may become a dead label)
  5349. }
  5350. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5351. GetNextInstruction(hp1_dist, hp1_last) and
  5352. (hp1_last = p_label)
  5353. ) or
  5354. (
  5355. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5356. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5357. then the second jump will never branch, so it can also be
  5358. removed regardless of where it goes }
  5359. (
  5360. (FirstValue = -1) or
  5361. (SecondValue = -1) or
  5362. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5363. )
  5364. )
  5365. ) then
  5366. begin
  5367. { Same jump location... can be a register since nothing's changed }
  5368. { If any of the entries are equivalent to test %reg,%reg, then the
  5369. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5370. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5371. if (hp1_last = p_label) then
  5372. begin
  5373. { Variant }
  5374. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5375. RemoveInstruction(p_dist);
  5376. if Assigned(JumpLabel) then
  5377. JumpLabel.decrefs;
  5378. RemoveInstruction(hp1);
  5379. end
  5380. else
  5381. begin
  5382. { Only remove the second test if no jumps or other conditional instructions follow }
  5383. TransferUsedRegs(TmpUsedRegs);
  5384. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5385. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5386. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5387. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5388. begin
  5389. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5390. RemoveInstruction(p_dist);
  5391. { Remove the first jump, not the second, to keep
  5392. any register deallocations between the second
  5393. TEST/JNE pair in the same place. Aids future
  5394. optimisation. }
  5395. if Assigned(JumpLabel) then
  5396. JumpLabel.decrefs;
  5397. RemoveInstruction(hp1);
  5398. end
  5399. else
  5400. begin
  5401. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5402. if IsJumpToLabel(taicpu(hp1_dist)) then
  5403. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5404. { Remove second jump in this instance }
  5405. RemoveInstruction(hp1_dist);
  5406. end;
  5407. end;
  5408. Result := True;
  5409. Exit;
  5410. end;
  5411. end;
  5412. if { If -O2 and under, it may stop on any old instruction }
  5413. (cs_opt_level3 in current_settings.optimizerswitches) and
  5414. (taicpu(p).oper[1]^.typ = top_reg) and
  5415. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5416. begin
  5417. hp1_last := p_dist;
  5418. Continue;
  5419. end;
  5420. Break;
  5421. end;
  5422. end;
  5423. { Search for:
  5424. test %reg,%reg
  5425. j(c1) @lbl1
  5426. ...
  5427. @lbl:
  5428. test %reg,%reg (same register)
  5429. j(c2) @lbl2
  5430. If c2 is a subset of c1, change to:
  5431. test %reg,%reg
  5432. j(c1) @lbl2
  5433. (@lbl1 may become a dead label as a result)
  5434. }
  5435. if (taicpu(p).oper[1]^.typ = top_reg) and
  5436. (taicpu(p).oper[0]^.typ = top_reg) and
  5437. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5438. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5439. Assigned(p_label) and
  5440. GetNextInstruction(p_label, p_dist) and
  5441. MatchInstruction(p_dist, A_TEST, []) and
  5442. { It's fine if the second test uses smaller sub-registers }
  5443. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5444. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5445. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5446. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5447. GetNextInstruction(p_dist, hp1_dist) and
  5448. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5449. begin
  5450. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5451. if JumpLabel = JumpLabel_dist then
  5452. { This is an infinite loop }
  5453. Exit;
  5454. { Best optimisation when the first condition is a subset (or equal) of the second }
  5455. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5456. begin
  5457. { Any registers used here will already be allocated }
  5458. if Assigned(JumpLabel) then
  5459. JumpLabel.DecRefs;
  5460. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5461. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5462. Result := True;
  5463. Exit;
  5464. end;
  5465. end;
  5466. end;
  5467. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5468. var
  5469. hp1, hp2: tai;
  5470. ActiveReg: TRegister;
  5471. OldOffset: asizeint;
  5472. ThisConst: TCGInt;
  5473. function RegDeallocated: Boolean;
  5474. begin
  5475. TransferUsedRegs(TmpUsedRegs);
  5476. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5477. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5478. end;
  5479. begin
  5480. result:=false;
  5481. hp1 := nil;
  5482. { replace
  5483. addX const,%reg1
  5484. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5485. dealloc %reg1
  5486. by
  5487. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5488. }
  5489. if MatchOpType(taicpu(p),top_const,top_reg) then
  5490. begin
  5491. ActiveReg := taicpu(p).oper[1]^.reg;
  5492. { Ensures the entire register was updated }
  5493. if (taicpu(p).opsize >= S_L) and
  5494. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5495. MatchInstruction(hp1,A_LEA,[]) and
  5496. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5497. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5498. (
  5499. { Cover the case where the register in the reference is also the destination register }
  5500. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5501. (
  5502. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5503. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5504. RegDeallocated
  5505. )
  5506. ) then
  5507. begin
  5508. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5509. {$push}
  5510. {$R-}{$Q-}
  5511. { Explicitly disable overflow checking for these offset calculation
  5512. as those do not matter for the final result }
  5513. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5514. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5515. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5516. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5517. {$pop}
  5518. {$ifdef x86_64}
  5519. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5520. begin
  5521. { Overflow; abort }
  5522. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5523. end
  5524. else
  5525. {$endif x86_64}
  5526. begin
  5527. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5528. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5529. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5530. RemoveCurrentP(p, hp1)
  5531. else
  5532. RemoveCurrentP(p);
  5533. result:=true;
  5534. Exit;
  5535. end;
  5536. end;
  5537. if (
  5538. { Save calling GetNextInstructionUsingReg again }
  5539. Assigned(hp1) or
  5540. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5541. ) and
  5542. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5543. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5544. begin
  5545. if taicpu(hp1).oper[0]^.typ = top_const then
  5546. begin
  5547. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5548. if taicpu(hp1).opcode = A_ADD then
  5549. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5550. else
  5551. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5552. Result := True;
  5553. { Handle any overflows }
  5554. case taicpu(p).opsize of
  5555. S_B:
  5556. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5557. S_W:
  5558. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5559. S_L:
  5560. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5561. {$ifdef x86_64}
  5562. S_Q:
  5563. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5564. { Overflow; abort }
  5565. Result := False
  5566. else
  5567. taicpu(p).oper[0]^.val := ThisConst;
  5568. {$endif x86_64}
  5569. else
  5570. InternalError(2021102610);
  5571. end;
  5572. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5573. if Result then
  5574. begin
  5575. if (taicpu(p).oper[0]^.val < 0) and
  5576. (
  5577. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5578. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5579. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5580. ) then
  5581. begin
  5582. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5583. taicpu(p).opcode := A_SUB;
  5584. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5585. end
  5586. else
  5587. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5588. RemoveInstruction(hp1);
  5589. end;
  5590. end
  5591. else
  5592. begin
  5593. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5594. TransferUsedRegs(TmpUsedRegs);
  5595. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5596. hp2 := p;
  5597. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5598. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5599. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5600. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5601. begin
  5602. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5603. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5604. Asml.Remove(p);
  5605. Asml.InsertAfter(p, hp1);
  5606. p := hp1;
  5607. Result := True;
  5608. Exit;
  5609. end;
  5610. end;
  5611. end;
  5612. if DoArithCombineOpt(p) then
  5613. Result:=true;
  5614. end;
  5615. end;
  5616. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5617. var
  5618. hp1, hp2: tai;
  5619. ref: Integer;
  5620. saveref: treference;
  5621. offsetcalc: Int64;
  5622. TempReg: TRegister;
  5623. Multiple: TCGInt;
  5624. Adjacent, IntermediateRegDiscarded: Boolean;
  5625. begin
  5626. Result:=false;
  5627. { play save and throw an error if LEA uses a seg register prefix,
  5628. this is most likely an error somewhere else }
  5629. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5630. internalerror(2022022001);
  5631. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5632. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5633. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5634. (
  5635. { do not mess with leas accessing the stack pointer
  5636. unless it's a null operation }
  5637. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5638. (
  5639. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5640. (taicpu(p).oper[0]^.ref^.offset = 0)
  5641. )
  5642. ) and
  5643. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5644. begin
  5645. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5646. begin
  5647. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5648. begin
  5649. taicpu(p).opcode := A_MOV;
  5650. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5651. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5652. end
  5653. else
  5654. begin
  5655. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5656. RemoveCurrentP(p);
  5657. end;
  5658. Result:=true;
  5659. exit;
  5660. end
  5661. else if (
  5662. { continue to use lea to adjust the stack pointer,
  5663. it is the recommended way, but only if not optimizing for size }
  5664. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5665. (cs_opt_size in current_settings.optimizerswitches)
  5666. ) and
  5667. { If the flags register is in use, don't change the instruction
  5668. to an ADD otherwise this will scramble the flags. [Kit] }
  5669. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5670. ConvertLEA(taicpu(p)) then
  5671. begin
  5672. Result:=true;
  5673. exit;
  5674. end;
  5675. end;
  5676. { Don't optimise if the stack or frame pointer is the destination register }
  5677. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5678. Exit;
  5679. if GetNextInstruction(p,hp1) and
  5680. (hp1.typ=ait_instruction) then
  5681. begin
  5682. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5683. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5684. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5685. begin
  5686. TransferUsedRegs(TmpUsedRegs);
  5687. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5688. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5689. begin
  5690. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5691. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5692. RemoveInstruction(hp1);
  5693. result:=true;
  5694. exit;
  5695. end;
  5696. end;
  5697. { changes
  5698. lea <ref1>, reg1
  5699. <op> ...,<ref. with reg1>,...
  5700. to
  5701. <op> ...,<ref1>,... }
  5702. { find a reference which uses reg1 }
  5703. 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
  5704. ref:=0
  5705. 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
  5706. ref:=1
  5707. else
  5708. ref:=-1;
  5709. if (ref<>-1) and
  5710. { reg1 must be either the base or the index }
  5711. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5712. begin
  5713. { reg1 can be removed from the reference }
  5714. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5715. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5716. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5717. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5718. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5719. else
  5720. Internalerror(2019111201);
  5721. { check if the can insert all data of the lea into the second instruction }
  5722. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5723. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5724. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5725. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5726. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5727. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5728. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5729. {$ifdef x86_64}
  5730. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5731. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5732. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5733. )
  5734. {$endif x86_64}
  5735. then
  5736. begin
  5737. { reg1 might not used by the second instruction after it is remove from the reference }
  5738. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5739. begin
  5740. TransferUsedRegs(TmpUsedRegs);
  5741. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5742. { reg1 is not updated so it might not be used afterwards }
  5743. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5744. begin
  5745. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5746. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5747. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5748. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5749. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5750. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5751. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5752. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5753. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5754. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5755. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5756. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5757. RemoveCurrentP(p, hp1);
  5758. result:=true;
  5759. exit;
  5760. end
  5761. end;
  5762. end;
  5763. { recover }
  5764. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5765. end;
  5766. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5767. if Adjacent or
  5768. { Check further ahead (up to 2 instructions ahead for -O2) }
  5769. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5770. begin
  5771. { Check common LEA/LEA conditions }
  5772. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5773. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5774. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5775. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5776. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5777. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5778. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5779. (
  5780. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5781. calling it (since it calls GetNextInstruction) }
  5782. Adjacent or
  5783. (
  5784. (
  5785. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5786. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5787. ) and (
  5788. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5789. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5790. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5791. )
  5792. )
  5793. ) then
  5794. begin
  5795. TransferUsedRegs(TmpUsedRegs);
  5796. hp2 := p;
  5797. repeat
  5798. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5799. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5800. IntermediateRegDiscarded :=
  5801. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5802. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5803. { changes
  5804. lea offset1(regX,scale), reg1
  5805. lea offset2(reg1,reg1), reg2
  5806. to
  5807. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5808. and
  5809. lea offset1(regX,scale1), reg1
  5810. lea offset2(reg1,scale2), reg2
  5811. to
  5812. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5813. and
  5814. lea offset1(regX,scale1), reg1
  5815. lea offset2(reg3,reg1,scale2), reg2
  5816. to
  5817. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5818. ... so long as the final scale does not exceed 8
  5819. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5820. }
  5821. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5822. (
  5823. { Don't optimise if size is a concern and the intermediate register remains in use }
  5824. IntermediateRegDiscarded or
  5825. not (cs_opt_size in current_settings.optimizerswitches)
  5826. ) and
  5827. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5828. (
  5829. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5830. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5831. ) and (
  5832. (
  5833. { lea (reg1,scale2), reg2 variant }
  5834. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5835. (
  5836. Adjacent or
  5837. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5838. ) and
  5839. (
  5840. (
  5841. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5842. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5843. ) or (
  5844. { lea (regX,regX), reg1 variant }
  5845. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5846. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5847. )
  5848. )
  5849. ) or (
  5850. { lea (reg1,reg1), reg1 variant }
  5851. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5852. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5853. )
  5854. ) then
  5855. begin
  5856. { Make everything homogeneous to make calculations easier }
  5857. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5858. begin
  5859. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5860. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5861. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5862. else
  5863. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5864. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5865. end;
  5866. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5867. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5868. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5869. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5870. begin
  5871. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5872. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5873. begin
  5874. { Put the register to change in the index register }
  5875. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5876. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5877. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5878. end;
  5879. { Change lea (reg,reg) to lea(,reg,2) }
  5880. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5881. begin
  5882. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5883. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5884. end;
  5885. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5886. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5887. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5888. { Just to prevent miscalculations }
  5889. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5890. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5891. else
  5892. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5893. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5894. if IntermediateRegDiscarded then
  5895. begin
  5896. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5897. RemoveCurrentP(p);
  5898. end
  5899. else
  5900. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5901. result:=true;
  5902. exit;
  5903. end;
  5904. end;
  5905. { changes
  5906. lea offset1(regX), reg1
  5907. lea offset2(reg1), reg2
  5908. to
  5909. lea offset1+offset2(regX), reg2 }
  5910. if (
  5911. { Don't optimise if size is a concern and the intermediate register remains in use }
  5912. IntermediateRegDiscarded or
  5913. not (cs_opt_size in current_settings.optimizerswitches)
  5914. ) and
  5915. (
  5916. (
  5917. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5918. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5919. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5920. ) or (
  5921. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5922. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5923. (
  5924. (
  5925. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5926. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5927. ) or (
  5928. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5929. (
  5930. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5931. (
  5932. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5933. (
  5934. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5935. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5936. )
  5937. )
  5938. )
  5939. )
  5940. )
  5941. )
  5942. ) then
  5943. begin
  5944. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5945. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5946. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5947. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5948. begin
  5949. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5950. begin
  5951. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5952. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5953. { if the register is used as index and base, we have to increase for base as well
  5954. and adapt base }
  5955. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5956. begin
  5957. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5958. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5959. end;
  5960. end
  5961. else
  5962. begin
  5963. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5964. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5965. end;
  5966. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5967. begin
  5968. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5969. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5970. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5971. { Catch the situation where the base = index
  5972. and treat this as *2. The scalefactor of
  5973. p will be 0 or 1 due to the conditional
  5974. checks above. Fixes i40647 }
  5975. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5976. else
  5977. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5978. end;
  5979. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5980. if IntermediateRegDiscarded then
  5981. begin
  5982. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5983. RemoveCurrentP(p);
  5984. end
  5985. else
  5986. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5987. result:=true;
  5988. exit;
  5989. end;
  5990. end;
  5991. end;
  5992. { Change:
  5993. leal/q $x(%reg1),%reg2
  5994. ...
  5995. shll/q $y,%reg2
  5996. To:
  5997. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5998. }
  5999. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6000. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  6001. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6002. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6003. (taicpu(hp1).oper[0]^.val <= 3) then
  6004. begin
  6005. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  6006. TransferUsedRegs(TmpUsedRegs);
  6007. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6008. if
  6009. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  6010. (this works even if scalefactor is zero) }
  6011. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  6012. { Ensure offset doesn't go out of bounds }
  6013. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  6014. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  6015. (
  6016. (
  6017. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  6018. (
  6019. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6020. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6021. (
  6022. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6023. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6024. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6025. )
  6026. )
  6027. ) or (
  6028. (
  6029. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6030. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6031. ) and
  6032. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6033. )
  6034. ) then
  6035. begin
  6036. repeat
  6037. with taicpu(p).oper[0]^.ref^ do
  6038. begin
  6039. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6040. if index = base then
  6041. begin
  6042. if Multiple > 4 then
  6043. { Optimisation will no longer work because resultant
  6044. scale factor will exceed 8 }
  6045. Break;
  6046. base := NR_NO;
  6047. scalefactor := 2;
  6048. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6049. end
  6050. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6051. begin
  6052. { Scale factor only works on the index register }
  6053. index := base;
  6054. base := NR_NO;
  6055. end;
  6056. { For safety }
  6057. if scalefactor <= 1 then
  6058. begin
  6059. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6060. scalefactor := Multiple;
  6061. end
  6062. else
  6063. begin
  6064. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6065. scalefactor := scalefactor * Multiple;
  6066. end;
  6067. offset := offset * Multiple;
  6068. end;
  6069. RemoveInstruction(hp1);
  6070. Result := True;
  6071. Exit;
  6072. { This repeat..until loop exists for the benefit of Break }
  6073. until True;
  6074. end;
  6075. end;
  6076. end;
  6077. end;
  6078. end;
  6079. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6080. var
  6081. hp1 : tai;
  6082. SubInstr: Boolean;
  6083. ThisConst: TCGInt;
  6084. const
  6085. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6086. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6087. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6088. begin
  6089. Result := False;
  6090. if taicpu(p).oper[0]^.typ <> top_const then
  6091. { Should have been confirmed before calling }
  6092. InternalError(2021102601);
  6093. SubInstr := (taicpu(p).opcode = A_SUB);
  6094. if GetLastInstruction(p, hp1) and
  6095. (hp1.typ = ait_instruction) and
  6096. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6097. begin
  6098. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6099. { Bad size }
  6100. InternalError(2022042001);
  6101. case taicpu(hp1).opcode Of
  6102. A_INC:
  6103. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6104. begin
  6105. if SubInstr then
  6106. ThisConst := taicpu(p).oper[0]^.val - 1
  6107. else
  6108. ThisConst := taicpu(p).oper[0]^.val + 1;
  6109. end
  6110. else
  6111. Exit;
  6112. A_DEC:
  6113. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6114. begin
  6115. if SubInstr then
  6116. ThisConst := taicpu(p).oper[0]^.val + 1
  6117. else
  6118. ThisConst := taicpu(p).oper[0]^.val - 1;
  6119. end
  6120. else
  6121. Exit;
  6122. A_SUB:
  6123. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6124. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6125. begin
  6126. if SubInstr then
  6127. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6128. else
  6129. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6130. end
  6131. else
  6132. Exit;
  6133. A_ADD:
  6134. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6135. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6136. begin
  6137. if SubInstr then
  6138. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6139. else
  6140. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6141. end
  6142. else
  6143. Exit;
  6144. else
  6145. Exit;
  6146. end;
  6147. { Check that the values are in range }
  6148. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6149. { Overflow; abort }
  6150. Exit;
  6151. if (ThisConst = 0) then
  6152. begin
  6153. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6154. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6155. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6156. RemoveInstruction(hp1);
  6157. hp1 := tai(p.next);
  6158. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6159. if not GetLastInstruction(hp1, p) then
  6160. p := hp1;
  6161. end
  6162. else
  6163. begin
  6164. if taicpu(hp1).opercnt=1 then
  6165. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6166. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6167. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6168. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6169. else
  6170. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6171. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6172. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6173. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6174. RemoveInstruction(hp1);
  6175. taicpu(p).loadconst(0, ThisConst);
  6176. end;
  6177. Result := True;
  6178. end;
  6179. end;
  6180. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6181. begin
  6182. Result := False;
  6183. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6184. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6185. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6186. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6187. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6188. (
  6189. (
  6190. (taicpu(hp1).opcode = A_TEST)
  6191. ) or (
  6192. (taicpu(hp1).opcode = A_CMP) and
  6193. { A sanity check more than anything }
  6194. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6195. )
  6196. ) then
  6197. begin
  6198. { change
  6199. mov mem, %reg
  6200. ...
  6201. cmp/test x, %reg / test %reg,%reg
  6202. (reg deallocated)
  6203. to
  6204. cmp/test x, mem / cmp 0, mem
  6205. }
  6206. TransferUsedRegs(TmpUsedRegs);
  6207. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6208. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6209. begin
  6210. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6211. if (taicpu(hp1).opcode = A_TEST) and
  6212. (
  6213. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6214. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6215. ) then
  6216. begin
  6217. taicpu(hp1).opcode := A_CMP;
  6218. taicpu(hp1).loadconst(0, 0);
  6219. end;
  6220. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6221. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6222. RemoveCurrentP(p);
  6223. if (p <> hp1) then
  6224. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6225. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6226. { Make sure the flags are allocated across the CMP instruction }
  6227. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6228. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6229. Result := True;
  6230. Exit;
  6231. end;
  6232. end;
  6233. end;
  6234. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6235. var
  6236. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6237. ThisReg, SecondReg: TRegister;
  6238. JumpLoc: TAsmLabel;
  6239. NewSize: TOpSize;
  6240. begin
  6241. Result := False;
  6242. {
  6243. Convert:
  6244. j<c> .L1
  6245. .L2:
  6246. mov 1,reg
  6247. jmp .L3 (or ret, although it might not be a RET yet)
  6248. .L1:
  6249. mov 0,reg
  6250. jmp .L3 (or ret)
  6251. ( As long as .L3 <> .L1 or .L2)
  6252. To:
  6253. mov 0,reg
  6254. set<not(c)> reg
  6255. jmp .L3 (or ret)
  6256. .L2:
  6257. mov 1,reg
  6258. jmp .L3 (or ret)
  6259. .L1:
  6260. mov 0,reg
  6261. jmp .L3 (or ret)
  6262. }
  6263. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6264. Exit;
  6265. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6266. if GetNextInstruction(hp_label, hp2) and
  6267. MatchInstruction(hp2,A_MOV,[]) and
  6268. (taicpu(hp2).oper[0]^.typ = top_const) and
  6269. (
  6270. (
  6271. (taicpu(hp2).oper[1]^.typ = top_reg)
  6272. {$ifdef i386}
  6273. { Under i386, ESI, EDI, EBP and ESP
  6274. don't have an 8-bit representation }
  6275. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6276. {$endif i386}
  6277. ) or (
  6278. {$ifdef i386}
  6279. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6280. {$endif i386}
  6281. (taicpu(hp2).opsize = S_B)
  6282. )
  6283. ) and
  6284. GetNextInstruction(hp2, hp3) and
  6285. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6286. (
  6287. (taicpu(hp3).opcode=A_RET) or
  6288. (
  6289. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6290. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6291. )
  6292. ) and
  6293. GetNextInstruction(hp3, hp4) and
  6294. FindLabel(JumpLoc, hp4) and
  6295. (
  6296. not (cs_opt_size in current_settings.optimizerswitches) or
  6297. { If the initial jump is the label's only reference, then it will
  6298. become a dead label if the other conditions are met and hence
  6299. remove at least 2 instructions, including a jump }
  6300. (JumpLoc.getrefs = 1)
  6301. ) and
  6302. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6303. that will be optimised out }
  6304. GetNextInstruction(hp4, hp5) and
  6305. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6306. (taicpu(hp5).oper[0]^.typ = top_const) and
  6307. (
  6308. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6309. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6310. ) and
  6311. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6312. GetNextInstruction(hp5,hp6) and
  6313. (
  6314. not (hp6.typ in [ait_align, ait_label]) or
  6315. SkipLabels(hp6, hp6)
  6316. ) and
  6317. (hp6.typ=ait_instruction) then
  6318. begin
  6319. { First, let's look at the two jumps that are hp3 and hp6 }
  6320. if not
  6321. (
  6322. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6323. (
  6324. (taicpu(hp6).opcode=A_RET) or
  6325. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6326. )
  6327. ) then
  6328. { If condition is False, then the JMP/RET instructions matched conventionally }
  6329. begin
  6330. { See if one of the jumps can be instantly converted into a RET }
  6331. if (taicpu(hp3).opcode=A_JMP) then
  6332. begin
  6333. { Reuse hp5 }
  6334. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6335. { Make sure hp5 doesn't jump back to .L1 (zero distance jump) or .L2 (infinite loop) }
  6336. if not Assigned(hp5) or (hp5 = hp_label) or (hp5 = hp4) or not GetNextInstruction(hp5, hp5) then
  6337. Exit;
  6338. if MatchInstruction(hp5, A_RET, []) then
  6339. begin
  6340. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6341. ConvertJumpToRET(hp3, hp5);
  6342. Result := True;
  6343. end
  6344. else
  6345. Exit;
  6346. end;
  6347. if (taicpu(hp6).opcode=A_JMP) then
  6348. begin
  6349. { Reuse hp5 }
  6350. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6351. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6352. Exit;
  6353. if MatchInstruction(hp5, A_RET, []) then
  6354. begin
  6355. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6356. ConvertJumpToRET(hp6, hp5);
  6357. Result := True;
  6358. end
  6359. else
  6360. Exit;
  6361. end;
  6362. if not
  6363. (
  6364. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6365. (
  6366. (taicpu(hp6).opcode=A_RET) or
  6367. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6368. )
  6369. ) then
  6370. { Still doesn't match }
  6371. Exit;
  6372. end;
  6373. if (taicpu(hp2).oper[0]^.val = 1) then
  6374. begin
  6375. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6376. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6377. end
  6378. else
  6379. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6380. if taicpu(hp2).opsize=S_B then
  6381. begin
  6382. if taicpu(hp2).oper[1]^.typ = top_reg then
  6383. begin
  6384. SecondReg := taicpu(hp2).oper[1]^.reg;
  6385. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6386. end
  6387. else
  6388. begin
  6389. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6390. SecondReg := NR_NO;
  6391. end;
  6392. hp_pos := p;
  6393. hp_allocstart := hp4;
  6394. end
  6395. else
  6396. begin
  6397. { Will be a register because the size can't be S_B otherwise }
  6398. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6399. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6400. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6401. if (cs_opt_size in current_settings.optimizerswitches) then
  6402. begin
  6403. { Favour using MOVZX when optimising for size }
  6404. case taicpu(hp2).opsize of
  6405. S_W:
  6406. NewSize := S_BW;
  6407. S_L:
  6408. NewSize := S_BL;
  6409. {$ifdef x86_64}
  6410. S_Q:
  6411. begin
  6412. NewSize := S_BL;
  6413. { Will implicitly zero-extend to 64-bit }
  6414. setsubreg(SecondReg, R_SUBD);
  6415. end;
  6416. {$endif x86_64}
  6417. else
  6418. InternalError(2022101301);
  6419. end;
  6420. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6421. { Inserting it right before p will guarantee that the flags are also tracked }
  6422. Asml.InsertBefore(hp5, p);
  6423. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6424. hp_pos := hp5;
  6425. hp_allocstart := hp4;
  6426. end
  6427. else
  6428. begin
  6429. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6430. { Inserting it right before p will guarantee that the flags are also tracked }
  6431. Asml.InsertBefore(hp5, p);
  6432. hp_pos := p;
  6433. hp_allocstart := hp5;
  6434. end;
  6435. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6436. end;
  6437. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6438. taicpu(hp4).condition := taicpu(p).condition;
  6439. asml.InsertBefore(hp4, hp_pos);
  6440. if taicpu(hp3).is_jmp then
  6441. begin
  6442. JumpLoc.decrefs;
  6443. MakeUnconditional(taicpu(p));
  6444. { This also increases the reference count }
  6445. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6446. end
  6447. else
  6448. ConvertJumpToRET(p, hp3);
  6449. if SecondReg <> NR_NO then
  6450. { Ensure the destination register is allocated over this region }
  6451. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6452. if (JumpLoc.getrefs = 0) then
  6453. RemoveDeadCodeAfterJump(hp3);
  6454. Result:=true;
  6455. exit;
  6456. end;
  6457. end;
  6458. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6459. var
  6460. hp1, hp2: tai;
  6461. ActiveReg: TRegister;
  6462. OldOffset: asizeint;
  6463. ThisConst: TCGInt;
  6464. function RegDeallocated: Boolean;
  6465. begin
  6466. TransferUsedRegs(TmpUsedRegs);
  6467. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6468. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6469. end;
  6470. begin
  6471. Result:=false;
  6472. hp1 := nil;
  6473. { replace
  6474. subX const,%reg1
  6475. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6476. dealloc %reg1
  6477. by
  6478. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6479. }
  6480. if MatchOpType(taicpu(p),top_const,top_reg) then
  6481. begin
  6482. ActiveReg := taicpu(p).oper[1]^.reg;
  6483. { Ensures the entire register was updated }
  6484. if (taicpu(p).opsize >= S_L) and
  6485. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6486. MatchInstruction(hp1,A_LEA,[]) and
  6487. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6488. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6489. (
  6490. { Cover the case where the register in the reference is also the destination register }
  6491. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6492. (
  6493. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6494. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6495. RegDeallocated
  6496. )
  6497. ) then
  6498. begin
  6499. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6500. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6501. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6502. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6503. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6504. {$ifdef x86_64}
  6505. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6506. begin
  6507. { Overflow; abort }
  6508. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6509. end
  6510. else
  6511. {$endif x86_64}
  6512. begin
  6513. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6514. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6515. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6516. RemoveCurrentP(p, hp1)
  6517. else
  6518. RemoveCurrentP(p);
  6519. result:=true;
  6520. Exit;
  6521. end;
  6522. end;
  6523. if (
  6524. { Save calling GetNextInstructionUsingReg again }
  6525. Assigned(hp1) or
  6526. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6527. ) and
  6528. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6529. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6530. begin
  6531. if taicpu(hp1).oper[0]^.typ = top_const then
  6532. begin
  6533. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6534. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6535. Result := True;
  6536. { Handle any overflows }
  6537. case taicpu(p).opsize of
  6538. S_B:
  6539. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6540. S_W:
  6541. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6542. S_L:
  6543. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6544. {$ifdef x86_64}
  6545. S_Q:
  6546. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6547. { Overflow; abort }
  6548. Result := False
  6549. else
  6550. taicpu(p).oper[0]^.val := ThisConst;
  6551. {$endif x86_64}
  6552. else
  6553. InternalError(2021102611);
  6554. end;
  6555. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6556. if Result then
  6557. begin
  6558. if (taicpu(p).oper[0]^.val < 0) and
  6559. (
  6560. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6561. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6562. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6563. ) then
  6564. begin
  6565. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6566. taicpu(p).opcode := A_SUB;
  6567. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6568. end
  6569. else
  6570. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6571. RemoveInstruction(hp1);
  6572. end;
  6573. end
  6574. else
  6575. begin
  6576. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6577. TransferUsedRegs(TmpUsedRegs);
  6578. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6579. hp2 := p;
  6580. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6581. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6582. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6583. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6584. begin
  6585. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6586. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6587. Asml.Remove(p);
  6588. Asml.InsertAfter(p, hp1);
  6589. p := hp1;
  6590. Result := True;
  6591. Exit;
  6592. end;
  6593. end;
  6594. end;
  6595. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6596. { * change "sub/add const1, reg" or "dec reg" followed by
  6597. "sub const2, reg" to one "sub ..., reg" }
  6598. {$ifdef i386}
  6599. if (taicpu(p).oper[0]^.val = 2) and
  6600. (ActiveReg = NR_ESP) and
  6601. { Don't do the sub/push optimization if the sub }
  6602. { comes from setting up the stack frame (JM) }
  6603. (not(GetLastInstruction(p,hp1)) or
  6604. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6605. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6606. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6607. begin
  6608. hp1 := tai(p.next);
  6609. while Assigned(hp1) and
  6610. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6611. not RegReadByInstruction(NR_ESP,hp1) and
  6612. not RegModifiedByInstruction(NR_ESP,hp1) do
  6613. hp1 := tai(hp1.next);
  6614. if Assigned(hp1) and
  6615. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6616. begin
  6617. taicpu(hp1).changeopsize(S_L);
  6618. if taicpu(hp1).oper[0]^.typ=top_reg then
  6619. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6620. hp1 := tai(p.next);
  6621. RemoveCurrentp(p, hp1);
  6622. Result:=true;
  6623. exit;
  6624. end;
  6625. end;
  6626. {$endif i386}
  6627. if DoArithCombineOpt(p) then
  6628. Result:=true;
  6629. end;
  6630. end;
  6631. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6632. var
  6633. TmpBool1,TmpBool2 : Boolean;
  6634. tmpref : treference;
  6635. hp1,hp2: tai;
  6636. mask, shiftval: tcgint;
  6637. begin
  6638. Result:=false;
  6639. { All these optimisations work on "shl/sal const,%reg" }
  6640. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6641. Exit;
  6642. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6643. (taicpu(p).oper[0]^.val <= 3) then
  6644. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6645. begin
  6646. { should we check the next instruction? }
  6647. TmpBool1 := True;
  6648. { have we found an add/sub which could be
  6649. integrated in the lea? }
  6650. TmpBool2 := False;
  6651. reference_reset(tmpref,2,[]);
  6652. TmpRef.index := taicpu(p).oper[1]^.reg;
  6653. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6654. while TmpBool1 and
  6655. GetNextInstruction(p, hp1) and
  6656. (tai(hp1).typ = ait_instruction) and
  6657. ((((taicpu(hp1).opcode = A_ADD) or
  6658. (taicpu(hp1).opcode = A_SUB)) and
  6659. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6660. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6661. (((taicpu(hp1).opcode = A_INC) or
  6662. (taicpu(hp1).opcode = A_DEC)) and
  6663. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6664. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6665. ((taicpu(hp1).opcode = A_LEA) and
  6666. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6667. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6668. (not GetNextInstruction(hp1,hp2) or
  6669. not instrReadsFlags(hp2)) Do
  6670. begin
  6671. TmpBool1 := False;
  6672. if taicpu(hp1).opcode=A_LEA then
  6673. begin
  6674. if (TmpRef.base = NR_NO) and
  6675. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6676. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6677. { Segment register isn't a concern here }
  6678. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6679. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6680. begin
  6681. TmpBool1 := True;
  6682. TmpBool2 := True;
  6683. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6684. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6685. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6686. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6687. RemoveInstruction(hp1);
  6688. end
  6689. end
  6690. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6691. begin
  6692. TmpBool1 := True;
  6693. TmpBool2 := True;
  6694. case taicpu(hp1).opcode of
  6695. A_ADD:
  6696. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6697. A_SUB:
  6698. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6699. else
  6700. internalerror(2019050536);
  6701. end;
  6702. RemoveInstruction(hp1);
  6703. end
  6704. else
  6705. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6706. (((taicpu(hp1).opcode = A_ADD) and
  6707. (TmpRef.base = NR_NO)) or
  6708. (taicpu(hp1).opcode = A_INC) or
  6709. (taicpu(hp1).opcode = A_DEC)) then
  6710. begin
  6711. TmpBool1 := True;
  6712. TmpBool2 := True;
  6713. case taicpu(hp1).opcode of
  6714. A_ADD:
  6715. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6716. A_INC:
  6717. inc(TmpRef.offset);
  6718. A_DEC:
  6719. dec(TmpRef.offset);
  6720. else
  6721. internalerror(2019050535);
  6722. end;
  6723. RemoveInstruction(hp1);
  6724. end;
  6725. end;
  6726. if TmpBool2
  6727. {$ifndef x86_64}
  6728. or
  6729. ((current_settings.optimizecputype < cpu_Pentium2) and
  6730. (taicpu(p).oper[0]^.val <= 3) and
  6731. not(cs_opt_size in current_settings.optimizerswitches))
  6732. {$endif x86_64}
  6733. then
  6734. begin
  6735. if not(TmpBool2) and
  6736. (taicpu(p).oper[0]^.val=1) then
  6737. begin
  6738. taicpu(p).opcode := A_ADD;
  6739. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6740. end
  6741. else
  6742. begin
  6743. taicpu(p).opcode := A_LEA;
  6744. taicpu(p).loadref(0, TmpRef);
  6745. end;
  6746. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6747. Result := True;
  6748. end;
  6749. end
  6750. {$ifndef x86_64}
  6751. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6752. begin
  6753. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6754. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6755. (unlike shl, which is only Tairable in the U pipe) }
  6756. if taicpu(p).oper[0]^.val=1 then
  6757. begin
  6758. taicpu(p).opcode := A_ADD;
  6759. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6760. Result := True;
  6761. end
  6762. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6763. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6764. else if (taicpu(p).opsize = S_L) and
  6765. (taicpu(p).oper[0]^.val<= 3) then
  6766. begin
  6767. reference_reset(tmpref,2,[]);
  6768. TmpRef.index := taicpu(p).oper[1]^.reg;
  6769. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6770. taicpu(p).opcode := A_LEA;
  6771. taicpu(p).loadref(0, TmpRef);
  6772. Result := True;
  6773. end;
  6774. end
  6775. {$endif x86_64}
  6776. else if
  6777. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6778. (
  6779. (
  6780. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6781. SetAndTest(hp1, hp2)
  6782. {$ifdef x86_64}
  6783. ) or
  6784. (
  6785. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6786. GetNextInstruction(hp1, hp2) and
  6787. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6788. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6789. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6790. {$endif x86_64}
  6791. )
  6792. ) and
  6793. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6794. begin
  6795. { Change:
  6796. shl x, %reg1
  6797. mov -(1<<x), %reg2
  6798. and %reg2, %reg1
  6799. Or:
  6800. shl x, %reg1
  6801. and -(1<<x), %reg1
  6802. To just:
  6803. shl x, %reg1
  6804. Since the and operation only zeroes bits that are already zero from the shl operation
  6805. }
  6806. case taicpu(p).oper[0]^.val of
  6807. 8:
  6808. mask:=$FFFFFFFFFFFFFF00;
  6809. 16:
  6810. mask:=$FFFFFFFFFFFF0000;
  6811. 32:
  6812. mask:=$FFFFFFFF00000000;
  6813. 63:
  6814. { Constant pre-calculated to prevent overflow errors with Int64 }
  6815. mask:=$8000000000000000;
  6816. else
  6817. begin
  6818. if taicpu(p).oper[0]^.val >= 64 then
  6819. { Shouldn't happen realistically, since the register
  6820. is guaranteed to be set to zero at this point }
  6821. mask := 0
  6822. else
  6823. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6824. end;
  6825. end;
  6826. if taicpu(hp1).oper[0]^.val = mask then
  6827. begin
  6828. { Everything checks out, perform the optimisation, as long as
  6829. the FLAGS register isn't being used}
  6830. TransferUsedRegs(TmpUsedRegs);
  6831. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6832. {$ifdef x86_64}
  6833. if (hp1 <> hp2) then
  6834. begin
  6835. { "shl/mov/and" version }
  6836. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6837. { Don't do the optimisation if the FLAGS register is in use }
  6838. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6839. begin
  6840. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6841. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6842. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6843. begin
  6844. RemoveInstruction(hp1);
  6845. Result := True;
  6846. end;
  6847. { Only set Result to True if the 'mov' instruction was removed }
  6848. RemoveInstruction(hp2);
  6849. end;
  6850. end
  6851. else
  6852. {$endif x86_64}
  6853. begin
  6854. { "shl/and" version }
  6855. { Don't do the optimisation if the FLAGS register is in use }
  6856. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6857. begin
  6858. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6859. RemoveInstruction(hp1);
  6860. Result := True;
  6861. end;
  6862. end;
  6863. Exit;
  6864. end
  6865. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6866. begin
  6867. { Even if the mask doesn't allow for its removal, we might be
  6868. able to optimise the mask for the "shl/and" version, which
  6869. may permit other peephole optimisations }
  6870. {$ifdef DEBUG_AOPTCPU}
  6871. mask := taicpu(hp1).oper[0]^.val and mask;
  6872. if taicpu(hp1).oper[0]^.val <> mask then
  6873. begin
  6874. DebugMsg(
  6875. SPeepholeOptimization +
  6876. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6877. ' to $' + debug_tostr(mask) +
  6878. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6879. taicpu(hp1).oper[0]^.val := mask;
  6880. end;
  6881. {$else DEBUG_AOPTCPU}
  6882. { If debugging is off, just set the operand even if it's the same }
  6883. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6884. {$endif DEBUG_AOPTCPU}
  6885. end;
  6886. end;
  6887. {
  6888. change
  6889. shl/sal const,reg
  6890. <op> ...(...,reg,1),...
  6891. into
  6892. <op> ...(...,reg,1 shl const),...
  6893. if const in 1..3
  6894. }
  6895. if MatchOpType(taicpu(p), top_const, top_reg) and
  6896. (taicpu(p).oper[0]^.val in [1..3]) and
  6897. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6898. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6899. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6900. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6901. MatchOpType(taicpu(hp1),top_ref))
  6902. ) and
  6903. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6904. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6905. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6906. begin
  6907. TransferUsedRegs(TmpUsedRegs);
  6908. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6909. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6910. begin
  6911. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6912. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6913. RemoveCurrentP(p);
  6914. Result:=true;
  6915. exit;
  6916. end;
  6917. end;
  6918. if MatchOpType(taicpu(p), top_const, top_reg) and
  6919. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6920. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6921. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6922. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6923. begin
  6924. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6925. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6926. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6927. {$ifdef x86_64}
  6928. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6929. {$endif x86_64}
  6930. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6931. begin
  6932. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6933. taicpu(hp1).opcode:=A_MOV;
  6934. taicpu(hp1).oper[0]^.val:=0;
  6935. end
  6936. else
  6937. begin
  6938. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6939. taicpu(hp1).oper[0]^.val:=shiftval;
  6940. end;
  6941. RemoveCurrentP(p);
  6942. Result:=true;
  6943. exit;
  6944. end;
  6945. end;
  6946. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6947. begin
  6948. case shr_size of
  6949. S_B:
  6950. { No valid combinations }
  6951. Result := False;
  6952. S_W:
  6953. Result := (Shift >= 8) and (movz_size = S_BW);
  6954. S_L:
  6955. Result :=
  6956. (Shift >= 24) { Any opsize is valid for this shift } or
  6957. ((Shift >= 16) and (movz_size = S_WL));
  6958. {$ifdef x86_64}
  6959. S_Q:
  6960. Result :=
  6961. (Shift >= 56) { Any opsize is valid for this shift } or
  6962. ((Shift >= 48) and (movz_size = S_WL));
  6963. {$endif x86_64}
  6964. else
  6965. InternalError(2022081510);
  6966. end;
  6967. end;
  6968. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6969. var
  6970. hp1, hp2: tai;
  6971. Shift: TCGInt;
  6972. LimitSize: Topsize;
  6973. DoNotMerge: Boolean;
  6974. begin
  6975. Result := False;
  6976. { All these optimisations work on "shr const,%reg" }
  6977. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6978. Exit;
  6979. DoNotMerge := False;
  6980. Shift := taicpu(p).oper[0]^.val;
  6981. LimitSize := taicpu(p).opsize;
  6982. hp1 := p;
  6983. repeat
  6984. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6985. Exit;
  6986. case taicpu(hp1).opcode of
  6987. A_TEST, A_CMP, A_Jcc:
  6988. { Skip over conditional jumps and relevant comparisons }
  6989. Continue;
  6990. A_MOVZX:
  6991. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6992. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6993. begin
  6994. { Since the original register is being read as is, subsequent
  6995. SHRs must not be merged at this point }
  6996. DoNotMerge := True;
  6997. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6998. begin
  6999. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  7000. begin
  7001. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  7002. taicpu(hp1).opcode := A_MOV;
  7003. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  7004. case taicpu(hp1).opsize of
  7005. S_BW:
  7006. taicpu(hp1).opsize := S_W;
  7007. S_BL, S_WL:
  7008. taicpu(hp1).opsize := S_L;
  7009. else
  7010. InternalError(2022081503);
  7011. end;
  7012. { p itself hasn't changed, so no need to set Result to True }
  7013. Include(OptsToCheck, aoc_ForceNewIteration);
  7014. { See if there's anything afterwards that can be
  7015. optimised, since the input register hasn't changed }
  7016. Continue;
  7017. end;
  7018. { NOTE: If the MOVZX instruction reads and writes the same
  7019. register, defer this to the post-peephole optimisation stage }
  7020. Exit;
  7021. end;
  7022. end;
  7023. A_SHL, A_SAL, A_SHR:
  7024. if (taicpu(hp1).opsize <= LimitSize) and
  7025. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7026. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7027. begin
  7028. { Make sure the sizes don't exceed the register size limit
  7029. (measured by the shift value falling below the limit) }
  7030. if taicpu(hp1).opsize < LimitSize then
  7031. LimitSize := taicpu(hp1).opsize;
  7032. if taicpu(hp1).opcode = A_SHR then
  7033. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7034. else
  7035. begin
  7036. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7037. DoNotMerge := True;
  7038. end;
  7039. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7040. Exit;
  7041. { Since we've established that the combined shift is within
  7042. limits, we can actually combine the adjacent SHR
  7043. instructions even if they're different sizes }
  7044. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7045. begin
  7046. hp2 := tai(hp1.Previous);
  7047. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7048. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7049. RemoveInstruction(hp1);
  7050. hp1 := hp2;
  7051. { Though p has changed, only the constant has, and its
  7052. effects can still be detected on the next iteration of
  7053. the repeat..until loop }
  7054. Include(OptsToCheck, aoc_ForceNewIteration);
  7055. end;
  7056. { Move onto the next instruction }
  7057. Continue;
  7058. end;
  7059. else
  7060. ;
  7061. end;
  7062. Break;
  7063. until False;
  7064. end;
  7065. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7066. var
  7067. CurrentRef: TReference;
  7068. FullReg: TRegister;
  7069. hp1, hp2: tai;
  7070. begin
  7071. Result := False;
  7072. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7073. Exit;
  7074. { We assume you've checked if the operand is actually a reference by
  7075. this point. If it isn't, you'll most likely get an access violation }
  7076. CurrentRef := first_mov.oper[1]^.ref^;
  7077. { Memory must be aligned }
  7078. if (CurrentRef.offset mod 4) <> 0 then
  7079. Exit;
  7080. Inc(CurrentRef.offset);
  7081. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7082. if MatchOperand(second_mov.oper[0]^, 0) and
  7083. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7084. GetNextInstruction(second_mov, hp1) and
  7085. (hp1.typ = ait_instruction) and
  7086. (taicpu(hp1).opcode = A_MOV) and
  7087. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7088. (taicpu(hp1).oper[0]^.val = 0) then
  7089. begin
  7090. Inc(CurrentRef.offset);
  7091. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7092. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7093. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7094. begin
  7095. case taicpu(hp1).opsize of
  7096. S_B:
  7097. if GetNextInstruction(hp1, hp2) and
  7098. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7099. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7100. (taicpu(hp2).oper[0]^.val = 0) then
  7101. begin
  7102. Inc(CurrentRef.offset);
  7103. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7104. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7105. (taicpu(hp2).opsize = S_B) then
  7106. begin
  7107. RemoveInstruction(hp1);
  7108. RemoveInstruction(hp2);
  7109. first_mov.opsize := S_L;
  7110. if first_mov.oper[0]^.typ = top_reg then
  7111. begin
  7112. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7113. { Reuse second_mov as a MOVZX instruction }
  7114. second_mov.opcode := A_MOVZX;
  7115. second_mov.opsize := S_BL;
  7116. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7117. second_mov.loadreg(1, FullReg);
  7118. first_mov.oper[0]^.reg := FullReg;
  7119. asml.Remove(second_mov);
  7120. asml.InsertBefore(second_mov, first_mov);
  7121. end
  7122. else
  7123. { It's a value }
  7124. begin
  7125. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7126. RemoveInstruction(second_mov);
  7127. end;
  7128. Result := True;
  7129. Exit;
  7130. end;
  7131. end;
  7132. S_W:
  7133. begin
  7134. RemoveInstruction(hp1);
  7135. first_mov.opsize := S_L;
  7136. if first_mov.oper[0]^.typ = top_reg then
  7137. begin
  7138. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7139. { Reuse second_mov as a MOVZX instruction }
  7140. second_mov.opcode := A_MOVZX;
  7141. second_mov.opsize := S_BL;
  7142. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7143. second_mov.loadreg(1, FullReg);
  7144. first_mov.oper[0]^.reg := FullReg;
  7145. asml.Remove(second_mov);
  7146. asml.InsertBefore(second_mov, first_mov);
  7147. end
  7148. else
  7149. { It's a value }
  7150. begin
  7151. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7152. RemoveInstruction(second_mov);
  7153. end;
  7154. Result := True;
  7155. Exit;
  7156. end;
  7157. else
  7158. ;
  7159. end;
  7160. end;
  7161. end;
  7162. end;
  7163. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7164. { returns true if a "continue" should be done after this optimization }
  7165. var
  7166. hp1, hp2, hp3: tai;
  7167. begin
  7168. Result := false;
  7169. hp3 := nil;
  7170. if MatchOpType(taicpu(p),top_ref) and
  7171. GetNextInstruction(p, hp1) and
  7172. (hp1.typ = ait_instruction) and
  7173. (((taicpu(hp1).opcode = A_FLD) and
  7174. (taicpu(p).opcode = A_FSTP)) or
  7175. ((taicpu(p).opcode = A_FISTP) and
  7176. (taicpu(hp1).opcode = A_FILD))) and
  7177. MatchOpType(taicpu(hp1),top_ref) and
  7178. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7179. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7180. begin
  7181. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7182. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7183. GetNextInstruction(hp1, hp2) and
  7184. (((hp2.typ = ait_instruction) and
  7185. IsExitCode(hp2) and
  7186. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7187. not(assigned(current_procinfo.procdef.funcretsym) and
  7188. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7189. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7190. { fstp <temp>
  7191. fld <temp>
  7192. <dealloc> <temp>
  7193. }
  7194. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7195. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7196. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7197. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7198. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7199. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7200. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7201. )
  7202. )
  7203. ) then
  7204. begin
  7205. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7206. RemoveInstruction(hp1);
  7207. RemoveCurrentP(p, hp2);
  7208. { first case: exit code }
  7209. if hp2.typ = ait_instruction then
  7210. RemoveLastDeallocForFuncRes(p);
  7211. Result := true;
  7212. end
  7213. else
  7214. { we can do this only in fast math mode as fstp is rounding ...
  7215. ... still disabled as it breaks the compiler and/or rtl }
  7216. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7217. { ... or if another fstp equal to the first one follows }
  7218. GetNextInstruction(hp1,hp2) and
  7219. (hp2.typ = ait_instruction) and
  7220. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7221. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7222. begin
  7223. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7224. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7225. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7226. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7227. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7228. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7229. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7230. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7231. ) then
  7232. begin
  7233. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7234. RemoveCurrentP(p,hp2);
  7235. RemoveInstruction(hp1);
  7236. Result := true;
  7237. end
  7238. else if { fst can't store an extended/comp value }
  7239. (taicpu(p).opsize <> S_FX) and
  7240. (taicpu(p).opsize <> S_IQ) then
  7241. begin
  7242. if (taicpu(p).opcode = A_FSTP) then
  7243. taicpu(p).opcode := A_FST
  7244. else
  7245. taicpu(p).opcode := A_FIST;
  7246. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7247. RemoveInstruction(hp1);
  7248. Result := true;
  7249. end;
  7250. end;
  7251. end;
  7252. end;
  7253. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7254. var
  7255. hp1, hp2, hp3: tai;
  7256. begin
  7257. result:=false;
  7258. if MatchOpType(taicpu(p),top_reg) and
  7259. GetNextInstruction(p, hp1) and
  7260. (hp1.typ = Ait_Instruction) and
  7261. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7262. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7263. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7264. { change to
  7265. fld reg fxxx reg,st
  7266. fxxxp st, st1 (hp1)
  7267. Remark: non commutative operations must be reversed!
  7268. }
  7269. begin
  7270. case taicpu(hp1).opcode Of
  7271. A_FMULP,A_FADDP,
  7272. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7273. begin
  7274. case taicpu(hp1).opcode Of
  7275. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7276. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7277. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7278. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7279. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7280. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7281. else
  7282. internalerror(2019050534);
  7283. end;
  7284. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7285. taicpu(hp1).oper[1]^.reg := NR_ST;
  7286. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7287. RemoveCurrentP(p, hp1);
  7288. Result:=true;
  7289. exit;
  7290. end;
  7291. else
  7292. ;
  7293. end;
  7294. end
  7295. else
  7296. if MatchOpType(taicpu(p),top_ref) and
  7297. GetNextInstruction(p, hp2) and
  7298. (hp2.typ = Ait_Instruction) and
  7299. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7300. (taicpu(p).opsize in [S_FS, S_FL]) and
  7301. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7302. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7303. if GetLastInstruction(p, hp1) and
  7304. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7305. MatchOpType(taicpu(hp1),top_ref) and
  7306. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7307. if ((taicpu(hp2).opcode = A_FMULP) or
  7308. (taicpu(hp2).opcode = A_FADDP)) then
  7309. { change to
  7310. fld/fst mem1 (hp1) fld/fst mem1
  7311. fld mem1 (p) fadd/
  7312. faddp/ fmul st, st
  7313. fmulp st, st1 (hp2) }
  7314. begin
  7315. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7316. RemoveCurrentP(p, hp1);
  7317. if (taicpu(hp2).opcode = A_FADDP) then
  7318. taicpu(hp2).opcode := A_FADD
  7319. else
  7320. taicpu(hp2).opcode := A_FMUL;
  7321. taicpu(hp2).oper[1]^.reg := NR_ST;
  7322. end
  7323. else
  7324. { change to
  7325. fld/fst mem1 (hp1) fld/fst mem1
  7326. fld mem1 (p) fld st
  7327. }
  7328. begin
  7329. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7330. taicpu(p).changeopsize(S_FL);
  7331. taicpu(p).loadreg(0,NR_ST);
  7332. end
  7333. else
  7334. begin
  7335. case taicpu(hp2).opcode Of
  7336. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7337. { change to
  7338. fld/fst mem1 (hp1) fld/fst mem1
  7339. fld mem2 (p) fxxx mem2
  7340. fxxxp st, st1 (hp2) }
  7341. begin
  7342. case taicpu(hp2).opcode Of
  7343. A_FADDP: taicpu(p).opcode := A_FADD;
  7344. A_FMULP: taicpu(p).opcode := A_FMUL;
  7345. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7346. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7347. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7348. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7349. else
  7350. internalerror(2019050533);
  7351. end;
  7352. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7353. RemoveInstruction(hp2);
  7354. end
  7355. else
  7356. ;
  7357. end
  7358. end
  7359. end;
  7360. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7361. begin
  7362. Result := condition_in(cond1, cond2) or
  7363. { Not strictly subsets due to the actual flags checked, but because we're
  7364. comparing integers, E is a subset of AE and GE and their aliases }
  7365. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7366. end;
  7367. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7368. var
  7369. v: TCGInt;
  7370. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7371. FirstMatch, TempBool: Boolean;
  7372. NewReg: TRegister;
  7373. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7374. begin
  7375. Result:=false;
  7376. { All these optimisations need a next instruction }
  7377. if not GetNextInstruction(p, hp1) then
  7378. Exit;
  7379. true_hp1 := hp1;
  7380. { Search for:
  7381. cmp ###,###
  7382. j(c1) @lbl1
  7383. ...
  7384. @lbl:
  7385. cmp ###,### (same comparison as above)
  7386. j(c2) @lbl2
  7387. If c1 is a subset of c2, change to:
  7388. cmp ###,###
  7389. j(c1) @lbl2
  7390. (@lbl1 may become a dead label as a result)
  7391. }
  7392. { Also handle cases where there are multiple jumps in a row }
  7393. p_jump := hp1;
  7394. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7395. begin
  7396. Prefetch(p_jump.Next);
  7397. if IsJumpToLabel(taicpu(p_jump)) then
  7398. begin
  7399. { Do jump optimisations first in case the condition becomes
  7400. unnecessary }
  7401. TempBool := True;
  7402. if DoJumpOptimizations(p_jump, TempBool) or
  7403. not TempBool then
  7404. begin
  7405. if Assigned(p_jump) then
  7406. begin
  7407. { CollapseZeroDistJump will be set to the label or an align
  7408. before it after the jump if it optimises, whether or not
  7409. the label is live or dead }
  7410. if (p_jump.typ = ait_align) or
  7411. (
  7412. (p_jump.typ = ait_label) and
  7413. not (tai_label(p_jump).labsym.is_used)
  7414. ) then
  7415. GetNextInstruction(p_jump, p_jump);
  7416. end;
  7417. TransferUsedRegs(TmpUsedRegs);
  7418. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7419. if not Assigned(p_jump) or
  7420. (
  7421. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7422. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7423. ) then
  7424. begin
  7425. { No more conditional jumps; conditional statement is no longer required }
  7426. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7427. RemoveCurrentP(p);
  7428. Result := True;
  7429. Exit;
  7430. end;
  7431. hp1 := p_jump;
  7432. Include(OptsToCheck, aoc_ForceNewIteration);
  7433. Continue;
  7434. end;
  7435. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7436. if GetNextInstruction(p_jump, hp2) and
  7437. (
  7438. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7439. not TempBool
  7440. ) then
  7441. begin
  7442. hp1 := p_jump;
  7443. Include(OptsToCheck, aoc_ForceNewIteration);
  7444. Continue;
  7445. end;
  7446. p_label := nil;
  7447. if Assigned(JumpLabel) then
  7448. p_label := getlabelwithsym(JumpLabel);
  7449. if Assigned(p_label) and
  7450. GetNextInstruction(p_label, p_dist) and
  7451. MatchInstruction(p_dist, A_CMP, []) and
  7452. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7453. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7454. GetNextInstruction(p_dist, hp1_dist) and
  7455. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7456. begin
  7457. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7458. if JumpLabel = JumpLabel_dist then
  7459. { This is an infinite loop }
  7460. Exit;
  7461. { Best optimisation when the first condition is a subset (or equal) of the second }
  7462. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7463. begin
  7464. { Any registers used here will already be allocated }
  7465. if Assigned(JumpLabel) then
  7466. JumpLabel.DecRefs;
  7467. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7468. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7469. Include(OptsToCheck, aoc_ForceNewIteration);
  7470. { Don't exit yet. Since p and p_jump haven't actually been
  7471. removed, we can check for more on this iteration }
  7472. end
  7473. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7474. GetNextInstruction(hp1_dist, hp1_label) and
  7475. (hp1_label.typ = ait_label) then
  7476. begin
  7477. JumpLabel_far := tai_label(hp1_label).labsym;
  7478. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7479. { This is an infinite loop }
  7480. Exit;
  7481. if Assigned(JumpLabel_far) then
  7482. begin
  7483. { In this situation, if the first jump branches, the second one will never,
  7484. branch so change the destination label to after the second jump }
  7485. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7486. if Assigned(JumpLabel) then
  7487. JumpLabel.DecRefs;
  7488. JumpLabel_far.IncRefs;
  7489. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7490. Result := True;
  7491. { Don't exit yet. Since p and p_jump haven't actually been
  7492. removed, we can check for more on this iteration }
  7493. Continue;
  7494. end;
  7495. end;
  7496. end;
  7497. end;
  7498. { Search for:
  7499. cmp ###,###
  7500. j(c1) @lbl1
  7501. cmp ###,### (same as first)
  7502. Remove second cmp
  7503. }
  7504. if GetNextInstruction(p_jump, hp2) and
  7505. (
  7506. (
  7507. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7508. (
  7509. (
  7510. MatchOpType(taicpu(p), top_const, top_reg) and
  7511. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7512. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7513. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7514. ) or (
  7515. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7516. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7517. )
  7518. )
  7519. ) or (
  7520. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7521. MatchOperand(taicpu(p).oper[0]^, 0) and
  7522. (taicpu(p).oper[1]^.typ = top_reg) and
  7523. MatchInstruction(hp2, A_TEST, []) and
  7524. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7525. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7526. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7527. )
  7528. ) then
  7529. begin
  7530. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7531. TransferUsedRegs(TmpUsedRegs);
  7532. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7533. RemoveInstruction(hp2);
  7534. Result := True;
  7535. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7536. end
  7537. else
  7538. begin
  7539. { hp2 is the next instruction, so save time and just set p_jump
  7540. to it instead of calling GetNextInstruction below }
  7541. p_jump := hp2;
  7542. Continue;
  7543. end;
  7544. GetNextInstruction(p_jump, p_jump);
  7545. end;
  7546. if (
  7547. { Don't call GetNextInstruction again if we already have it }
  7548. (true_hp1 = p_jump) or
  7549. GetNextInstruction(p, hp1)
  7550. ) and
  7551. MatchInstruction(hp1, A_Jcc, []) and
  7552. IsJumpToLabel(taicpu(hp1)) and
  7553. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7554. GetNextInstruction(hp1, hp2) then
  7555. begin
  7556. {
  7557. cmp x, y (or "cmp y, x")
  7558. je @lbl
  7559. mov x, y
  7560. @lbl:
  7561. (x and y can be constants, registers or references)
  7562. Change to:
  7563. mov x, y (x and y will always be equal in the end)
  7564. @lbl: (may beceome a dead label)
  7565. Also:
  7566. cmp x, y (or "cmp y, x")
  7567. jne @lbl
  7568. mov x, y
  7569. @lbl:
  7570. (x and y can be constants, registers or references)
  7571. Change to:
  7572. Absolutely nothing! (Except @lbl if it's still live)
  7573. }
  7574. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7575. (
  7576. (
  7577. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7578. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7579. ) or (
  7580. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7581. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7582. )
  7583. ) and
  7584. GetNextInstruction(hp2, hp1_label) and
  7585. (hp1_label.typ = ait_label) and
  7586. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7587. begin
  7588. tai_label(hp1_label).labsym.DecRefs;
  7589. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7590. begin
  7591. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7592. RemoveInstruction(hp2);
  7593. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7594. end
  7595. else
  7596. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7597. RemoveInstruction(hp1);
  7598. RemoveCurrentp(p, hp2);
  7599. Result := True;
  7600. Exit;
  7601. end;
  7602. {
  7603. Try to optimise the following:
  7604. cmp $x,### ($x and $y can be registers or constants)
  7605. je @lbl1 (only reference)
  7606. cmp $y,### (### are identical)
  7607. @Lbl:
  7608. sete %reg1
  7609. Change to:
  7610. cmp $x,###
  7611. sete %reg2 (allocate new %reg2)
  7612. cmp $y,###
  7613. sete %reg1
  7614. orb %reg2,%reg1
  7615. (dealloc %reg2)
  7616. This adds an instruction (so don't perform under -Os), but it removes
  7617. a conditional branch.
  7618. }
  7619. if not (cs_opt_size in current_settings.optimizerswitches) and
  7620. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7621. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7622. { The first operand of CMP instructions can only be a register or
  7623. immediate anyway, so no need to check }
  7624. GetNextInstruction(hp2, p_label) and
  7625. (p_label.typ = ait_label) and
  7626. (tai_label(p_label).labsym.getrefs = 1) and
  7627. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7628. GetNextInstruction(p_label, p_dist) and
  7629. MatchInstruction(p_dist, A_SETcc, []) and
  7630. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7631. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7632. begin
  7633. TransferUsedRegs(TmpUsedRegs);
  7634. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7635. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7636. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7637. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7638. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7639. { Get the instruction after the SETcc instruction so we can
  7640. allocate a new register over the entire range }
  7641. GetNextInstruction(p_dist, hp1_dist) then
  7642. begin
  7643. { Register can appear in p if it's not used afterwards, so only
  7644. allocate between hp1 and hp1_dist }
  7645. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7646. if NewReg <> NR_NO then
  7647. begin
  7648. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7649. { Change the jump instruction into a SETcc instruction }
  7650. taicpu(hp1).opcode := A_SETcc;
  7651. taicpu(hp1).opsize := S_B;
  7652. taicpu(hp1).loadreg(0, NewReg);
  7653. { This is now a dead label }
  7654. tai_label(p_label).labsym.decrefs;
  7655. { Prefer adding before the next instruction so the FLAGS
  7656. register is deallicated first }
  7657. AsmL.InsertBefore(
  7658. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7659. hp1_dist
  7660. );
  7661. Result := True;
  7662. { Don't exit yet, as p wasn't changed and hp1, while
  7663. modified, is still intact and might be optimised by the
  7664. SETcc optimisation below }
  7665. end;
  7666. end;
  7667. end;
  7668. end;
  7669. if (taicpu(p).oper[0]^.typ = top_const) and
  7670. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7671. begin
  7672. if (taicpu(p).oper[0]^.val = 0) and
  7673. (taicpu(p).oper[1]^.typ = top_reg) then
  7674. begin
  7675. hp2 := p;
  7676. FirstMatch := True;
  7677. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7678. anything meaningful once it's converted to "test %reg,%reg";
  7679. additionally, some jumps will always (or never) branch, so
  7680. evaluate every jump immediately following the
  7681. comparison, optimising the conditions if possible.
  7682. Similarly with SETcc... those that are always set to 0 or 1
  7683. are changed to MOV instructions }
  7684. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7685. (
  7686. GetNextInstruction(hp2, hp1) and
  7687. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7688. ) do
  7689. begin
  7690. Prefetch(hp1.Next);
  7691. FirstMatch := False;
  7692. case taicpu(hp1).condition of
  7693. C_B, C_C, C_NAE, C_O:
  7694. { For B/NAE:
  7695. Will never branch since an unsigned integer can never be below zero
  7696. For C/O:
  7697. Result cannot overflow because 0 is being subtracted
  7698. }
  7699. begin
  7700. if taicpu(hp1).opcode = A_Jcc then
  7701. begin
  7702. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7703. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7704. RemoveInstruction(hp1);
  7705. { Since hp1 was deleted, hp2 must not be updated }
  7706. Continue;
  7707. end
  7708. else
  7709. begin
  7710. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7711. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7712. taicpu(hp1).opcode := A_MOV;
  7713. taicpu(hp1).ops := 2;
  7714. taicpu(hp1).condition := C_None;
  7715. taicpu(hp1).opsize := S_B;
  7716. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7717. taicpu(hp1).loadconst(0, 0);
  7718. end;
  7719. end;
  7720. C_BE, C_NA:
  7721. begin
  7722. { Will only branch if equal to zero }
  7723. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7724. taicpu(hp1).condition := C_E;
  7725. end;
  7726. C_A, C_NBE:
  7727. begin
  7728. { Will only branch if not equal to zero }
  7729. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7730. taicpu(hp1).condition := C_NE;
  7731. end;
  7732. C_AE, C_NB, C_NC, C_NO:
  7733. begin
  7734. { Will always branch }
  7735. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7736. if taicpu(hp1).opcode = A_Jcc then
  7737. begin
  7738. MakeUnconditional(taicpu(hp1));
  7739. { Any jumps/set that follow will now be dead code }
  7740. RemoveDeadCodeAfterJump(taicpu(hp1));
  7741. Break;
  7742. end
  7743. else
  7744. begin
  7745. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7746. taicpu(hp1).opcode := A_MOV;
  7747. taicpu(hp1).ops := 2;
  7748. taicpu(hp1).condition := C_None;
  7749. taicpu(hp1).opsize := S_B;
  7750. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7751. taicpu(hp1).loadconst(0, 1);
  7752. end;
  7753. end;
  7754. C_None:
  7755. InternalError(2020012201);
  7756. C_P, C_PE, C_NP, C_PO:
  7757. { We can't handle parity checks and they should never be generated
  7758. after a general-purpose CMP (it's used in some floating-point
  7759. comparisons that don't use CMP) }
  7760. InternalError(2020012202);
  7761. else
  7762. { Zero/Equality, Sign, their complements and all of the
  7763. signed comparisons do not need to be converted };
  7764. end;
  7765. hp2 := hp1;
  7766. end;
  7767. { Convert the instruction to a TEST }
  7768. taicpu(p).opcode := A_TEST;
  7769. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7770. Result := True;
  7771. Exit;
  7772. end
  7773. else
  7774. begin
  7775. TransferUsedRegs(TmpUsedRegs);
  7776. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7777. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7778. begin
  7779. if (taicpu(p).oper[0]^.val = 1) and
  7780. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7781. begin
  7782. { Convert; To:
  7783. cmp $1,r/m cmp $0,r/m
  7784. jl @lbl jle @lbl
  7785. (Also do inverted conditions)
  7786. }
  7787. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7788. taicpu(p).oper[0]^.val := 0;
  7789. if taicpu(hp1).condition in [C_L, C_NGE] then
  7790. taicpu(hp1).condition := C_LE
  7791. else
  7792. taicpu(hp1).condition := C_NLE;
  7793. { If the instruction is now "cmp $0,%reg", convert it to a
  7794. TEST (and effectively do the work of the "cmp $0,%reg" in
  7795. the block above)
  7796. }
  7797. if (taicpu(p).oper[1]^.typ = top_reg) then
  7798. begin
  7799. taicpu(p).opcode := A_TEST;
  7800. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7801. end;
  7802. Result := True;
  7803. Exit;
  7804. end
  7805. else if (taicpu(p).oper[1]^.typ = top_reg)
  7806. {$ifdef x86_64}
  7807. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7808. {$endif x86_64}
  7809. then
  7810. begin
  7811. { cmp register,$8000 neg register
  7812. je target --> jo target
  7813. .... only if register is deallocated before jump.}
  7814. case Taicpu(p).opsize of
  7815. S_B: v:=$80;
  7816. S_W: v:=$8000;
  7817. S_L: v:=qword($80000000);
  7818. else
  7819. internalerror(2013112905);
  7820. end;
  7821. if (taicpu(p).oper[0]^.val=v) and
  7822. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7823. begin
  7824. TransferUsedRegs(TmpUsedRegs);
  7825. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7826. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7827. begin
  7828. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7829. Taicpu(p).opcode:=A_NEG;
  7830. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7831. Taicpu(p).clearop(1);
  7832. Taicpu(p).ops:=1;
  7833. if Taicpu(hp1).condition=C_E then
  7834. Taicpu(hp1).condition:=C_O
  7835. else
  7836. Taicpu(hp1).condition:=C_NO;
  7837. Result:=true;
  7838. exit;
  7839. end;
  7840. end;
  7841. end;
  7842. end;
  7843. end;
  7844. end;
  7845. if TrySwapMovCmp(p, hp1) then
  7846. begin
  7847. Result := True;
  7848. Exit;
  7849. end;
  7850. end;
  7851. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7852. var
  7853. hp1: tai;
  7854. begin
  7855. {
  7856. remove the second (v)pxor from
  7857. pxor reg,reg
  7858. ...
  7859. pxor reg,reg
  7860. }
  7861. Result:=false;
  7862. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7863. MatchOpType(taicpu(p),top_reg,top_reg) and
  7864. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7865. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7866. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7867. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7868. begin
  7869. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7870. RemoveInstruction(hp1);
  7871. Result:=true;
  7872. Exit;
  7873. end
  7874. {
  7875. replace
  7876. pxor reg1,reg1
  7877. movapd/s reg1,reg2
  7878. dealloc reg1
  7879. by
  7880. pxor reg2,reg2
  7881. }
  7882. else if GetNextInstruction(p,hp1) and
  7883. { we mix single and double opperations here because we assume that the compiler
  7884. generates vmovapd only after double operations and vmovaps only after single operations }
  7885. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7886. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7887. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7888. (taicpu(p).oper[0]^.typ=top_reg) then
  7889. begin
  7890. TransferUsedRegs(TmpUsedRegs);
  7891. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7892. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7893. begin
  7894. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7895. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7896. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7897. RemoveInstruction(hp1);
  7898. result:=true;
  7899. end;
  7900. end;
  7901. end;
  7902. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7903. var
  7904. hp1: tai;
  7905. begin
  7906. {
  7907. remove the second (v)pxor from
  7908. (v)pxor reg,reg
  7909. ...
  7910. (v)pxor reg,reg
  7911. }
  7912. Result:=false;
  7913. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7914. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7915. begin
  7916. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7917. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7918. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7919. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7920. begin
  7921. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7922. RemoveInstruction(hp1);
  7923. Result:=true;
  7924. Exit;
  7925. end;
  7926. {$ifdef x86_64}
  7927. {
  7928. replace
  7929. vpxor reg1,reg1,reg1
  7930. vmov reg,mem
  7931. by
  7932. movq $0,mem
  7933. }
  7934. if GetNextInstruction(p,hp1) and
  7935. MatchInstruction(hp1,A_VMOVSD,[]) and
  7936. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7937. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7938. begin
  7939. TransferUsedRegs(TmpUsedRegs);
  7940. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7941. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7942. begin
  7943. taicpu(hp1).loadconst(0,0);
  7944. taicpu(hp1).opcode:=A_MOV;
  7945. taicpu(hp1).opsize:=S_Q;
  7946. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7947. RemoveCurrentP(p);
  7948. result:=true;
  7949. Exit;
  7950. end;
  7951. end;
  7952. {$endif x86_64}
  7953. end
  7954. {
  7955. replace
  7956. vpxor reg1,reg1,reg2
  7957. by
  7958. vpxor reg2,reg2,reg2
  7959. to avoid unncessary data dependencies
  7960. }
  7961. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7962. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7963. begin
  7964. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7965. { avoid unncessary data dependency }
  7966. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7967. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7968. result:=true;
  7969. exit;
  7970. end;
  7971. Result:=OptPass1VOP(p);
  7972. end;
  7973. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7974. var
  7975. hp1 : tai;
  7976. begin
  7977. result:=false;
  7978. { replace
  7979. IMul const,%mreg1,%mreg2
  7980. Mov %reg2,%mreg3
  7981. dealloc %mreg3
  7982. by
  7983. Imul const,%mreg1,%mreg23
  7984. }
  7985. if (taicpu(p).ops=3) and
  7986. GetNextInstruction(p,hp1) and
  7987. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7988. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7989. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7990. begin
  7991. TransferUsedRegs(TmpUsedRegs);
  7992. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7993. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7994. begin
  7995. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7996. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7997. RemoveInstruction(hp1);
  7998. result:=true;
  7999. end;
  8000. end;
  8001. end;
  8002. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  8003. var
  8004. hp1 : tai;
  8005. begin
  8006. result:=false;
  8007. { replace
  8008. IMul %reg0,%reg1,%reg2
  8009. Mov %reg2,%reg3
  8010. dealloc %reg2
  8011. by
  8012. Imul %reg0,%reg1,%reg3
  8013. }
  8014. if GetNextInstruction(p,hp1) and
  8015. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8016. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8017. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8018. begin
  8019. TransferUsedRegs(TmpUsedRegs);
  8020. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8021. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8022. begin
  8023. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8024. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8025. RemoveInstruction(hp1);
  8026. result:=true;
  8027. end;
  8028. end;
  8029. end;
  8030. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8031. var
  8032. hp1: tai;
  8033. begin
  8034. Result:=false;
  8035. { get rid of
  8036. (v)cvtss2sd reg0,<reg1,>reg2
  8037. (v)cvtss2sd reg2,<reg2,>reg0
  8038. }
  8039. if GetNextInstruction(p,hp1) and
  8040. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8041. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8042. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8043. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8044. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8045. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8046. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8047. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8048. )
  8049. ) then
  8050. begin
  8051. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8052. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8053. begin
  8054. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8055. RemoveCurrentP(p);
  8056. RemoveInstruction(hp1);
  8057. end
  8058. else
  8059. begin
  8060. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8061. if taicpu(hp1).opcode=A_CVTSD2SS then
  8062. begin
  8063. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8064. taicpu(p).opcode:=A_MOVAPS;
  8065. end
  8066. else
  8067. begin
  8068. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8069. taicpu(p).opcode:=A_VMOVAPS;
  8070. end;
  8071. taicpu(p).ops:=2;
  8072. RemoveInstruction(hp1);
  8073. end;
  8074. Result:=true;
  8075. Exit;
  8076. end;
  8077. end;
  8078. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8079. var
  8080. hp1, hp2, hp3, hp4, hp5: tai;
  8081. ThisReg: TRegister;
  8082. begin
  8083. Result := False;
  8084. if not GetNextInstruction(p,hp1) then
  8085. Exit;
  8086. {
  8087. convert
  8088. j<c> .L1
  8089. mov 1,reg
  8090. jmp .L2
  8091. .L1
  8092. mov 0,reg
  8093. .L2
  8094. into
  8095. mov 0,reg
  8096. set<not(c)> reg
  8097. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8098. would destroy the flag contents
  8099. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8100. executed at the same time as a previous comparison.
  8101. set<not(c)> reg
  8102. movzx reg, reg
  8103. }
  8104. if MatchInstruction(hp1,A_MOV,[]) and
  8105. (taicpu(hp1).oper[0]^.typ = top_const) and
  8106. (
  8107. (
  8108. (taicpu(hp1).oper[1]^.typ = top_reg)
  8109. {$ifdef i386}
  8110. { Under i386, ESI, EDI, EBP and ESP
  8111. don't have an 8-bit representation }
  8112. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8113. {$endif i386}
  8114. ) or (
  8115. {$ifdef i386}
  8116. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8117. {$endif i386}
  8118. (taicpu(hp1).opsize = S_B)
  8119. )
  8120. ) and
  8121. GetNextInstruction(hp1,hp2) and
  8122. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8123. GetNextInstruction(hp2,hp3) and
  8124. FindLabel(tasmlabel(taicpu(p).oper[0]^.ref^.symbol), hp3) and
  8125. GetNextInstruction(hp3,hp4) and
  8126. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8127. (taicpu(hp4).oper[0]^.typ = top_const) and
  8128. (
  8129. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8130. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8131. ) and
  8132. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8133. GetNextInstruction(hp4,hp5) and
  8134. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol), hp5) then
  8135. begin
  8136. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8137. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8138. tai_label(hp3).labsym.DecRefs;
  8139. { If this isn't the only reference to the middle label, we can
  8140. still make a saving - only that the first jump and everything
  8141. that follows will remain. }
  8142. if (tai_label(hp3).labsym.getrefs = 0) then
  8143. begin
  8144. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8145. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8146. else
  8147. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8148. { remove jump, first label and second MOV (also catching any aligns) }
  8149. repeat
  8150. if not GetNextInstruction(hp2, hp3) then
  8151. InternalError(2021040810);
  8152. RemoveInstruction(hp2);
  8153. hp2 := hp3;
  8154. until hp2 = hp5;
  8155. { Don't decrement reference count before the removal loop
  8156. above, otherwise GetNextInstruction won't stop on the
  8157. the label }
  8158. tai_label(hp5).labsym.DecRefs;
  8159. end
  8160. else
  8161. begin
  8162. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8163. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8164. else
  8165. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8166. end;
  8167. taicpu(p).opcode:=A_SETcc;
  8168. taicpu(p).opsize:=S_B;
  8169. taicpu(p).is_jmp:=False;
  8170. if taicpu(hp1).opsize=S_B then
  8171. begin
  8172. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8173. if taicpu(hp1).oper[1]^.typ = top_reg then
  8174. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8175. RemoveInstruction(hp1);
  8176. end
  8177. else
  8178. begin
  8179. { Will be a register because the size can't be S_B otherwise }
  8180. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8181. taicpu(p).loadreg(0, ThisReg);
  8182. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8183. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8184. begin
  8185. case taicpu(hp1).opsize of
  8186. S_W:
  8187. taicpu(hp1).opsize := S_BW;
  8188. S_L:
  8189. taicpu(hp1).opsize := S_BL;
  8190. {$ifdef x86_64}
  8191. S_Q:
  8192. begin
  8193. taicpu(hp1).opsize := S_BL;
  8194. { Change the destination register to 32-bit }
  8195. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8196. end;
  8197. {$endif x86_64}
  8198. else
  8199. InternalError(2021040820);
  8200. end;
  8201. taicpu(hp1).opcode := A_MOVZX;
  8202. taicpu(hp1).loadreg(0, ThisReg);
  8203. end
  8204. else
  8205. begin
  8206. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8207. { hp1 is already a MOV instruction with the correct register }
  8208. taicpu(hp1).loadconst(0, 0);
  8209. { Inserting it right before p will guarantee that the flags are also tracked }
  8210. asml.Remove(hp1);
  8211. asml.InsertBefore(hp1, p);
  8212. end;
  8213. end;
  8214. Result:=true;
  8215. exit;
  8216. end
  8217. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8218. Result := TryJccStcClcOpt(p, hp1)
  8219. else if (hp1.typ = ait_label) then
  8220. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8221. end;
  8222. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8223. var
  8224. hp1, hp2, hp3: tai;
  8225. SourceRef, TargetRef: TReference;
  8226. CurrentReg: TRegister;
  8227. begin
  8228. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8229. if not UseAVX then
  8230. InternalError(2021100501);
  8231. Result := False;
  8232. { Look for the following to simplify:
  8233. vmovdqa/u x(mem1), %xmmreg
  8234. vmovdqa/u %xmmreg, y(mem2)
  8235. vmovdqa/u x+16(mem1), %xmmreg
  8236. vmovdqa/u %xmmreg, y+16(mem2)
  8237. Change to:
  8238. vmovdqa/u x(mem1), %ymmreg
  8239. vmovdqa/u %ymmreg, y(mem2)
  8240. vpxor %ymmreg, %ymmreg, %ymmreg
  8241. ( The VPXOR instruction is to zero the upper half, thus removing the
  8242. need to call the potentially expensive VZEROUPPER instruction. Other
  8243. peephole optimisations can remove VPXOR if it's unnecessary )
  8244. }
  8245. TransferUsedRegs(TmpUsedRegs);
  8246. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8247. { NOTE: In the optimisations below, if the references dictate that an
  8248. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8249. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8250. if (taicpu(p).opsize = S_XMM) and
  8251. MatchOpType(taicpu(p), top_ref, top_reg) and
  8252. GetNextInstruction(p, hp1) and
  8253. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8254. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8255. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8256. begin
  8257. SourceRef := taicpu(p).oper[0]^.ref^;
  8258. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8259. if GetNextInstruction(hp1, hp2) and
  8260. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8261. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8262. begin
  8263. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8264. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8265. Inc(SourceRef.offset, 16);
  8266. { Reuse the register in the first block move }
  8267. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8268. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8269. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8270. begin
  8271. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8272. Inc(TargetRef.offset, 16);
  8273. if GetNextInstruction(hp2, hp3) and
  8274. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8275. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8276. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8277. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8278. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8279. begin
  8280. { Update the register tracking to the new size }
  8281. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8282. { Remember that the offsets are 16 ahead }
  8283. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8284. if not (
  8285. ((SourceRef.offset mod 32) = 16) and
  8286. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8287. ) then
  8288. taicpu(p).opcode := A_VMOVDQU;
  8289. taicpu(p).opsize := S_YMM;
  8290. taicpu(p).oper[1]^.reg := CurrentReg;
  8291. if not (
  8292. ((TargetRef.offset mod 32) = 16) and
  8293. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8294. ) then
  8295. taicpu(hp1).opcode := A_VMOVDQU;
  8296. taicpu(hp1).opsize := S_YMM;
  8297. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8298. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8299. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8300. if (pi_uses_ymm in current_procinfo.flags) then
  8301. RemoveInstruction(hp2)
  8302. else
  8303. begin
  8304. taicpu(hp2).opcode := A_VPXOR;
  8305. taicpu(hp2).opsize := S_YMM;
  8306. taicpu(hp2).loadreg(0, CurrentReg);
  8307. taicpu(hp2).loadreg(1, CurrentReg);
  8308. taicpu(hp2).loadreg(2, CurrentReg);
  8309. taicpu(hp2).ops := 3;
  8310. end;
  8311. RemoveInstruction(hp3);
  8312. Result := True;
  8313. Exit;
  8314. end;
  8315. end
  8316. else
  8317. begin
  8318. { See if the next references are 16 less rather than 16 greater }
  8319. Dec(SourceRef.offset, 32); { -16 the other way }
  8320. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8321. begin
  8322. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8323. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8324. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8325. GetNextInstruction(hp2, hp3) and
  8326. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8327. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8328. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8329. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8330. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8331. begin
  8332. { Update the register tracking to the new size }
  8333. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8334. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8335. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8336. if not(
  8337. ((SourceRef.offset mod 32) = 0) and
  8338. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8339. ) then
  8340. taicpu(hp2).opcode := A_VMOVDQU;
  8341. taicpu(hp2).opsize := S_YMM;
  8342. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8343. if not (
  8344. ((TargetRef.offset mod 32) = 0) and
  8345. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8346. ) then
  8347. taicpu(hp3).opcode := A_VMOVDQU;
  8348. taicpu(hp3).opsize := S_YMM;
  8349. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8350. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8351. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8352. if (pi_uses_ymm in current_procinfo.flags) then
  8353. RemoveInstruction(hp1)
  8354. else
  8355. begin
  8356. taicpu(hp1).opcode := A_VPXOR;
  8357. taicpu(hp1).opsize := S_YMM;
  8358. taicpu(hp1).loadreg(0, CurrentReg);
  8359. taicpu(hp1).loadreg(1, CurrentReg);
  8360. taicpu(hp1).loadreg(2, CurrentReg);
  8361. taicpu(hp1).ops := 3;
  8362. Asml.Remove(hp1);
  8363. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8364. end;
  8365. RemoveCurrentP(p, hp2);
  8366. Result := True;
  8367. Exit;
  8368. end;
  8369. end;
  8370. end;
  8371. end;
  8372. end;
  8373. end;
  8374. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8375. var
  8376. hp2, hp3, first_assignment: tai;
  8377. IncCount, OperIdx: Integer;
  8378. OrigLabel: TAsmLabel;
  8379. begin
  8380. Count := 0;
  8381. Result := False;
  8382. first_assignment := nil;
  8383. if (LoopCount >= 20) then
  8384. begin
  8385. { Guard against infinite loops }
  8386. Exit;
  8387. end;
  8388. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8389. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8390. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8391. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8392. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8393. Exit;
  8394. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8395. {
  8396. change
  8397. jmp .L1
  8398. ...
  8399. .L1:
  8400. mov ##, ## ( multiple movs possible )
  8401. jmp/ret
  8402. into
  8403. mov ##, ##
  8404. jmp/ret
  8405. }
  8406. if not Assigned(hp1) then
  8407. begin
  8408. hp1 := GetLabelWithSym(OrigLabel);
  8409. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8410. Exit;
  8411. end;
  8412. hp2 := hp1;
  8413. while Assigned(hp2) do
  8414. begin
  8415. if Assigned(hp2) and (hp2.typ = ait_label) then
  8416. SkipLabels(hp2,hp2);
  8417. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8418. Break;
  8419. case taicpu(hp2).opcode of
  8420. A_MOVSD:
  8421. begin
  8422. if taicpu(hp2).ops = 0 then
  8423. { Wrong MOVSD }
  8424. Break;
  8425. Inc(Count);
  8426. if Count >= 5 then
  8427. { Too many to be worthwhile }
  8428. Break;
  8429. GetNextInstruction(hp2, hp2);
  8430. Continue;
  8431. end;
  8432. A_MOV,
  8433. A_MOVD,
  8434. A_MOVQ,
  8435. A_MOVSX,
  8436. {$ifdef x86_64}
  8437. A_MOVSXD,
  8438. {$endif x86_64}
  8439. A_MOVZX,
  8440. A_MOVAPS,
  8441. A_MOVUPS,
  8442. A_MOVSS,
  8443. A_MOVAPD,
  8444. A_MOVUPD,
  8445. A_MOVDQA,
  8446. A_MOVDQU,
  8447. A_VMOVSS,
  8448. A_VMOVAPS,
  8449. A_VMOVUPS,
  8450. A_VMOVSD,
  8451. A_VMOVAPD,
  8452. A_VMOVUPD,
  8453. A_VMOVDQA,
  8454. A_VMOVDQU:
  8455. begin
  8456. Inc(Count);
  8457. if Count >= 5 then
  8458. { Too many to be worthwhile }
  8459. Break;
  8460. GetNextInstruction(hp2, hp2);
  8461. Continue;
  8462. end;
  8463. A_JMP:
  8464. begin
  8465. { Guard against infinite loops }
  8466. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8467. Exit;
  8468. { Analyse this jump first in case it also duplicates assignments }
  8469. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8470. begin
  8471. { Something did change! }
  8472. Result := True;
  8473. Inc(Count, IncCount);
  8474. if Count >= 5 then
  8475. begin
  8476. { Too many to be worthwhile }
  8477. Exit;
  8478. end;
  8479. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8480. Break;
  8481. end;
  8482. Result := True;
  8483. Break;
  8484. end;
  8485. A_RET:
  8486. begin
  8487. Result := True;
  8488. Break;
  8489. end;
  8490. else
  8491. Break;
  8492. end;
  8493. end;
  8494. if Result then
  8495. begin
  8496. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8497. if Count = 0 then
  8498. begin
  8499. Result := False;
  8500. Exit;
  8501. end;
  8502. TransferUsedRegs(TmpUsedRegs);
  8503. hp3 := p;
  8504. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8505. while True do
  8506. begin
  8507. if Assigned(hp1) and (hp1.typ = ait_label) then
  8508. SkipLabels(hp1,hp1);
  8509. case hp1.typ of
  8510. ait_regalloc:
  8511. if tai_regalloc(hp1).ratype = ra_dealloc then
  8512. begin
  8513. { Duplicate the register deallocation... }
  8514. hp3:=tai(hp1.getcopy);
  8515. if first_assignment = nil then
  8516. first_assignment := hp3;
  8517. asml.InsertBefore(hp3, p);
  8518. { ... but also reallocate it after the jump }
  8519. hp3:=tai(hp1.getcopy);
  8520. tai_regalloc(hp3).ratype := ra_alloc;
  8521. asml.InsertAfter(hp3, p);
  8522. end;
  8523. ait_instruction:
  8524. case taicpu(hp1).opcode of
  8525. A_JMP:
  8526. begin
  8527. { Change the original jump to the new destination }
  8528. OrigLabel.decrefs;
  8529. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8530. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8531. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8532. if not Assigned(first_assignment) then
  8533. InternalError(2021040810)
  8534. else
  8535. p := first_assignment;
  8536. Exit;
  8537. end;
  8538. A_RET:
  8539. begin
  8540. { Now change the jump into a RET instruction }
  8541. ConvertJumpToRET(p, hp1);
  8542. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8543. if not Assigned(first_assignment) then
  8544. InternalError(2021040811)
  8545. else
  8546. p := first_assignment;
  8547. Exit;
  8548. end;
  8549. else
  8550. begin
  8551. { Duplicate the MOV instruction }
  8552. hp3:=tai(hp1.getcopy);
  8553. if first_assignment = nil then
  8554. first_assignment := hp3;
  8555. asml.InsertBefore(hp3, p);
  8556. { Make sure the compiler knows about any final registers written here }
  8557. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8558. with taicpu(hp3).oper[OperIdx]^ do
  8559. begin
  8560. case typ of
  8561. top_ref:
  8562. begin
  8563. if (ref^.base <> NR_NO) and
  8564. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8565. (
  8566. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8567. (
  8568. { Allow the frame pointer if it's not being used by the procedure as such }
  8569. Assigned(current_procinfo) and
  8570. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8571. )
  8572. )
  8573. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8574. then
  8575. begin
  8576. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8577. if not Assigned(first_assignment) then
  8578. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8579. end;
  8580. if (ref^.index <> NR_NO) and
  8581. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8582. (
  8583. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8584. (
  8585. { Allow the frame pointer if it's not being used by the procedure as such }
  8586. Assigned(current_procinfo) and
  8587. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8588. )
  8589. )
  8590. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8591. (ref^.index <> ref^.base) then
  8592. begin
  8593. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8594. if not Assigned(first_assignment) then
  8595. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8596. end;
  8597. end;
  8598. top_reg:
  8599. begin
  8600. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8601. if not Assigned(first_assignment) then
  8602. IncludeRegInUsedRegs(reg, UsedRegs);
  8603. end;
  8604. else
  8605. ;
  8606. end;
  8607. end;
  8608. end;
  8609. end;
  8610. else
  8611. InternalError(2021040720);
  8612. end;
  8613. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8614. { Should have dropped out earlier }
  8615. InternalError(2021040710);
  8616. end;
  8617. end;
  8618. end;
  8619. const
  8620. WriteOp: array[0..3] of set of TInsChange = (
  8621. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8622. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8623. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8624. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8625. RegWriteFlags: array[0..7] of set of TInsChange = (
  8626. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8627. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8628. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8629. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8630. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8631. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8632. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8633. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8634. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8635. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8636. var
  8637. hp2: tai;
  8638. X: Integer;
  8639. begin
  8640. { If we have something like:
  8641. op ###,###
  8642. mov ###,###
  8643. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8644. interfere in regards to what they write to.
  8645. NOTE: p must be a 2-operand instruction
  8646. }
  8647. Result := False;
  8648. if (hp1.typ <> ait_instruction) or
  8649. taicpu(hp1).is_jmp or
  8650. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8651. Exit;
  8652. { NOP is a pipeline fence, likely marking the beginning of the function
  8653. epilogue, so drop out. Similarly, drop out if POP or RET are
  8654. encountered }
  8655. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8656. Exit;
  8657. if (taicpu(hp1).opcode = A_MOVSD) and
  8658. (taicpu(hp1).ops = 0) then
  8659. { Wrong MOVSD }
  8660. Exit;
  8661. { Check for writes to specific registers first }
  8662. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8663. for X := 0 to 7 do
  8664. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8665. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8666. Exit;
  8667. for X := 0 to taicpu(hp1).ops - 1 do
  8668. begin
  8669. { Check to see if this operand writes to something }
  8670. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8671. { And matches something in the CMP/TEST instruction }
  8672. (
  8673. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8674. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8675. (
  8676. { If it's a register, make sure the register written to doesn't
  8677. appear in the cmp instruction as part of a reference }
  8678. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8679. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8680. )
  8681. ) then
  8682. Exit;
  8683. end;
  8684. { Check p to make sure it doesn't write to something that affects hp1 }
  8685. { Check for writes to specific registers first }
  8686. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8687. for X := 0 to 7 do
  8688. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8689. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8690. Exit;
  8691. for X := 0 to taicpu(p).ops - 1 do
  8692. begin
  8693. { Check to see if this operand writes to something }
  8694. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8695. { And matches something in hp1 }
  8696. (taicpu(p).oper[X]^.typ = top_reg) and
  8697. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8698. Exit;
  8699. end;
  8700. { The instruction can be safely moved }
  8701. asml.Remove(hp1);
  8702. { Try to insert after the last instructions where the FLAGS register is not
  8703. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8704. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8705. asml.InsertBefore(hp1, hp2)
  8706. { Failing that, try to insert after the last instructions where the
  8707. FLAGS register is not yet in use }
  8708. else if GetLastInstruction(p, hp2) and
  8709. (
  8710. (hp2.typ <> ait_instruction) or
  8711. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8712. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8713. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8714. ) then
  8715. asml.InsertAfter(hp1, hp2)
  8716. else
  8717. { Note, if p.Previous is nil (even if it should logically never be the
  8718. case), FindRegAllocBackward immediately exits with False and so we
  8719. safely land here (we can't just pass p because FindRegAllocBackward
  8720. immediately exits on an instruction). [Kit] }
  8721. asml.InsertBefore(hp1, p);
  8722. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8723. { We can't trust UsedRegs because we're looking backwards, although we
  8724. know the registers are allocated after p at the very least, so manually
  8725. create tai_regalloc objects if needed }
  8726. for X := 0 to taicpu(hp1).ops - 1 do
  8727. case taicpu(hp1).oper[X]^.typ of
  8728. top_reg:
  8729. begin
  8730. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8731. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8732. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8733. end;
  8734. top_ref:
  8735. begin
  8736. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8737. begin
  8738. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8739. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8740. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8741. end;
  8742. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8743. begin
  8744. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8745. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8746. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8747. end;
  8748. end;
  8749. else
  8750. ;
  8751. end;
  8752. Result := True;
  8753. end;
  8754. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8755. var
  8756. hp2: tai;
  8757. X: Integer;
  8758. begin
  8759. { If we have something like:
  8760. cmp ###,%reg1
  8761. mov 0,%reg2
  8762. And no modified registers are shared, move the instruction to before
  8763. the comparison as this means it can be optimised without worrying
  8764. about the FLAGS register. (CMP/MOV is generated by
  8765. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8766. As long as the second instruction doesn't use the flags or one of the
  8767. registers used by CMP or TEST (also check any references that use the
  8768. registers), then it can be moved prior to the comparison.
  8769. }
  8770. Result := False;
  8771. if not TrySwapMovOp(p, hp1) then
  8772. Exit;
  8773. if taicpu(hp1).opcode = A_LEA then
  8774. { The flags will be overwritten by the CMP/TEST instruction }
  8775. ConvertLEA(taicpu(hp1));
  8776. Result := True;
  8777. { Can we move it one further back? }
  8778. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8779. { Check to see if CMP/TEST is a comparison against zero }
  8780. (
  8781. (
  8782. (taicpu(p).opcode = A_CMP) and
  8783. MatchOperand(taicpu(p).oper[0]^, 0)
  8784. ) or
  8785. (
  8786. (taicpu(p).opcode = A_TEST) and
  8787. (
  8788. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8789. MatchOperand(taicpu(p).oper[0]^, -1)
  8790. )
  8791. )
  8792. ) and
  8793. { These instructions set the zero flag if the result is zero }
  8794. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8795. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8796. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8797. TrySwapMovOp(hp2, hp1);
  8798. end;
  8799. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8800. var
  8801. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8802. JumpLabel: TAsmLabel;
  8803. TmpBool: Boolean;
  8804. begin
  8805. Result := False;
  8806. { Look for:
  8807. stc/clc
  8808. j(c) .L1
  8809. ...
  8810. .L1:
  8811. set(n)cb %reg
  8812. (flags deallocated)
  8813. j(c) .L2
  8814. Change to:
  8815. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8816. j(c) .L2
  8817. }
  8818. p_last := p;
  8819. while GetNextInstruction(p_last, hp1) and
  8820. (hp1.typ = ait_instruction) and
  8821. IsJumpToLabel(taicpu(hp1)) do
  8822. begin
  8823. if DoJumpOptimizations(hp1, TmpBool) then
  8824. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8825. Continue;
  8826. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8827. if not Assigned(JumpLabel) then
  8828. InternalError(2024012801);
  8829. { Optimise the J(c); stc/clc optimisation first since this will
  8830. get missed if the main optimisation takes place }
  8831. if (taicpu(hp1).opcode = A_JCC) then
  8832. begin
  8833. if GetNextInstruction(hp1, hp2) and
  8834. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8835. TryJccStcClcOpt(hp1, hp2) then
  8836. begin
  8837. Result := True;
  8838. Exit;
  8839. end;
  8840. hp2 := nil; { Suppress compiler warning }
  8841. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8842. { Make sure the flags aren't used again }
  8843. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8844. begin
  8845. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8846. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8847. begin
  8848. if (taicpu(p).opcode = A_STC) then
  8849. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8850. else
  8851. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8852. MakeUnconditional(taicpu(hp1));
  8853. { Move the jump to after the flag deallocations }
  8854. Asml.Remove(hp1);
  8855. Asml.InsertAfter(hp1, hp2);
  8856. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8857. Result := True;
  8858. Exit;
  8859. end
  8860. else
  8861. begin
  8862. if (taicpu(p).opcode = A_STC) then
  8863. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8864. else
  8865. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8866. { In this case, the jump is deterministic in that it will never be taken }
  8867. JumpLabel.DecRefs;
  8868. RemoveInstruction(hp1);
  8869. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8870. Result := True;
  8871. Exit;
  8872. end;
  8873. end;
  8874. end;
  8875. hp2 := nil; { Suppress compiler warning }
  8876. if
  8877. { Make sure the carry flag doesn't appear in the jump conditions }
  8878. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8879. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8880. GetNextInstruction(hp2, p_dist) and
  8881. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8882. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8883. begin
  8884. case taicpu(p_dist).opcode of
  8885. A_Jcc:
  8886. begin
  8887. if DoJumpOptimizations(p_dist, TmpBool) then
  8888. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8889. Continue;
  8890. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8891. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8892. begin
  8893. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8894. JumpLabel.decrefs;
  8895. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8896. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8897. Result := True;
  8898. Exit;
  8899. end
  8900. else if GetNextInstruction(p_dist, hp1_dist) and
  8901. (hp1_dist.typ = ait_label) then
  8902. begin
  8903. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8904. JumpLabel.decrefs;
  8905. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8906. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8907. Result := True;
  8908. Exit;
  8909. end;
  8910. end;
  8911. A_SETcc:
  8912. if { Make sure the flags aren't used again }
  8913. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8914. GetNextInstruction(hp2, hp1_dist) and
  8915. (hp1_dist.typ = ait_instruction) and
  8916. IsJumpToLabel(taicpu(hp1_dist)) and
  8917. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8918. { This works if hp1_dist or both are regular JMP instructions }
  8919. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8920. (
  8921. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8922. { Make sure the register isn't still in use, otherwise it
  8923. may get corrupted (fixes #40659) }
  8924. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8925. ) then
  8926. begin
  8927. taicpu(p).allocate_oper(2);
  8928. taicpu(p).ops := 2;
  8929. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8930. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8931. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8932. taicpu(p).opcode := A_MOV;
  8933. taicpu(p).opsize := S_B;
  8934. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8935. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8936. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8937. JumpLabel.decrefs;
  8938. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8939. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8940. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8941. (tai_regalloc(hp2).ratype = ra_alloc) then
  8942. begin
  8943. Asml.Remove(hp2);
  8944. Asml.InsertAfter(hp2, p);
  8945. end;
  8946. Result := True;
  8947. Exit;
  8948. end;
  8949. else
  8950. ;
  8951. end;
  8952. end;
  8953. p_last := hp1;
  8954. end;
  8955. end;
  8956. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8957. var
  8958. hp2, hp3: tai;
  8959. TempBool: Boolean;
  8960. begin
  8961. Result := False;
  8962. {
  8963. j(c) .L1
  8964. stc/clc
  8965. .L1:
  8966. jc/jnc .L2
  8967. (Flags deallocated)
  8968. Change to:
  8969. j)c) .L1
  8970. jmp .L2
  8971. .L1:
  8972. jc/jnc .L2
  8973. Then call DoJumpOptimizations to convert to:
  8974. j(nc) .L2
  8975. .L1: (may become a dead label)
  8976. jc/jnc .L2
  8977. }
  8978. if GetNextInstruction(hp1, hp2) and
  8979. (hp2.typ = ait_label) and
  8980. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8981. GetNextInstruction(hp2, hp3) and
  8982. MatchInstruction(hp3, A_Jcc, []) and
  8983. (
  8984. (
  8985. (taicpu(hp3).condition = C_C) and
  8986. (taicpu(hp1).opcode = A_STC)
  8987. ) or (
  8988. (taicpu(hp3).condition = C_NC) and
  8989. (taicpu(hp1).opcode = A_CLC)
  8990. )
  8991. ) and
  8992. { Make sure the flags aren't used again }
  8993. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8994. begin
  8995. taicpu(hp1).allocate_oper(1);
  8996. taicpu(hp1).ops := 1;
  8997. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8998. taicpu(hp1).opcode := A_JMP;
  8999. taicpu(hp1).is_jmp := True;
  9000. TempBool := True; { Prevent compiler warnings }
  9001. if DoJumpOptimizations(p, TempBool) then
  9002. Result := True
  9003. else
  9004. Include(OptsToCheck, aoc_ForceNewIteration);
  9005. end;
  9006. end;
  9007. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  9008. begin
  9009. { This generally only executes under -O3 and above }
  9010. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  9011. end;
  9012. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  9013. var
  9014. hp1, hp2: tai;
  9015. FoundComparison: Boolean;
  9016. begin
  9017. { Run the pass 1 optimisations as well, since they may have some effect
  9018. after the CMOV blocks are created in OptPass2Jcc }
  9019. Result := False;
  9020. { Result := OptPass1CMOVcc(p);
  9021. if Result then
  9022. Exit;}
  9023. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9024. and make a slightly inefficent result on branching-type blocks, notably
  9025. when setting a function result then jumping to the function epilogue.
  9026. In this case, change:
  9027. cmov(c) %reg1,%reg2
  9028. j(c) @lbl
  9029. (%reg2 deallocated)
  9030. To:
  9031. mov %reg11,%reg2
  9032. j(c) @lbl
  9033. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9034. jump because if it's not present, we may end up with a jump that's
  9035. completely unrelated.
  9036. }
  9037. hp1 := p;
  9038. while GetNextInstruction(hp1, hp1) and
  9039. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9040. if (hp1.typ = ait_instruction) and
  9041. (taicpu(hp1).opcode = A_Jcc) and
  9042. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9043. begin
  9044. TransferUsedRegs(TmpUsedRegs);
  9045. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9046. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9047. (
  9048. { See if we can find a more distant instruction that overwrites
  9049. the destination register }
  9050. (cs_opt_level3 in current_settings.optimizerswitches) and
  9051. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9052. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9053. ) then
  9054. begin
  9055. if (taicpu(p).oper[0]^.typ = top_reg) then
  9056. begin
  9057. { Search backwards to see if the source register is set to a
  9058. constant }
  9059. FoundComparison := False;
  9060. hp1 := p;
  9061. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9062. begin
  9063. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9064. begin
  9065. FoundComparison := True;
  9066. Continue;
  9067. end;
  9068. { Once we find the CMP, TEST or similar instruction, we
  9069. have to stop if we find anything other than a MOV }
  9070. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9071. Break;
  9072. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9073. { Destination register was modified }
  9074. Break;
  9075. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9076. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9077. begin
  9078. { Found a constant! }
  9079. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9080. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9081. { The source register is no longer in use }
  9082. RemoveInstruction(hp1);
  9083. Break;
  9084. end;
  9085. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9086. { Some other instruction has modified the source register }
  9087. Break;
  9088. end;
  9089. end;
  9090. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9091. taicpu(p).opcode := A_MOV;
  9092. taicpu(p).condition := C_None;
  9093. { Rely on the post peephole stage to put the MOV before the
  9094. CMP/TEST instruction that appears prior }
  9095. Result := True;
  9096. Exit;
  9097. end;
  9098. end;
  9099. end;
  9100. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9101. function IsXCHGAcceptable: Boolean; inline;
  9102. begin
  9103. { Always accept if optimising for size }
  9104. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9105. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9106. than 3, so it becomes a saving compared to three MOVs with two of
  9107. them able to execute simultaneously. [Kit] }
  9108. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9109. end;
  9110. var
  9111. NewRef: TReference;
  9112. hp1, hp2, hp3, hp4: Tai;
  9113. {$ifndef x86_64}
  9114. OperIdx: Integer;
  9115. {$endif x86_64}
  9116. NewInstr : Taicpu;
  9117. NewAligh : Tai_align;
  9118. DestLabel: TAsmLabel;
  9119. TempTracking: TAllUsedRegs;
  9120. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9121. var
  9122. NextInstr: tai;
  9123. begin
  9124. Result := False;
  9125. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9126. if not GetNextInstruction(InputInstr, NextInstr) or
  9127. (
  9128. { The FLAGS register isn't always tracked properly, so do not
  9129. perform this optimisation if a conditional statement follows }
  9130. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9131. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9132. ) then
  9133. begin
  9134. reference_reset(NewRef, 1, []);
  9135. NewRef.base := taicpu(p).oper[0]^.reg;
  9136. NewRef.scalefactor := 1;
  9137. if taicpu(InputInstr).opcode = A_ADD then
  9138. begin
  9139. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9140. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9141. end
  9142. else
  9143. begin
  9144. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9145. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9146. end;
  9147. taicpu(p).opcode := A_LEA;
  9148. taicpu(p).loadref(0, NewRef);
  9149. { For the sake of debugging, have the line info match the
  9150. arithmetic instruction rather than the MOV instruction }
  9151. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9152. RemoveInstruction(InputInstr);
  9153. Result := True;
  9154. end;
  9155. end;
  9156. begin
  9157. Result:=false;
  9158. { This optimisation adds an instruction, so only do it for speed }
  9159. if not (cs_opt_size in current_settings.optimizerswitches) and
  9160. MatchOpType(taicpu(p), top_const, top_reg) and
  9161. (taicpu(p).oper[0]^.val = 0) then
  9162. begin
  9163. { To avoid compiler warning }
  9164. DestLabel := nil;
  9165. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9166. InternalError(2021040750);
  9167. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9168. Exit;
  9169. case hp1.typ of
  9170. ait_label:
  9171. begin
  9172. { Change:
  9173. mov $0,%reg mov $0,%reg
  9174. @Lbl1: @Lbl1:
  9175. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9176. je @Lbl2 jne @Lbl2
  9177. To: To:
  9178. mov $0,%reg mov $0,%reg
  9179. jmp @Lbl2 jmp @Lbl3
  9180. (align) (align)
  9181. @Lbl1: @Lbl1:
  9182. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9183. je @Lbl2 je @Lbl2
  9184. @Lbl3: <-- Only if label exists
  9185. (Not if it's optimised for size)
  9186. }
  9187. if not GetNextInstruction(hp1, hp2) then
  9188. Exit;
  9189. if (hp2.typ = ait_instruction) and
  9190. (
  9191. { Register sizes must exactly match }
  9192. (
  9193. (taicpu(hp2).opcode = A_CMP) and
  9194. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9195. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9196. ) or (
  9197. (taicpu(hp2).opcode = A_TEST) and
  9198. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9199. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9200. )
  9201. ) and GetNextInstruction(hp2, hp3) and
  9202. (hp3.typ = ait_instruction) and
  9203. (taicpu(hp3).opcode = A_JCC) and
  9204. (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
  9205. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9206. begin
  9207. { Check condition of jump }
  9208. { Always true? }
  9209. if condition_in(C_E, taicpu(hp3).condition) then
  9210. begin
  9211. { Copy label symbol and obtain matching label entry for the
  9212. conditional jump, as this will be our destination}
  9213. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9214. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9215. Result := True;
  9216. end
  9217. { Always false? }
  9218. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9219. begin
  9220. { This is only worth it if there's a jump to take }
  9221. case hp2.typ of
  9222. ait_instruction:
  9223. begin
  9224. if taicpu(hp2).opcode = A_JMP then
  9225. begin
  9226. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9227. { An unconditional jump follows the conditional jump which will always be false,
  9228. so use this jump's destination for the new jump }
  9229. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9230. Result := True;
  9231. end
  9232. else if taicpu(hp2).opcode = A_JCC then
  9233. begin
  9234. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9235. if condition_in(C_E, taicpu(hp2).condition) then
  9236. begin
  9237. { A second conditional jump follows the conditional jump which will always be false,
  9238. while the second jump is always True, so use this jump's destination for the new jump }
  9239. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9240. Result := True;
  9241. end;
  9242. { Don't risk it if the jump isn't always true (Result remains False) }
  9243. end;
  9244. end;
  9245. else
  9246. { If anything else don't optimise };
  9247. end;
  9248. end;
  9249. if Result then
  9250. begin
  9251. { Just so we have something to insert as a paremeter}
  9252. reference_reset(NewRef, 1, []);
  9253. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9254. { Now actually load the correct parameter (this also
  9255. increases the reference count) }
  9256. NewInstr.loadsymbol(0, DestLabel, 0);
  9257. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9258. begin
  9259. { Get instruction before original label (may not be p under -O3) }
  9260. if not GetLastInstruction(hp1, hp2) then
  9261. { Shouldn't fail here }
  9262. InternalError(2021040701);
  9263. end
  9264. else
  9265. hp2 := p;
  9266. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9267. AsmL.InsertAfter(NewInstr, hp2);
  9268. { Add new alignment field }
  9269. (* AsmL.InsertAfter(
  9270. cai_align.create_max(
  9271. current_settings.alignment.jumpalign,
  9272. current_settings.alignment.jumpalignskipmax
  9273. ),
  9274. NewInstr
  9275. ); *)
  9276. end;
  9277. Exit;
  9278. end;
  9279. end;
  9280. else
  9281. ;
  9282. end;
  9283. end;
  9284. if not GetNextInstruction(p, hp1) then
  9285. Exit;
  9286. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9287. begin
  9288. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9289. begin
  9290. Result := True;
  9291. Exit;
  9292. end;
  9293. { This optimisation is only effective on a second run of Pass 2,
  9294. hence -O3 or above.
  9295. Change:
  9296. mov %reg1,%reg2
  9297. cmp/test (contains %reg1)
  9298. mov x, %reg1
  9299. (another mov or a j(c))
  9300. To:
  9301. mov %reg1,%reg2
  9302. mov x, %reg1
  9303. cmp (%reg1 replaced with %reg2)
  9304. (another mov or a j(c))
  9305. The requirement of an additional MOV or a jump ensures there
  9306. isn't performance loss, since a j(c) will permit macro-fusion
  9307. with the cmp instruction, while another MOV likely means it's
  9308. not all being executed in a single cycle due to parallelisation.
  9309. }
  9310. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9311. MatchOpType(taicpu(p), top_reg, top_reg) and
  9312. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9313. GetNextInstruction(hp1, hp2) and
  9314. MatchInstruction(hp2, A_MOV, []) and
  9315. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9316. { Registers don't have to be the same size in this case }
  9317. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9318. GetNextInstruction(hp2, hp3) and
  9319. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9320. { Make sure the operands in the camparison can be safely replaced }
  9321. (
  9322. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9323. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9324. ) and
  9325. (
  9326. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9327. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9328. ) then
  9329. begin
  9330. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9331. AsmL.Remove(hp2);
  9332. AsmL.InsertAfter(hp2, p);
  9333. Result := True;
  9334. Exit;
  9335. end;
  9336. end;
  9337. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9338. begin
  9339. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9340. further, but we can't just put this jump optimisation in pass 1
  9341. because it tends to perform worse when conditional jumps are
  9342. nearby (e.g. when converting CMOV instructions). [Kit] }
  9343. CopyUsedRegs(TempTracking);
  9344. UpdateUsedRegs(tai(p.Next));
  9345. if OptPass2JMP(hp1) then
  9346. begin
  9347. { Restore register state }
  9348. RestoreUsedRegs(TempTracking);
  9349. ReleaseUsedRegs(TempTracking);
  9350. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9351. OptPass1MOV(p);
  9352. Result := True;
  9353. Exit;
  9354. end;
  9355. { If OptPass2JMP returned False, no optimisations were done to
  9356. the jump and there are no further optimisations that can be done
  9357. to the MOV instruction on this pass other than FuncMov2Func }
  9358. { Restore register state }
  9359. RestoreUsedRegs(TempTracking);
  9360. ReleaseUsedRegs(TempTracking);
  9361. Result := FuncMov2Func(p, hp1);
  9362. Exit;
  9363. end;
  9364. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9365. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9366. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9367. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9368. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9369. begin
  9370. { Change:
  9371. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9372. addl/q $x,%reg2 subl/q $x,%reg2
  9373. To:
  9374. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9375. }
  9376. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9377. { be lazy, checking separately for sub would be slightly better }
  9378. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9379. begin
  9380. TransferUsedRegs(TmpUsedRegs);
  9381. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9382. if TryMovArith2Lea(hp1) then
  9383. begin
  9384. Result := True;
  9385. Exit;
  9386. end
  9387. end
  9388. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9389. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9390. { Same as above, but also adds or subtracts to %reg2 in between.
  9391. It's still valid as long as the flags aren't in use }
  9392. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9393. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9394. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9395. { be lazy, checking separately for sub would be slightly better }
  9396. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9397. begin
  9398. TransferUsedRegs(TmpUsedRegs);
  9399. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9400. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9401. if TryMovArith2Lea(hp2) then
  9402. begin
  9403. Result := True;
  9404. Exit;
  9405. end;
  9406. end;
  9407. end;
  9408. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9409. {$ifdef x86_64}
  9410. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9411. {$else x86_64}
  9412. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9413. {$endif x86_64}
  9414. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9415. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9416. { mov reg1, reg2 mov reg1, reg2
  9417. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9418. begin
  9419. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9420. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9421. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9422. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9423. TransferUsedRegs(TmpUsedRegs);
  9424. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9425. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9426. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9427. then
  9428. begin
  9429. RemoveCurrentP(p, hp1);
  9430. Result:=true;
  9431. end;
  9432. Exit;
  9433. end;
  9434. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9435. IsXCHGAcceptable and
  9436. { XCHG doesn't support 8-bit registers }
  9437. (taicpu(p).opsize <> S_B) and
  9438. MatchInstruction(hp1, A_MOV, []) and
  9439. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9440. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9441. GetNextInstruction(hp1, hp2) and
  9442. MatchInstruction(hp2, A_MOV, []) and
  9443. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9444. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9445. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9446. begin
  9447. { mov %reg1,%reg2
  9448. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9449. mov %reg2,%reg3
  9450. (%reg2 not used afterwards)
  9451. Note that xchg takes 3 cycles to execute, and generally mov's take
  9452. only one cycle apiece, but the first two mov's can be executed in
  9453. parallel, only taking 2 cycles overall. Older processors should
  9454. therefore only optimise for size. [Kit]
  9455. }
  9456. TransferUsedRegs(TmpUsedRegs);
  9457. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9458. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9459. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9460. begin
  9461. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9462. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9463. taicpu(hp1).opcode := A_XCHG;
  9464. RemoveCurrentP(p, hp1);
  9465. RemoveInstruction(hp2);
  9466. Result := True;
  9467. Exit;
  9468. end;
  9469. end;
  9470. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9471. MatchInstruction(hp1, A_SAR, []) then
  9472. begin
  9473. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9474. begin
  9475. { the use of %edx also covers the opsize being S_L }
  9476. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9477. begin
  9478. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9479. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9480. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9481. begin
  9482. { Change:
  9483. movl %eax,%edx
  9484. sarl $31,%edx
  9485. To:
  9486. cltd
  9487. }
  9488. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9489. RemoveInstruction(hp1);
  9490. taicpu(p).opcode := A_CDQ;
  9491. taicpu(p).opsize := S_NO;
  9492. taicpu(p).clearop(1);
  9493. taicpu(p).clearop(0);
  9494. taicpu(p).ops:=0;
  9495. Result := True;
  9496. Exit;
  9497. end
  9498. else if (cs_opt_size in current_settings.optimizerswitches) and
  9499. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9500. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9501. begin
  9502. { Change:
  9503. movl %edx,%eax
  9504. sarl $31,%edx
  9505. To:
  9506. movl %edx,%eax
  9507. cltd
  9508. Note that this creates a dependency between the two instructions,
  9509. so only perform if optimising for size.
  9510. }
  9511. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9512. taicpu(hp1).opcode := A_CDQ;
  9513. taicpu(hp1).opsize := S_NO;
  9514. taicpu(hp1).clearop(1);
  9515. taicpu(hp1).clearop(0);
  9516. taicpu(hp1).ops:=0;
  9517. Include(OptsToCheck, aoc_ForceNewIteration);
  9518. Exit;
  9519. end;
  9520. {$ifndef x86_64}
  9521. end
  9522. { Don't bother if CMOV is supported, because a more optimal
  9523. sequence would have been generated for the Abs() intrinsic }
  9524. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9525. { the use of %eax also covers the opsize being S_L }
  9526. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9527. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9528. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9529. GetNextInstruction(hp1, hp2) and
  9530. MatchInstruction(hp2, A_XOR, [S_L]) and
  9531. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9532. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9533. GetNextInstruction(hp2, hp3) and
  9534. MatchInstruction(hp3, A_SUB, [S_L]) and
  9535. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9536. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9537. begin
  9538. { Change:
  9539. movl %eax,%edx
  9540. sarl $31,%eax
  9541. xorl %eax,%edx
  9542. subl %eax,%edx
  9543. (Instruction that uses %edx)
  9544. (%eax deallocated)
  9545. (%edx deallocated)
  9546. To:
  9547. cltd
  9548. xorl %edx,%eax <-- Note the registers have swapped
  9549. subl %edx,%eax
  9550. (Instruction that uses %eax) <-- %eax rather than %edx
  9551. }
  9552. TransferUsedRegs(TmpUsedRegs);
  9553. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9554. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9555. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9556. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9557. begin
  9558. if GetNextInstruction(hp3, hp4) and
  9559. not RegModifiedByInstruction(NR_EDX, hp4) and
  9560. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9561. begin
  9562. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9563. taicpu(p).opcode := A_CDQ;
  9564. taicpu(p).clearop(1);
  9565. taicpu(p).clearop(0);
  9566. taicpu(p).ops:=0;
  9567. RemoveInstruction(hp1);
  9568. taicpu(hp2).loadreg(0, NR_EDX);
  9569. taicpu(hp2).loadreg(1, NR_EAX);
  9570. taicpu(hp3).loadreg(0, NR_EDX);
  9571. taicpu(hp3).loadreg(1, NR_EAX);
  9572. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9573. { Convert references in the following instruction (hp4) from %edx to %eax }
  9574. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9575. with taicpu(hp4).oper[OperIdx]^ do
  9576. case typ of
  9577. top_reg:
  9578. if getsupreg(reg) = RS_EDX then
  9579. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9580. top_ref:
  9581. begin
  9582. if getsupreg(reg) = RS_EDX then
  9583. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9584. if getsupreg(reg) = RS_EDX then
  9585. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9586. end;
  9587. else
  9588. ;
  9589. end;
  9590. Result := True;
  9591. Exit;
  9592. end;
  9593. end;
  9594. {$else x86_64}
  9595. end;
  9596. end
  9597. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9598. { the use of %rdx also covers the opsize being S_Q }
  9599. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9600. begin
  9601. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9602. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9603. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9604. begin
  9605. { Change:
  9606. movq %rax,%rdx
  9607. sarq $63,%rdx
  9608. To:
  9609. cqto
  9610. }
  9611. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9612. RemoveInstruction(hp1);
  9613. taicpu(p).opcode := A_CQO;
  9614. taicpu(p).opsize := S_NO;
  9615. taicpu(p).clearop(1);
  9616. taicpu(p).clearop(0);
  9617. taicpu(p).ops:=0;
  9618. Result := True;
  9619. Exit;
  9620. end
  9621. else if (cs_opt_size in current_settings.optimizerswitches) and
  9622. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9623. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9624. begin
  9625. { Change:
  9626. movq %rdx,%rax
  9627. sarq $63,%rdx
  9628. To:
  9629. movq %rdx,%rax
  9630. cqto
  9631. Note that this creates a dependency between the two instructions,
  9632. so only perform if optimising for size.
  9633. }
  9634. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9635. taicpu(hp1).opcode := A_CQO;
  9636. taicpu(hp1).opsize := S_NO;
  9637. taicpu(hp1).clearop(1);
  9638. taicpu(hp1).clearop(0);
  9639. taicpu(hp1).ops:=0;
  9640. Include(OptsToCheck, aoc_ForceNewIteration);
  9641. Exit;
  9642. {$endif x86_64}
  9643. end;
  9644. end;
  9645. end;
  9646. if MatchInstruction(hp1, A_MOV, []) and
  9647. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9648. { Though "GetNextInstruction" could be factored out, along with
  9649. the instructions that depend on hp2, it is an expensive call that
  9650. should be delayed for as long as possible, hence we do cheaper
  9651. checks first that are likely to be False. [Kit] }
  9652. begin
  9653. if (
  9654. (
  9655. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9656. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9657. (
  9658. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9659. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9660. )
  9661. ) or
  9662. (
  9663. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9664. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9665. (
  9666. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9667. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9668. )
  9669. )
  9670. ) and
  9671. GetNextInstruction(hp1, hp2) and
  9672. MatchInstruction(hp2, A_SAR, []) and
  9673. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9674. begin
  9675. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9676. begin
  9677. { Change:
  9678. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9679. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9680. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9681. To:
  9682. movl r/m,%eax <- Note the change in register
  9683. cltd
  9684. }
  9685. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9686. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9687. taicpu(p).loadreg(1, NR_EAX);
  9688. taicpu(hp1).opcode := A_CDQ;
  9689. taicpu(hp1).clearop(1);
  9690. taicpu(hp1).clearop(0);
  9691. taicpu(hp1).ops:=0;
  9692. RemoveInstruction(hp2);
  9693. Include(OptsToCheck, aoc_ForceNewIteration);
  9694. (*
  9695. {$ifdef x86_64}
  9696. end
  9697. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9698. { This code sequence does not get generated - however it might become useful
  9699. if and when 128-bit signed integer types make an appearance, so the code
  9700. is kept here for when it is eventually needed. [Kit] }
  9701. (
  9702. (
  9703. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9704. (
  9705. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9706. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9707. )
  9708. ) or
  9709. (
  9710. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9711. (
  9712. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9713. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9714. )
  9715. )
  9716. ) and
  9717. GetNextInstruction(hp1, hp2) and
  9718. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9719. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9720. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9721. begin
  9722. { Change:
  9723. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9724. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9725. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9726. To:
  9727. movq r/m,%rax <- Note the change in register
  9728. cqto
  9729. }
  9730. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9731. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9732. taicpu(p).loadreg(1, NR_RAX);
  9733. taicpu(hp1).opcode := A_CQO;
  9734. taicpu(hp1).clearop(1);
  9735. taicpu(hp1).clearop(0);
  9736. taicpu(hp1).ops:=0;
  9737. RemoveInstruction(hp2);
  9738. Include(OptsToCheck, aoc_ForceNewIteration);
  9739. {$endif x86_64}
  9740. *)
  9741. end;
  9742. end;
  9743. {$ifdef x86_64}
  9744. end;
  9745. if (taicpu(p).opsize = S_L) and
  9746. (taicpu(p).oper[1]^.typ = top_reg) and
  9747. (
  9748. MatchInstruction(hp1, A_MOV,[]) and
  9749. (taicpu(hp1).opsize = S_L) and
  9750. (taicpu(hp1).oper[1]^.typ = top_reg)
  9751. ) and (
  9752. GetNextInstruction(hp1, hp2) and
  9753. (tai(hp2).typ=ait_instruction) and
  9754. (taicpu(hp2).opsize = S_Q) and
  9755. (
  9756. (
  9757. MatchInstruction(hp2, A_ADD,[]) and
  9758. (taicpu(hp2).opsize = S_Q) and
  9759. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9760. (
  9761. (
  9762. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9763. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9764. ) or (
  9765. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9766. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9767. )
  9768. )
  9769. ) or (
  9770. MatchInstruction(hp2, A_LEA,[]) and
  9771. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9772. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9773. (
  9774. (
  9775. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9776. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9777. ) or (
  9778. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9779. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9780. )
  9781. ) and (
  9782. (
  9783. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9784. ) or (
  9785. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9786. )
  9787. )
  9788. )
  9789. )
  9790. ) and (
  9791. GetNextInstruction(hp2, hp3) and
  9792. MatchInstruction(hp3, A_SHR,[]) and
  9793. (taicpu(hp3).opsize = S_Q) and
  9794. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9795. (taicpu(hp3).oper[0]^.val = 1) and
  9796. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9797. ) then
  9798. begin
  9799. { Change movl x, reg1d movl x, reg1d
  9800. movl y, reg2d movl y, reg2d
  9801. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9802. shrq $1, reg1q shrq $1, reg1q
  9803. ( reg1d and reg2d can be switched around in the first two instructions )
  9804. To movl x, reg1d
  9805. addl y, reg1d
  9806. rcrl $1, reg1d
  9807. This corresponds to the common expression (x + y) shr 1, where
  9808. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9809. smaller code, but won't account for x + y causing an overflow). [Kit]
  9810. }
  9811. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9812. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9813. begin
  9814. { Change first MOV command to have the same register as the final output }
  9815. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9816. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  9817. Result := True;
  9818. end
  9819. else
  9820. begin
  9821. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9822. Include(OptsToCheck, aoc_ForceNewIteration);
  9823. end;
  9824. { Change second MOV command to an ADD command. This is easier than
  9825. converting the existing command because it means we don't have to
  9826. touch 'y', which might be a complicated reference, and also the
  9827. fact that the third command might either be ADD or LEA. [Kit] }
  9828. taicpu(hp1).opcode := A_ADD;
  9829. { Delete old ADD/LEA instruction }
  9830. RemoveInstruction(hp2);
  9831. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9832. taicpu(hp3).opcode := A_RCR;
  9833. taicpu(hp3).changeopsize(S_L);
  9834. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9835. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  9836. called, so FuncMov2Func below is safe to call }
  9837. {$endif x86_64}
  9838. end;
  9839. if FuncMov2Func(p, hp1) then
  9840. begin
  9841. Result := True;
  9842. Exit;
  9843. end;
  9844. end;
  9845. {$push}
  9846. {$q-}{$r-}
  9847. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9848. var
  9849. ThisReg: TRegister;
  9850. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9851. TargetSubReg: TSubRegister;
  9852. hp1, hp2: tai;
  9853. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9854. { Store list of found instructions so we don't have to call
  9855. GetNextInstructionUsingReg multiple times }
  9856. InstrList: array of taicpu;
  9857. InstrMax, Index: Integer;
  9858. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9859. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9860. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9861. WorkingValue: TCgInt;
  9862. PreMessage: string;
  9863. { Data flow analysis }
  9864. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9865. BitwiseOnly, OrXorUsed,
  9866. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9867. function CheckOverflowConditions: Boolean;
  9868. begin
  9869. Result := True;
  9870. if (TestValSignedMax > SignedUpperLimit) then
  9871. UpperSignedOverflow := True;
  9872. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9873. LowerSignedOverflow := True;
  9874. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9875. LowerUnsignedOverflow := True;
  9876. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9877. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9878. begin
  9879. { Absolute overflow }
  9880. Result := False;
  9881. Exit;
  9882. end;
  9883. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9884. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9885. ShiftDownOverflow := True;
  9886. if (TestValMin < 0) or (TestValMax < 0) then
  9887. begin
  9888. LowerUnsignedOverflow := True;
  9889. UpperUnsignedOverflow := True;
  9890. end;
  9891. end;
  9892. function AdjustInitialLoadAndSize: Boolean;
  9893. begin
  9894. Result := False;
  9895. if not p_removed then
  9896. begin
  9897. if TargetSize = MinSize then
  9898. begin
  9899. { Convert the input MOVZX to a MOV }
  9900. if (taicpu(p).oper[0]^.typ = top_reg) and
  9901. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9902. begin
  9903. { Or remove it completely! }
  9904. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9905. RemoveCurrentP(p);
  9906. p_removed := True;
  9907. end
  9908. else
  9909. begin
  9910. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9911. taicpu(p).opcode := A_MOV;
  9912. taicpu(p).oper[1]^.reg := ThisReg;
  9913. taicpu(p).opsize := TargetSize;
  9914. end;
  9915. Result := True;
  9916. end
  9917. else if TargetSize <> MaxSize then
  9918. begin
  9919. case MaxSize of
  9920. S_L:
  9921. if TargetSize = S_W then
  9922. begin
  9923. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9924. taicpu(p).opsize := S_BW;
  9925. taicpu(p).oper[1]^.reg := ThisReg;
  9926. Result := True;
  9927. end
  9928. else
  9929. InternalError(2020112341);
  9930. S_W:
  9931. if TargetSize = S_L then
  9932. begin
  9933. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9934. taicpu(p).opsize := S_BL;
  9935. taicpu(p).oper[1]^.reg := ThisReg;
  9936. Result := True;
  9937. end
  9938. else
  9939. InternalError(2020112342);
  9940. else
  9941. ;
  9942. end;
  9943. end
  9944. else if not hp1_removed and not RegInUse then
  9945. begin
  9946. { If we have something like:
  9947. movzbl (oper),%regd
  9948. add x, %regd
  9949. movzbl %regb, %regd
  9950. We can reduce the register size to the input of the final
  9951. movzbl instruction. Overflows won't have any effect.
  9952. }
  9953. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9954. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9955. begin
  9956. TargetSize := S_B;
  9957. setsubreg(ThisReg, R_SUBL);
  9958. Result := True;
  9959. end
  9960. else if (taicpu(p).opsize = S_WL) and
  9961. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9962. begin
  9963. TargetSize := S_W;
  9964. setsubreg(ThisReg, R_SUBW);
  9965. Result := True;
  9966. end;
  9967. if Result then
  9968. begin
  9969. { Convert the input MOVZX to a MOV }
  9970. if (taicpu(p).oper[0]^.typ = top_reg) and
  9971. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9972. begin
  9973. { Or remove it completely! }
  9974. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9975. RemoveCurrentP(p);
  9976. p_removed := True;
  9977. end
  9978. else
  9979. begin
  9980. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9981. taicpu(p).opcode := A_MOV;
  9982. taicpu(p).oper[1]^.reg := ThisReg;
  9983. taicpu(p).opsize := TargetSize;
  9984. end;
  9985. end;
  9986. end;
  9987. end;
  9988. end;
  9989. procedure AdjustFinalLoad;
  9990. begin
  9991. if not LowerUnsignedOverflow then
  9992. begin
  9993. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9994. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9995. begin
  9996. { Convert the output MOVZX to a MOV }
  9997. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9998. begin
  9999. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  10000. if (MinSize = S_B) or
  10001. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  10002. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  10003. begin
  10004. { Remove it completely! }
  10005. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  10006. { Be careful; if p = hp1 and p was also removed, p
  10007. will become a dangling pointer }
  10008. if p = hp1 then
  10009. begin
  10010. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10011. p_removed := True;
  10012. end
  10013. else
  10014. RemoveInstruction(hp1);
  10015. hp1_removed := True;
  10016. end;
  10017. end
  10018. else
  10019. begin
  10020. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10021. taicpu(hp1).opcode := A_MOV;
  10022. taicpu(hp1).oper[0]^.reg := ThisReg;
  10023. taicpu(hp1).opsize := TargetSize;
  10024. end;
  10025. end
  10026. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10027. begin
  10028. { Need to change the size of the output }
  10029. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10030. taicpu(hp1).oper[0]^.reg := ThisReg;
  10031. taicpu(hp1).opsize := S_BL;
  10032. end;
  10033. end;
  10034. end;
  10035. function CompressInstructions: Boolean;
  10036. var
  10037. LocalIndex: Integer;
  10038. begin
  10039. Result := False;
  10040. { The objective here is to try to find a combination that
  10041. removes one of the MOV/Z instructions. }
  10042. if (
  10043. (taicpu(p).oper[0]^.typ <> top_reg) or
  10044. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10045. ) and
  10046. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10047. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10048. begin
  10049. { Make a preference to remove the second MOVZX instruction }
  10050. case taicpu(hp1).opsize of
  10051. S_BL, S_WL:
  10052. begin
  10053. TargetSize := S_L;
  10054. TargetSubReg := R_SUBD;
  10055. end;
  10056. S_BW:
  10057. begin
  10058. TargetSize := S_W;
  10059. TargetSubReg := R_SUBW;
  10060. end;
  10061. else
  10062. InternalError(2020112302);
  10063. end;
  10064. end
  10065. else
  10066. begin
  10067. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10068. begin
  10069. { Exceeded lower bound but not upper bound }
  10070. TargetSize := MaxSize;
  10071. end
  10072. else if not LowerUnsignedOverflow then
  10073. begin
  10074. { Size didn't exceed lower bound }
  10075. TargetSize := MinSize;
  10076. end
  10077. else
  10078. Exit;
  10079. end;
  10080. case TargetSize of
  10081. S_B:
  10082. TargetSubReg := R_SUBL;
  10083. S_W:
  10084. TargetSubReg := R_SUBW;
  10085. S_L:
  10086. TargetSubReg := R_SUBD;
  10087. else
  10088. InternalError(2020112350);
  10089. end;
  10090. { Update the register to its new size }
  10091. setsubreg(ThisReg, TargetSubReg);
  10092. RegInUse := False;
  10093. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10094. begin
  10095. { Check to see if the active register is used afterwards;
  10096. if not, we can change it and make a saving. }
  10097. TransferUsedRegs(TmpUsedRegs);
  10098. { The target register may be marked as in use to cross
  10099. a jump to a distant label, so exclude it }
  10100. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10101. hp2 := p;
  10102. repeat
  10103. { Explicitly check for the excluded register (don't include the first
  10104. instruction as it may be reading from here }
  10105. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10106. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10107. begin
  10108. RegInUse := True;
  10109. Break;
  10110. end;
  10111. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10112. if not GetNextInstruction(hp2, hp2) then
  10113. InternalError(2020112340);
  10114. until (hp2 = hp1);
  10115. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10116. { We might still be able to get away with this }
  10117. RegInUse := not
  10118. (
  10119. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10120. (hp2.typ = ait_instruction) and
  10121. (
  10122. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10123. instruction that doesn't actually contain ThisReg }
  10124. (cs_opt_level3 in current_settings.optimizerswitches) or
  10125. RegInInstruction(ThisReg, hp2)
  10126. ) and
  10127. RegLoadedWithNewValue(ThisReg, hp2)
  10128. );
  10129. if not RegInUse then
  10130. begin
  10131. { Force the register size to the same as this instruction so it can be removed}
  10132. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10133. begin
  10134. TargetSize := S_L;
  10135. TargetSubReg := R_SUBD;
  10136. end
  10137. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10138. begin
  10139. TargetSize := S_W;
  10140. TargetSubReg := R_SUBW;
  10141. end;
  10142. ThisReg := taicpu(hp1).oper[1]^.reg;
  10143. setsubreg(ThisReg, TargetSubReg);
  10144. RegChanged := True;
  10145. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10146. TransferUsedRegs(TmpUsedRegs);
  10147. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10148. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10149. if p = hp1 then
  10150. begin
  10151. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10152. p_removed := True;
  10153. end
  10154. else
  10155. RemoveInstruction(hp1);
  10156. hp1_removed := True;
  10157. { Instruction will become "mov %reg,%reg" }
  10158. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10159. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10160. begin
  10161. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10162. RemoveCurrentP(p);
  10163. p_removed := True;
  10164. end
  10165. else
  10166. taicpu(p).oper[1]^.reg := ThisReg;
  10167. Result := True;
  10168. end
  10169. else
  10170. begin
  10171. if TargetSize <> MaxSize then
  10172. begin
  10173. { Since the register is in use, we have to force it to
  10174. MaxSize otherwise part of it may become undefined later on }
  10175. TargetSize := MaxSize;
  10176. case TargetSize of
  10177. S_B:
  10178. TargetSubReg := R_SUBL;
  10179. S_W:
  10180. TargetSubReg := R_SUBW;
  10181. S_L:
  10182. TargetSubReg := R_SUBD;
  10183. else
  10184. InternalError(2020112351);
  10185. end;
  10186. setsubreg(ThisReg, TargetSubReg);
  10187. end;
  10188. AdjustFinalLoad;
  10189. end;
  10190. end
  10191. else
  10192. AdjustFinalLoad;
  10193. Result := AdjustInitialLoadAndSize or Result;
  10194. { Now go through every instruction we found and change the
  10195. size. If TargetSize = MaxSize, then almost no changes are
  10196. needed and Result can remain False if it hasn't been set
  10197. yet.
  10198. If RegChanged is True, then the register requires changing
  10199. and so the point about TargetSize = MaxSize doesn't apply. }
  10200. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10201. begin
  10202. for LocalIndex := 0 to InstrMax do
  10203. begin
  10204. { If p_removed is true, then the original MOV/Z was removed
  10205. and removing the AND instruction may not be safe if it
  10206. appears first }
  10207. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10208. InternalError(2020112310);
  10209. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10210. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10211. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10212. InstrList[LocalIndex].opsize := TargetSize;
  10213. end;
  10214. Result := True;
  10215. end;
  10216. end;
  10217. begin
  10218. Result := False;
  10219. p_removed := False;
  10220. hp1_removed := False;
  10221. ThisReg := taicpu(p).oper[1]^.reg;
  10222. { Check for:
  10223. movs/z ###,%ecx (or %cx or %rcx)
  10224. ...
  10225. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10226. (dealloc %ecx)
  10227. Change to:
  10228. mov ###,%cl (if ### = %cl, then remove completely)
  10229. ...
  10230. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10231. }
  10232. if (getsupreg(ThisReg) = RS_ECX) and
  10233. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10234. (hp1.typ = ait_instruction) and
  10235. (
  10236. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10237. instruction that doesn't actually contain ECX }
  10238. (cs_opt_level3 in current_settings.optimizerswitches) or
  10239. RegInInstruction(NR_ECX, hp1) or
  10240. (
  10241. { It's common for the shift/rotate's read/write register to be
  10242. initialised in between, so under -O2 and under, search ahead
  10243. one more instruction
  10244. }
  10245. GetNextInstruction(hp1, hp1) and
  10246. (hp1.typ = ait_instruction) and
  10247. RegInInstruction(NR_ECX, hp1)
  10248. )
  10249. ) and
  10250. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10251. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10252. begin
  10253. TransferUsedRegs(TmpUsedRegs);
  10254. hp2 := p;
  10255. repeat
  10256. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10257. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10258. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10259. begin
  10260. case taicpu(p).opsize of
  10261. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10262. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10263. begin
  10264. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10265. RemoveCurrentP(p);
  10266. end
  10267. else
  10268. begin
  10269. taicpu(p).opcode := A_MOV;
  10270. taicpu(p).opsize := S_B;
  10271. taicpu(p).oper[1]^.reg := NR_CL;
  10272. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10273. end;
  10274. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10275. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10276. begin
  10277. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10278. RemoveCurrentP(p);
  10279. end
  10280. else
  10281. begin
  10282. taicpu(p).opcode := A_MOV;
  10283. taicpu(p).opsize := S_W;
  10284. taicpu(p).oper[1]^.reg := NR_CX;
  10285. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10286. end;
  10287. {$ifdef x86_64}
  10288. S_LQ:
  10289. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10290. begin
  10291. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10292. RemoveCurrentP(p);
  10293. end
  10294. else
  10295. begin
  10296. taicpu(p).opcode := A_MOV;
  10297. taicpu(p).opsize := S_L;
  10298. taicpu(p).oper[1]^.reg := NR_ECX;
  10299. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10300. end;
  10301. {$endif x86_64}
  10302. else
  10303. InternalError(2021120401);
  10304. end;
  10305. Result := True;
  10306. Exit;
  10307. end;
  10308. end;
  10309. { This is anything but quick! }
  10310. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10311. Exit;
  10312. SetLength(InstrList, 0);
  10313. InstrMax := -1;
  10314. case taicpu(p).opsize of
  10315. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10316. begin
  10317. {$if defined(i386) or defined(i8086)}
  10318. { If the target size is 8-bit, make sure we can actually encode it }
  10319. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10320. Exit;
  10321. {$endif i386 or i8086}
  10322. LowerLimit := $FF;
  10323. SignedLowerLimit := $7F;
  10324. SignedLowerLimitBottom := -128;
  10325. MinSize := S_B;
  10326. if taicpu(p).opsize = S_BW then
  10327. begin
  10328. MaxSize := S_W;
  10329. UpperLimit := $FFFF;
  10330. SignedUpperLimit := $7FFF;
  10331. SignedUpperLimitBottom := -32768;
  10332. end
  10333. else
  10334. begin
  10335. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10336. MaxSize := S_L;
  10337. UpperLimit := $FFFFFFFF;
  10338. SignedUpperLimit := $7FFFFFFF;
  10339. SignedUpperLimitBottom := -2147483648;
  10340. end;
  10341. end;
  10342. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10343. begin
  10344. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10345. LowerLimit := $FFFF;
  10346. SignedLowerLimit := $7FFF;
  10347. SignedLowerLimitBottom := -32768;
  10348. UpperLimit := $FFFFFFFF;
  10349. SignedUpperLimit := $7FFFFFFF;
  10350. SignedUpperLimitBottom := -2147483648;
  10351. MinSize := S_W;
  10352. MaxSize := S_L;
  10353. end;
  10354. {$ifdef x86_64}
  10355. S_LQ:
  10356. begin
  10357. { Both the lower and upper limits are set to 32-bit. If a limit
  10358. is breached, then optimisation is impossible }
  10359. LowerLimit := $FFFFFFFF;
  10360. SignedLowerLimit := $7FFFFFFF;
  10361. SignedLowerLimitBottom := -2147483648;
  10362. UpperLimit := $FFFFFFFF;
  10363. SignedUpperLimit := $7FFFFFFF;
  10364. SignedUpperLimitBottom := -2147483648;
  10365. MinSize := S_L;
  10366. MaxSize := S_L;
  10367. end;
  10368. {$endif x86_64}
  10369. else
  10370. InternalError(2020112301);
  10371. end;
  10372. TestValMin := 0;
  10373. TestValMax := LowerLimit;
  10374. TestValSignedMax := SignedLowerLimit;
  10375. TryShiftDownLimit := LowerLimit;
  10376. TryShiftDown := S_NO;
  10377. ShiftDownOverflow := False;
  10378. RegChanged := False;
  10379. BitwiseOnly := True;
  10380. OrXorUsed := False;
  10381. UpperSignedOverflow := False;
  10382. LowerSignedOverflow := False;
  10383. UpperUnsignedOverflow := False;
  10384. LowerUnsignedOverflow := False;
  10385. hp1 := p;
  10386. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10387. (hp1.typ = ait_instruction) and
  10388. (
  10389. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10390. instruction that doesn't actually contain ThisReg }
  10391. (cs_opt_level3 in current_settings.optimizerswitches) or
  10392. { This allows this Movx optimisation to work through the SETcc instructions
  10393. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10394. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10395. skip over these SETcc instructions). }
  10396. (taicpu(hp1).opcode = A_SETcc) or
  10397. RegInInstruction(ThisReg, hp1)
  10398. ) do
  10399. begin
  10400. case taicpu(hp1).opcode of
  10401. A_INC,A_DEC:
  10402. begin
  10403. { Has to be an exact match on the register }
  10404. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10405. Break;
  10406. if taicpu(hp1).opcode = A_INC then
  10407. begin
  10408. Inc(TestValMin);
  10409. Inc(TestValMax);
  10410. Inc(TestValSignedMax);
  10411. end
  10412. else
  10413. begin
  10414. Dec(TestValMin);
  10415. Dec(TestValMax);
  10416. Dec(TestValSignedMax);
  10417. end;
  10418. end;
  10419. A_TEST, A_CMP:
  10420. begin
  10421. if (
  10422. { Too high a risk of non-linear behaviour that breaks DFA
  10423. here, unless it's cmp $0,%reg, which is equivalent to
  10424. test %reg,%reg }
  10425. OrXorUsed and
  10426. (taicpu(hp1).opcode = A_CMP) and
  10427. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10428. ) or
  10429. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10430. { Has to be an exact match on the register }
  10431. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10432. (
  10433. { Permit "test %reg,%reg" }
  10434. (taicpu(hp1).opcode = A_TEST) and
  10435. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10436. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10437. ) or
  10438. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10439. { Make sure the comparison value is not smaller than the
  10440. smallest allowed signed value for the minimum size (e.g.
  10441. -128 for 8-bit) }
  10442. not (
  10443. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10444. { Is it in the negative range? }
  10445. (
  10446. (taicpu(hp1).oper[0]^.val < 0) and
  10447. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10448. )
  10449. ) then
  10450. Break;
  10451. { Check to see if the active register is used afterwards }
  10452. TransferUsedRegs(TmpUsedRegs);
  10453. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10454. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10455. begin
  10456. { Make sure the comparison or any previous instructions
  10457. hasn't pushed the test values outside of the range of
  10458. MinSize }
  10459. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10460. begin
  10461. { Exceeded lower bound but not upper bound }
  10462. Exit;
  10463. end
  10464. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10465. begin
  10466. { Size didn't exceed lower bound }
  10467. TargetSize := MinSize;
  10468. end
  10469. else
  10470. Break;
  10471. case TargetSize of
  10472. S_B:
  10473. TargetSubReg := R_SUBL;
  10474. S_W:
  10475. TargetSubReg := R_SUBW;
  10476. S_L:
  10477. TargetSubReg := R_SUBD;
  10478. else
  10479. InternalError(2021051002);
  10480. end;
  10481. if TargetSize <> MaxSize then
  10482. begin
  10483. { Update the register to its new size }
  10484. setsubreg(ThisReg, TargetSubReg);
  10485. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10486. taicpu(hp1).oper[1]^.reg := ThisReg;
  10487. taicpu(hp1).opsize := TargetSize;
  10488. { Convert the input MOVZX to a MOV if necessary }
  10489. AdjustInitialLoadAndSize;
  10490. if (InstrMax >= 0) then
  10491. begin
  10492. for Index := 0 to InstrMax do
  10493. begin
  10494. { If p_removed is true, then the original MOV/Z was removed
  10495. and removing the AND instruction may not be safe if it
  10496. appears first }
  10497. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10498. InternalError(2020112311);
  10499. if InstrList[Index].oper[0]^.typ = top_reg then
  10500. InstrList[Index].oper[0]^.reg := ThisReg;
  10501. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10502. InstrList[Index].opsize := MinSize;
  10503. end;
  10504. end;
  10505. Result := True;
  10506. end;
  10507. Exit;
  10508. end;
  10509. end;
  10510. A_SETcc:
  10511. begin
  10512. { This allows this Movx optimisation to work through the SETcc instructions
  10513. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10514. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10515. skip over these SETcc instructions). }
  10516. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10517. { Of course, break out if the current register is used }
  10518. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10519. Break
  10520. else
  10521. { We must use Continue so the instruction doesn't get added
  10522. to InstrList }
  10523. Continue;
  10524. end;
  10525. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10526. begin
  10527. if
  10528. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10529. { Has to be an exact match on the register }
  10530. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10531. (
  10532. (
  10533. (taicpu(hp1).oper[0]^.typ = top_const) and
  10534. (
  10535. (
  10536. (taicpu(hp1).opcode = A_SHL) and
  10537. (
  10538. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10539. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10540. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10541. )
  10542. ) or (
  10543. (taicpu(hp1).opcode <> A_SHL) and
  10544. (
  10545. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10546. { Is it in the negative range? }
  10547. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10548. )
  10549. )
  10550. )
  10551. ) or (
  10552. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10553. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10554. )
  10555. ) then
  10556. Break;
  10557. { Only process OR and XOR if there are only bitwise operations,
  10558. since otherwise they can too easily fool the data flow
  10559. analysis (they can cause non-linear behaviour) }
  10560. case taicpu(hp1).opcode of
  10561. A_ADD:
  10562. begin
  10563. if OrXorUsed then
  10564. { Too high a risk of non-linear behaviour that breaks DFA here }
  10565. Break
  10566. else
  10567. BitwiseOnly := False;
  10568. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10569. begin
  10570. TestValMin := TestValMin * 2;
  10571. TestValMax := TestValMax * 2;
  10572. TestValSignedMax := TestValSignedMax * 2;
  10573. end
  10574. else
  10575. begin
  10576. WorkingValue := taicpu(hp1).oper[0]^.val;
  10577. TestValMin := TestValMin + WorkingValue;
  10578. TestValMax := TestValMax + WorkingValue;
  10579. TestValSignedMax := TestValSignedMax + WorkingValue;
  10580. end;
  10581. end;
  10582. A_SUB:
  10583. begin
  10584. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10585. begin
  10586. TestValMin := 0;
  10587. TestValMax := 0;
  10588. TestValSignedMax := 0;
  10589. end
  10590. else
  10591. begin
  10592. if OrXorUsed then
  10593. { Too high a risk of non-linear behaviour that breaks DFA here }
  10594. Break
  10595. else
  10596. BitwiseOnly := False;
  10597. WorkingValue := taicpu(hp1).oper[0]^.val;
  10598. TestValMin := TestValMin - WorkingValue;
  10599. TestValMax := TestValMax - WorkingValue;
  10600. TestValSignedMax := TestValSignedMax - WorkingValue;
  10601. end;
  10602. end;
  10603. A_AND:
  10604. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10605. begin
  10606. { we might be able to go smaller if AND appears first }
  10607. if InstrMax = -1 then
  10608. case MinSize of
  10609. S_B:
  10610. ;
  10611. S_W:
  10612. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10613. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10614. begin
  10615. TryShiftDown := S_B;
  10616. TryShiftDownLimit := $FF;
  10617. end;
  10618. S_L:
  10619. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10620. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10621. begin
  10622. TryShiftDown := S_B;
  10623. TryShiftDownLimit := $FF;
  10624. end
  10625. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10626. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10627. begin
  10628. TryShiftDown := S_W;
  10629. TryShiftDownLimit := $FFFF;
  10630. end;
  10631. else
  10632. InternalError(2020112320);
  10633. end;
  10634. WorkingValue := taicpu(hp1).oper[0]^.val;
  10635. TestValMin := TestValMin and WorkingValue;
  10636. TestValMax := TestValMax and WorkingValue;
  10637. TestValSignedMax := TestValSignedMax and WorkingValue;
  10638. end;
  10639. A_OR:
  10640. begin
  10641. if not BitwiseOnly then
  10642. Break;
  10643. OrXorUsed := True;
  10644. WorkingValue := taicpu(hp1).oper[0]^.val;
  10645. TestValMin := TestValMin or WorkingValue;
  10646. TestValMax := TestValMax or WorkingValue;
  10647. TestValSignedMax := TestValSignedMax or WorkingValue;
  10648. end;
  10649. A_XOR:
  10650. begin
  10651. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10652. begin
  10653. TestValMin := 0;
  10654. TestValMax := 0;
  10655. TestValSignedMax := 0;
  10656. end
  10657. else
  10658. begin
  10659. if not BitwiseOnly then
  10660. Break;
  10661. OrXorUsed := True;
  10662. WorkingValue := taicpu(hp1).oper[0]^.val;
  10663. TestValMin := TestValMin xor WorkingValue;
  10664. TestValMax := TestValMax xor WorkingValue;
  10665. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10666. end;
  10667. end;
  10668. A_SHL:
  10669. begin
  10670. BitwiseOnly := False;
  10671. WorkingValue := taicpu(hp1).oper[0]^.val;
  10672. TestValMin := TestValMin shl WorkingValue;
  10673. TestValMax := TestValMax shl WorkingValue;
  10674. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10675. end;
  10676. A_SHR,
  10677. { The first instruction was MOVZX, so the value won't be negative }
  10678. A_SAR:
  10679. begin
  10680. if InstrMax <> -1 then
  10681. BitwiseOnly := False
  10682. else
  10683. { we might be able to go smaller if SHR appears first }
  10684. case MinSize of
  10685. S_B:
  10686. ;
  10687. S_W:
  10688. if (taicpu(hp1).oper[0]^.val >= 8) then
  10689. begin
  10690. TryShiftDown := S_B;
  10691. TryShiftDownLimit := $FF;
  10692. TryShiftDownSignedLimit := $7F;
  10693. TryShiftDownSignedLimitLower := -128;
  10694. end;
  10695. S_L:
  10696. if (taicpu(hp1).oper[0]^.val >= 24) then
  10697. begin
  10698. TryShiftDown := S_B;
  10699. TryShiftDownLimit := $FF;
  10700. TryShiftDownSignedLimit := $7F;
  10701. TryShiftDownSignedLimitLower := -128;
  10702. end
  10703. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10704. begin
  10705. TryShiftDown := S_W;
  10706. TryShiftDownLimit := $FFFF;
  10707. TryShiftDownSignedLimit := $7FFF;
  10708. TryShiftDownSignedLimitLower := -32768;
  10709. end;
  10710. else
  10711. InternalError(2020112321);
  10712. end;
  10713. WorkingValue := taicpu(hp1).oper[0]^.val;
  10714. if taicpu(hp1).opcode = A_SAR then
  10715. begin
  10716. TestValMin := SarInt64(TestValMin, WorkingValue);
  10717. TestValMax := SarInt64(TestValMax, WorkingValue);
  10718. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10719. end
  10720. else
  10721. begin
  10722. TestValMin := TestValMin shr WorkingValue;
  10723. TestValMax := TestValMax shr WorkingValue;
  10724. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10725. end;
  10726. end;
  10727. else
  10728. InternalError(2020112303);
  10729. end;
  10730. end;
  10731. (*
  10732. A_IMUL:
  10733. case taicpu(hp1).ops of
  10734. 2:
  10735. begin
  10736. if not MatchOpType(hp1, top_reg, top_reg) or
  10737. { Has to be an exact match on the register }
  10738. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10739. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10740. Break;
  10741. TestValMin := TestValMin * TestValMin;
  10742. TestValMax := TestValMax * TestValMax;
  10743. TestValSignedMax := TestValSignedMax * TestValMax;
  10744. end;
  10745. 3:
  10746. begin
  10747. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10748. { Has to be an exact match on the register }
  10749. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10750. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10751. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10752. { Is it in the negative range? }
  10753. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10754. Break;
  10755. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10756. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10757. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10758. end;
  10759. else
  10760. Break;
  10761. end;
  10762. A_IDIV:
  10763. case taicpu(hp1).ops of
  10764. 3:
  10765. begin
  10766. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10767. { Has to be an exact match on the register }
  10768. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10769. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10770. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10771. { Is it in the negative range? }
  10772. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10773. Break;
  10774. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10775. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10776. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10777. end;
  10778. else
  10779. Break;
  10780. end;
  10781. *)
  10782. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10783. begin
  10784. { If there are no instructions in between, then we might be able to make a saving }
  10785. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10786. Break;
  10787. { We have something like:
  10788. movzbw %dl,%dx
  10789. ...
  10790. movswl %dx,%edx
  10791. Change the latter to a zero-extension then enter the
  10792. A_MOVZX case branch.
  10793. }
  10794. {$ifdef x86_64}
  10795. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10796. begin
  10797. { this becomes a zero extension from 32-bit to 64-bit, but
  10798. the upper 32 bits are already zero, so just delete the
  10799. instruction }
  10800. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10801. RemoveInstruction(hp1);
  10802. Result := True;
  10803. Exit;
  10804. end
  10805. else
  10806. {$endif x86_64}
  10807. begin
  10808. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10809. taicpu(hp1).opcode := A_MOVZX;
  10810. {$ifdef x86_64}
  10811. case taicpu(hp1).opsize of
  10812. S_BQ:
  10813. begin
  10814. taicpu(hp1).opsize := S_BL;
  10815. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10816. end;
  10817. S_WQ:
  10818. begin
  10819. taicpu(hp1).opsize := S_WL;
  10820. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10821. end;
  10822. S_LQ:
  10823. begin
  10824. taicpu(hp1).opcode := A_MOV;
  10825. taicpu(hp1).opsize := S_L;
  10826. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10827. { In this instance, we need to break out because the
  10828. instruction is no longer MOVZX or MOVSXD }
  10829. Result := True;
  10830. Exit;
  10831. end;
  10832. else
  10833. ;
  10834. end;
  10835. {$endif x86_64}
  10836. Result := CompressInstructions;
  10837. Exit;
  10838. end;
  10839. end;
  10840. A_MOVZX:
  10841. begin
  10842. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10843. Break;
  10844. if (InstrMax = -1) then
  10845. begin
  10846. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10847. begin
  10848. { Optimise around i40003 }
  10849. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10850. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10851. {$ifndef x86_64}
  10852. and (
  10853. (taicpu(p).oper[0]^.typ <> top_reg) or
  10854. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10855. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10856. )
  10857. {$endif not x86_64}
  10858. then
  10859. begin
  10860. if (taicpu(p).oper[0]^.typ = top_reg) then
  10861. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10862. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10863. taicpu(p).opsize := S_BL;
  10864. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10865. RemoveInstruction(hp1);
  10866. Result := True;
  10867. Exit;
  10868. end;
  10869. end
  10870. else
  10871. begin
  10872. { Will return false if the second parameter isn't ThisReg
  10873. (can happen on -O2 and under) }
  10874. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10875. begin
  10876. { The two MOVZX instructions are adjacent, so remove the first one }
  10877. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10878. RemoveCurrentP(p);
  10879. Result := True;
  10880. Exit;
  10881. end;
  10882. Break;
  10883. end;
  10884. end;
  10885. Result := CompressInstructions;
  10886. Exit;
  10887. end;
  10888. else
  10889. { This includes ADC, SBB and IDIV }
  10890. Break;
  10891. end;
  10892. if not CheckOverflowConditions then
  10893. Break;
  10894. { Contains highest index (so instruction count - 1) }
  10895. Inc(InstrMax);
  10896. if InstrMax > High(InstrList) then
  10897. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10898. InstrList[InstrMax] := taicpu(hp1);
  10899. end;
  10900. end;
  10901. {$pop}
  10902. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10903. var
  10904. hp1 : tai;
  10905. begin
  10906. Result:=false;
  10907. if (taicpu(p).ops >= 2) and
  10908. ((taicpu(p).oper[0]^.typ = top_const) or
  10909. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10910. (taicpu(p).oper[1]^.typ = top_reg) and
  10911. ((taicpu(p).ops = 2) or
  10912. ((taicpu(p).oper[2]^.typ = top_reg) and
  10913. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10914. GetLastInstruction(p,hp1) and
  10915. MatchInstruction(hp1,A_MOV,[]) and
  10916. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10917. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10918. begin
  10919. TransferUsedRegs(TmpUsedRegs);
  10920. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10921. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10922. { change
  10923. mov reg1,reg2
  10924. imul y,reg2 to imul y,reg1,reg2 }
  10925. begin
  10926. taicpu(p).ops := 3;
  10927. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10928. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10929. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10930. RemoveInstruction(hp1);
  10931. result:=true;
  10932. end;
  10933. end;
  10934. end;
  10935. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10936. var
  10937. ThisLabel: TAsmLabel;
  10938. begin
  10939. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10940. ThisLabel.decrefs;
  10941. taicpu(p).condition := C_None;
  10942. taicpu(p).opcode := A_RET;
  10943. taicpu(p).is_jmp := false;
  10944. taicpu(p).ops := taicpu(ret_p).ops;
  10945. case taicpu(ret_p).ops of
  10946. 0:
  10947. taicpu(p).clearop(0);
  10948. 1:
  10949. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10950. else
  10951. internalerror(2016041301);
  10952. end;
  10953. { If the original label is now dead, it might turn out that the label
  10954. immediately follows p. As a result, everything beyond it, which will
  10955. be just some final register configuration and a RET instruction, is
  10956. now dead code. [Kit] }
  10957. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10958. running RemoveDeadCodeAfterJump for each RET instruction, because
  10959. this optimisation rarely happens and most RETs appear at the end of
  10960. routines where there is nothing that can be stripped. [Kit] }
  10961. if not ThisLabel.is_used then
  10962. RemoveDeadCodeAfterJump(p);
  10963. end;
  10964. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10965. var
  10966. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10967. Unconditional, PotentialModified: Boolean;
  10968. OperPtr: POper;
  10969. NewRef: TReference;
  10970. InstrList: array of taicpu;
  10971. InstrMax, Index: Integer;
  10972. const
  10973. {$ifdef DEBUG_AOPTCPU}
  10974. SNoFlags: shortstring = ' so the flags aren''t modified';
  10975. {$else DEBUG_AOPTCPU}
  10976. SNoFlags = '';
  10977. {$endif DEBUG_AOPTCPU}
  10978. begin
  10979. Result:=false;
  10980. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10981. begin
  10982. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10983. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10984. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10985. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10986. GetNextInstruction(hp1, hp2) and
  10987. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10988. { Change from: To:
  10989. set(C) %reg j(~C) label
  10990. test %reg,%reg/cmp $0,%reg
  10991. je label
  10992. set(C) %reg j(C) label
  10993. test %reg,%reg/cmp $0,%reg
  10994. jne label
  10995. (Also do something similar with sete/setne instead of je/jne)
  10996. }
  10997. begin
  10998. { Before we do anything else, we need to check the instructions
  10999. in between SETcc and TEST to make sure they don't modify the
  11000. FLAGS register - if -O2 or under, there won't be any
  11001. instructions between SET and TEST }
  11002. TransferUsedRegs(TmpUsedRegs);
  11003. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11004. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11005. begin
  11006. next := p;
  11007. SetLength(InstrList, 0);
  11008. InstrMax := -1;
  11009. PotentialModified := False;
  11010. { Make a note of every instruction that modifies the FLAGS
  11011. register }
  11012. while GetNextInstruction(next, next) and (next <> hp1) do
  11013. begin
  11014. if next.typ <> ait_instruction then
  11015. { GetNextInstructionUsingReg should have returned False }
  11016. InternalError(2021051701);
  11017. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11018. begin
  11019. case taicpu(next).opcode of
  11020. A_SETcc,
  11021. A_CMOVcc,
  11022. A_Jcc:
  11023. begin
  11024. if PotentialModified then
  11025. { Not safe because the flags were modified earlier }
  11026. Exit
  11027. else
  11028. { Condition is the same as the initial SETcc, so this is safe
  11029. (don't add to instruction list though) }
  11030. Continue;
  11031. end;
  11032. A_ADD:
  11033. begin
  11034. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11035. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11036. (taicpu(next).oper[1]^.typ <> top_reg) or
  11037. { Must write to a register }
  11038. (taicpu(next).oper[0]^.typ = top_ref) then
  11039. { Require a constant or a register }
  11040. Exit;
  11041. PotentialModified := True;
  11042. end;
  11043. A_SUB:
  11044. begin
  11045. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11046. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11047. (taicpu(next).oper[1]^.typ <> top_reg) or
  11048. { Must write to a register }
  11049. (taicpu(next).oper[0]^.typ <> top_const) or
  11050. (taicpu(next).oper[0]^.val = $80000000) then
  11051. { Can't subtract a register with LEA - also
  11052. check that the value isn't -2^31, as this
  11053. can't be negated }
  11054. Exit;
  11055. PotentialModified := True;
  11056. end;
  11057. A_SAL,
  11058. A_SHL:
  11059. begin
  11060. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11061. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11062. (taicpu(next).oper[1]^.typ <> top_reg) or
  11063. { Must write to a register }
  11064. (taicpu(next).oper[0]^.typ <> top_const) or
  11065. (taicpu(next).oper[0]^.val < 0) or
  11066. (taicpu(next).oper[0]^.val > 3) then
  11067. Exit;
  11068. PotentialModified := True;
  11069. end;
  11070. A_IMUL:
  11071. begin
  11072. if (taicpu(next).ops <> 3) or
  11073. (taicpu(next).oper[1]^.typ <> top_reg) or
  11074. { Must write to a register }
  11075. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11076. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11077. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11078. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11079. Exit
  11080. else
  11081. PotentialModified := True;
  11082. end;
  11083. else
  11084. { Don't know how to change this, so abort }
  11085. Exit;
  11086. end;
  11087. { Contains highest index (so instruction count - 1) }
  11088. Inc(InstrMax);
  11089. if InstrMax > High(InstrList) then
  11090. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11091. InstrList[InstrMax] := taicpu(next);
  11092. end;
  11093. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11094. end;
  11095. if not Assigned(next) or (next <> hp1) then
  11096. { It should be equal to hp1 }
  11097. InternalError(2021051702);
  11098. { Cycle through each instruction and check to see if we can
  11099. change them to versions that don't modify the flags }
  11100. if (InstrMax >= 0) then
  11101. begin
  11102. for Index := 0 to InstrMax do
  11103. case InstrList[Index].opcode of
  11104. A_ADD:
  11105. begin
  11106. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11107. InstrList[Index].opcode := A_LEA;
  11108. reference_reset(NewRef, 1, []);
  11109. NewRef.base := InstrList[Index].oper[1]^.reg;
  11110. if InstrList[Index].oper[0]^.typ = top_reg then
  11111. begin
  11112. NewRef.index := InstrList[Index].oper[0]^.reg;
  11113. NewRef.scalefactor := 1;
  11114. end
  11115. else
  11116. NewRef.offset := InstrList[Index].oper[0]^.val;
  11117. InstrList[Index].loadref(0, NewRef);
  11118. end;
  11119. A_SUB:
  11120. begin
  11121. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11122. InstrList[Index].opcode := A_LEA;
  11123. reference_reset(NewRef, 1, []);
  11124. NewRef.base := InstrList[Index].oper[1]^.reg;
  11125. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11126. InstrList[Index].loadref(0, NewRef);
  11127. end;
  11128. A_SHL,
  11129. A_SAL:
  11130. begin
  11131. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11132. InstrList[Index].opcode := A_LEA;
  11133. reference_reset(NewRef, 1, []);
  11134. NewRef.index := InstrList[Index].oper[1]^.reg;
  11135. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11136. InstrList[Index].loadref(0, NewRef);
  11137. end;
  11138. A_IMUL:
  11139. begin
  11140. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11141. InstrList[Index].opcode := A_LEA;
  11142. reference_reset(NewRef, 1, []);
  11143. NewRef.index := InstrList[Index].oper[1]^.reg;
  11144. case InstrList[Index].oper[0]^.val of
  11145. 2, 4, 8:
  11146. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11147. else {3, 5 and 9}
  11148. begin
  11149. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11150. NewRef.base := InstrList[Index].oper[1]^.reg;
  11151. end;
  11152. end;
  11153. InstrList[Index].loadref(0, NewRef);
  11154. end;
  11155. else
  11156. InternalError(2021051710);
  11157. end;
  11158. end;
  11159. { Mark the FLAGS register as used across this whole block }
  11160. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11161. end;
  11162. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11163. JumpC := taicpu(hp2).condition;
  11164. Unconditional := False;
  11165. if conditions_equal(JumpC, C_E) then
  11166. SetC := inverse_cond(taicpu(p).condition)
  11167. else if conditions_equal(JumpC, C_NE) then
  11168. SetC := taicpu(p).condition
  11169. else
  11170. { We've got something weird here (and inefficent) }
  11171. begin
  11172. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11173. SetC := C_NONE;
  11174. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11175. if condition_in(C_AE, JumpC) then
  11176. Unconditional := True
  11177. else
  11178. { Not sure what to do with this jump - drop out }
  11179. Exit;
  11180. end;
  11181. RemoveInstruction(hp1);
  11182. if Unconditional then
  11183. MakeUnconditional(taicpu(hp2))
  11184. else
  11185. begin
  11186. if SetC = C_NONE then
  11187. InternalError(2018061402);
  11188. taicpu(hp2).SetCondition(SetC);
  11189. end;
  11190. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11191. TmpUsedRegs }
  11192. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11193. begin
  11194. RemoveCurrentp(p, hp2);
  11195. if taicpu(hp2).opcode = A_SETcc then
  11196. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11197. else
  11198. begin
  11199. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11200. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11201. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11202. end;
  11203. end
  11204. else
  11205. if taicpu(hp2).opcode = A_SETcc then
  11206. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11207. else
  11208. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11209. Result := True;
  11210. end
  11211. else if
  11212. { Make sure the instructions are adjacent }
  11213. (
  11214. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11215. GetNextInstruction(p, hp1)
  11216. ) and
  11217. MatchInstruction(hp1, A_MOV, [S_B]) and
  11218. { Writing to memory is allowed }
  11219. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11220. begin
  11221. {
  11222. Watch out for sequences such as:
  11223. set(c)b %regb
  11224. movb %regb,(ref)
  11225. movb $0,1(ref)
  11226. movb $0,2(ref)
  11227. movb $0,3(ref)
  11228. Much more efficient to turn it into:
  11229. movl $0,%regl
  11230. set(c)b %regb
  11231. movl %regl,(ref)
  11232. Or:
  11233. set(c)b %regb
  11234. movzbl %regb,%regl
  11235. movl %regl,(ref)
  11236. }
  11237. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11238. GetNextInstruction(hp1, hp2) and
  11239. MatchInstruction(hp2, A_MOV, [S_B]) and
  11240. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11241. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11242. begin
  11243. { Don't do anything else except set Result to True }
  11244. end
  11245. else
  11246. begin
  11247. if taicpu(p).oper[0]^.typ = top_reg then
  11248. begin
  11249. TransferUsedRegs(TmpUsedRegs);
  11250. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11251. end;
  11252. { If it's not a register, it's a memory address }
  11253. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11254. begin
  11255. { Even if the register is still in use, we can minimise the
  11256. pipeline stall by changing the MOV into another SETcc. }
  11257. taicpu(hp1).opcode := A_SETcc;
  11258. taicpu(hp1).condition := taicpu(p).condition;
  11259. if taicpu(hp1).oper[1]^.typ = top_ref then
  11260. begin
  11261. { Swapping the operand pointers like this is probably a
  11262. bit naughty, but it is far faster than using loadoper
  11263. to transfer the reference from oper[1] to oper[0] if
  11264. you take into account the extra procedure calls and
  11265. the memory allocation and deallocation required }
  11266. OperPtr := taicpu(hp1).oper[1];
  11267. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11268. taicpu(hp1).oper[0] := OperPtr;
  11269. end
  11270. else
  11271. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11272. taicpu(hp1).clearop(1);
  11273. taicpu(hp1).ops := 1;
  11274. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11275. end
  11276. else
  11277. begin
  11278. if taicpu(hp1).oper[1]^.typ = top_reg then
  11279. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11280. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11281. RemoveInstruction(hp1);
  11282. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11283. end
  11284. end;
  11285. Result := True;
  11286. end;
  11287. end;
  11288. end;
  11289. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11290. var
  11291. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11292. TargetReg: TRegister;
  11293. condition, inverted_condition: TAsmCond;
  11294. FoundMOV: Boolean;
  11295. begin
  11296. Result := False;
  11297. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11298. create the most optimial instructions possible due to limited
  11299. register availability, and there are situations where two
  11300. complementary "simple" CMOV blocks are created which, after the fact
  11301. can be merged into a "double" block. For example:
  11302. movw $257,%ax
  11303. movw $2,%r8w
  11304. xorl r9d,%r9d
  11305. testw $16,18(%rcx)
  11306. cmovew %ax,%dx
  11307. cmovew %r8w,%bx
  11308. cmovel %r9d,%r14d
  11309. movw $1283,%ax
  11310. movw $4,%r8w
  11311. movl $9,%r9d
  11312. cmovnew %ax,%dx
  11313. cmovnew %r8w,%bx
  11314. cmovnel %r9d,%r14d
  11315. The CMOVNE instructions at the end can be removed, and the
  11316. destination registers copied into the MOV instructions directly
  11317. above them, before finally being moved to before the first CMOVE
  11318. instructions, to produce:
  11319. movw $257,%ax
  11320. movw $2,%r8w
  11321. xorl r9d,%r9d
  11322. testw $16,18(%rcx)
  11323. movw $1283,%dx
  11324. movw $4,%bx
  11325. movl $9,%r14d
  11326. cmovew %ax,%dx
  11327. cmovew %r8w,%bx
  11328. cmovel %r9d,%r14d
  11329. Which can then be later optimised to:
  11330. movw $257,%ax
  11331. movw $2,%r8w
  11332. xorl r9d,%r9d
  11333. movw $1283,%dx
  11334. movw $4,%bx
  11335. movl $9,%r14d
  11336. testw $16,18(%rcx)
  11337. cmovew %ax,%dx
  11338. cmovew %r8w,%bx
  11339. cmovel %r9d,%r14d
  11340. }
  11341. TargetReg := taicpu(hp1).oper[1]^.reg;
  11342. condition := taicpu(hp1).condition;
  11343. inverted_condition := inverse_cond(condition);
  11344. pFirstMov := nil;
  11345. pLastMov := nil;
  11346. pCMOV := nil;
  11347. if (p.typ = ait_instruction) then
  11348. pCond := p
  11349. else if not GetNextInstruction(p, pCond) then
  11350. InternalError(2024012501);
  11351. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11352. { We should get the CMP or TEST instructeion }
  11353. InternalError(2024012502);
  11354. if (
  11355. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11356. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11357. ) then
  11358. begin
  11359. { We have to tread carefully here, hence why we're not using
  11360. GetNextInstructionUsingReg... we can only accept MOV and other
  11361. CMOV instructions. Anything else and we must drop out}
  11362. hp2 := hp1;
  11363. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11364. begin
  11365. if (hp2.typ <> ait_instruction) then
  11366. Exit;
  11367. case taicpu(hp2).opcode of
  11368. A_MOV:
  11369. begin
  11370. if not Assigned(pFirstMov) then
  11371. pFirstMov := hp2;
  11372. pLastMOV := hp2;
  11373. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11374. { Something different - drop out }
  11375. Exit;
  11376. { Otherwise, leave it for now }
  11377. end;
  11378. A_CMOVcc:
  11379. begin
  11380. if taicpu(hp2).condition = inverted_condition then
  11381. begin
  11382. { We found what we're looking for }
  11383. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11384. begin
  11385. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11386. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11387. begin
  11388. pCMOV := hp2;
  11389. Break;
  11390. end
  11391. else
  11392. { Unsafe reference - drop out }
  11393. Exit;
  11394. end;
  11395. end
  11396. else if taicpu(hp2).condition <> condition then
  11397. { Something weird - drop out }
  11398. Exit;
  11399. end;
  11400. else
  11401. { Invalid }
  11402. Exit;
  11403. end;
  11404. end;
  11405. if not Assigned(pCMOV) then
  11406. { No complementary CMOV found }
  11407. Exit;
  11408. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11409. begin
  11410. { Don't need to do anything special or search for a matching MOV }
  11411. Asml.Remove(pCMOV);
  11412. if RegInInstruction(TargetReg, pCond) then
  11413. { Make sure we don't overwrite the register if it's being used in the condition }
  11414. Asml.InsertAfter(pCMOV, pCond)
  11415. else
  11416. Asml.InsertBefore(pCMOV, pCond);
  11417. taicpu(pCMOV).opcode := A_MOV;
  11418. taicpu(pCMOV).condition := C_None;
  11419. { Don't need to worry about allocating new registers in these cases }
  11420. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11421. Result := True;
  11422. Exit;
  11423. end
  11424. else
  11425. begin
  11426. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11427. FoundMOV := False;
  11428. { Search for the MOV that sets the target register }
  11429. hp2 := pFirstMov;
  11430. repeat
  11431. if (taicpu(hp2).opcode = A_MOV) and
  11432. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11433. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11434. begin
  11435. { Change the destination }
  11436. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11437. if not FoundMOV then
  11438. begin
  11439. FoundMOV := True;
  11440. { Make sure the register is allocated }
  11441. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11442. end;
  11443. hp1 := tai(hp2.Previous);
  11444. Asml.Remove(hp2);
  11445. if RegInInstruction(TargetReg, pCond) then
  11446. { Make sure we don't overwrite the register if it's being used in the condition }
  11447. Asml.InsertAfter(hp2, pCond)
  11448. else
  11449. Asml.InsertBefore(hp2, pCond);
  11450. if (hp2 = pLastMov) then
  11451. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11452. Break;
  11453. hp2 := hp1;
  11454. end;
  11455. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11456. if FoundMOV then
  11457. { Delete the CMOV }
  11458. RemoveInstruction(pCMOV)
  11459. else
  11460. begin
  11461. { If no MOV was found, we have to actually move and transmute the CMOV }
  11462. Asml.Remove(pCMOV);
  11463. if RegInInstruction(TargetReg, pCond) then
  11464. { Make sure we don't overwrite the register if it's being used in the condition }
  11465. Asml.InsertAfter(pCMOV, pCond)
  11466. else
  11467. Asml.InsertBefore(pCMOV, pCond);
  11468. taicpu(pCMOV).opcode := A_MOV;
  11469. taicpu(pCMOV).condition := C_None;
  11470. end;
  11471. Result := True;
  11472. Exit;
  11473. end;
  11474. end;
  11475. end;
  11476. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11477. var
  11478. hp1, hp2, pCond: tai;
  11479. begin
  11480. Result := False;
  11481. { Search ahead for CMOV instructions }
  11482. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11483. begin
  11484. hp1 := p;
  11485. hp2 := p;
  11486. pCond := nil; { To prevent compiler warnings }
  11487. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11488. DEFAULTFLAGS }
  11489. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11490. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11491. pCond := p;
  11492. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11493. begin
  11494. if (hp1.typ <> ait_instruction) then
  11495. { Break out on markers and labels etc. }
  11496. Break;
  11497. case taicpu(hp1).opcode of
  11498. A_MOV:
  11499. { Ignore regular MOVs unless they are obviously not related
  11500. to a CMOV block }
  11501. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11502. Break;
  11503. A_CMOVcc:
  11504. if TryCmpCMovOpts(pCond, hp1) then
  11505. begin
  11506. hp1 := hp2;
  11507. { p itself isn't changed, and we're still inside a
  11508. while loop to catch subsequent CMOVs, so just flag
  11509. a new iteration }
  11510. Include(OptsToCheck, aoc_ForceNewIteration);
  11511. Continue;
  11512. end;
  11513. else
  11514. { Drop out if we find anything else }
  11515. Break;
  11516. end;
  11517. hp2 := hp1;
  11518. end;
  11519. end;
  11520. end;
  11521. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11522. var
  11523. hp1, hp2, pCond: tai;
  11524. SourceReg, TargetReg: TRegister;
  11525. begin
  11526. Result := False;
  11527. { In some situations, we end up with an inefficient arrangement of
  11528. instructions in the form of:
  11529. or %reg1,%reg2
  11530. (%reg1 deallocated)
  11531. test %reg2,%reg2
  11532. mov x,%reg2
  11533. we may be able to swap and rearrange the registers to produce:
  11534. or %reg2,%reg1
  11535. mov x,%reg2
  11536. test %reg1,%reg1
  11537. (%reg1 deallocated)
  11538. }
  11539. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11540. (taicpu(p).oper[1]^.typ = top_reg) and
  11541. (
  11542. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11543. MatchOperand(taicpu(p).oper[0]^, -1)
  11544. ) and
  11545. GetNextInstruction(p, hp1) and
  11546. MatchInstruction(hp1, A_MOV, []) and
  11547. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11548. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11549. begin
  11550. TargetReg := taicpu(p).oper[1]^.reg;
  11551. { Now look backwards to find a simple commutative operation: ADD,
  11552. IMUL (2-register version), OR, AND or XOR - whose destination
  11553. register is the same as TEST }
  11554. hp2 := p;
  11555. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11556. if RegInInstruction(TargetReg, hp2) then
  11557. begin
  11558. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11559. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11560. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11561. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11562. begin
  11563. SourceReg := taicpu(hp2).oper[0]^.reg;
  11564. if
  11565. { Make sure the MOV doesn't use the other register }
  11566. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11567. { And make sure the source register is not used afterwards }
  11568. not RegInUsedRegs(SourceReg, UsedRegs) then
  11569. begin
  11570. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11571. taicpu(hp2).oper[0]^.reg := TargetReg;
  11572. taicpu(hp2).oper[1]^.reg := SourceReg;
  11573. if taicpu(p).oper[0]^.typ = top_reg then
  11574. taicpu(p).oper[0]^.reg := SourceReg;
  11575. taicpu(p).oper[1]^.reg := SourceReg;
  11576. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11577. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11578. Include(OptsToCheck, aoc_ForceNewIteration);
  11579. { We can still check the following optimisations since
  11580. the instruction is still a TEST }
  11581. end;
  11582. end;
  11583. Break;
  11584. end;
  11585. end;
  11586. { Search ahead3 for CMOV instructions }
  11587. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11588. begin
  11589. hp1 := p;
  11590. hp2 := p;
  11591. pCond := nil; { To prevent compiler warnings }
  11592. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11593. DEFAULTFLAGS }
  11594. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11595. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11596. pCond := p;
  11597. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11598. begin
  11599. if (hp1.typ <> ait_instruction) then
  11600. { Break out on markers and labels etc. }
  11601. Break;
  11602. case taicpu(hp1).opcode of
  11603. A_MOV:
  11604. { Ignore regular MOVs unless they are obviously not related
  11605. to a CMOV block }
  11606. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11607. Break;
  11608. A_CMOVcc:
  11609. if TryCmpCMovOpts(pCond, hp1) then
  11610. begin
  11611. hp1 := hp2;
  11612. { p itself isn't changed, and we're still inside a
  11613. while loop to catch subsequent CMOVs, so just flag
  11614. a new iteration }
  11615. Include(OptsToCheck, aoc_ForceNewIteration);
  11616. Continue;
  11617. end;
  11618. else
  11619. { Drop out if we find anything else }
  11620. Break;
  11621. end;
  11622. hp2 := hp1;
  11623. end;
  11624. end;
  11625. end;
  11626. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11627. var
  11628. hp1: tai;
  11629. Count: Integer;
  11630. OrigLabel: TAsmLabel;
  11631. begin
  11632. result := False;
  11633. { Sometimes, the optimisations below can permit this }
  11634. RemoveDeadCodeAfterJump(p);
  11635. 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
  11636. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11637. begin
  11638. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11639. { Also a side-effect of optimisations }
  11640. if CollapseZeroDistJump(p, OrigLabel) then
  11641. begin
  11642. Result := True;
  11643. Exit;
  11644. end;
  11645. hp1 := GetLabelWithSym(OrigLabel);
  11646. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11647. begin
  11648. if taicpu(hp1).opcode = A_RET then
  11649. begin
  11650. {
  11651. change
  11652. jmp .L1
  11653. ...
  11654. .L1:
  11655. ret
  11656. into
  11657. ret
  11658. }
  11659. begin
  11660. ConvertJumpToRET(p, hp1);
  11661. result:=true;
  11662. end;
  11663. end
  11664. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11665. not (cs_opt_size in current_settings.optimizerswitches) and
  11666. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11667. begin
  11668. Result := True;
  11669. Exit;
  11670. end;
  11671. end;
  11672. end;
  11673. end;
  11674. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11675. begin
  11676. Result := assigned(p) and
  11677. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11678. (taicpu(p).oper[1]^.typ = top_reg) and
  11679. (
  11680. (taicpu(p).oper[0]^.typ = top_reg) or
  11681. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11682. it is not expected that this can cause a seg. violation }
  11683. (
  11684. (taicpu(p).oper[0]^.typ = top_ref) and
  11685. { TODO: Can we detect which references become constants at this
  11686. stage so we don't have to do a blanket ban? }
  11687. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11688. (
  11689. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11690. (
  11691. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11692. not RefModified and
  11693. { If the reference also appears in the condition, then we know it's safe, otherwise
  11694. any kind of access violation would have occurred already }
  11695. Assigned(cond_p) and
  11696. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11697. (cond_p.typ = ait_instruction) and
  11698. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11699. { Just consider 2-operand comparison instructions for now to be safe }
  11700. (taicpu(cond_p).ops = 2) and
  11701. (
  11702. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11703. (
  11704. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11705. { Don't risk identical registers but different offsets, as we may have constructs
  11706. such as buffer streams with things like length fields that indicate whether
  11707. any more data follows. And there are probably some contrived examples where
  11708. writing to offsets behind the one being read also lead to access violations }
  11709. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11710. (
  11711. { Check that we're not modifying a register that appears in the reference }
  11712. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11713. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11714. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11715. )
  11716. )
  11717. )
  11718. )
  11719. )
  11720. )
  11721. );
  11722. end;
  11723. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11724. begin
  11725. { Update integer registers, ignoring deallocations }
  11726. repeat
  11727. while assigned(p) and
  11728. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11729. (p.typ = ait_label) or
  11730. ((p.typ = ait_marker) and
  11731. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11732. p := tai(p.next);
  11733. while assigned(p) and
  11734. (p.typ=ait_RegAlloc) Do
  11735. begin
  11736. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11737. begin
  11738. case tai_regalloc(p).ratype of
  11739. ra_alloc :
  11740. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11741. else
  11742. ;
  11743. end;
  11744. end;
  11745. p := tai(p.next);
  11746. end;
  11747. until not(assigned(p)) or
  11748. (not(p.typ in SkipInstr) and
  11749. not((p.typ = ait_label) and
  11750. labelCanBeSkipped(tai_label(p))));
  11751. end;
  11752. {$ifndef 8086}
  11753. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11754. begin
  11755. Result := False;
  11756. EndJump := nil;
  11757. BlockStop := nil;
  11758. while (BlockStart <> fOptimizer.BlockEnd) and
  11759. { stop on labels }
  11760. (BlockStart.typ <> ait_label) do
  11761. begin
  11762. { Keep track of all integer registers that are used }
  11763. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11764. if BlockStart.typ = ait_instruction then
  11765. begin
  11766. if (taicpu(BlockStart).opcode = A_JMP) then
  11767. begin
  11768. if not IsJumpToLabel(taicpu(BlockStart)) or
  11769. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11770. Exit;
  11771. EndJump := BlockStart;
  11772. Break;
  11773. end
  11774. { Check to see if we have a valid MOV instruction instead }
  11775. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11776. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11777. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11778. begin
  11779. Exit;
  11780. end
  11781. else
  11782. { This will be a valid MOV }
  11783. fAllocationRange := BlockStart;
  11784. end;
  11785. OneBeforeBlock := BlockStart;
  11786. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11787. end;
  11788. if (BlockStart = fOptimizer.BlockEnd) then
  11789. Exit;
  11790. BlockStop := BlockStart;
  11791. Result := True;
  11792. end;
  11793. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11794. var
  11795. hp1: tai;
  11796. RefModified: Boolean;
  11797. begin
  11798. Result := 0;
  11799. hp1 := BlockStart;
  11800. RefModified := False; { As long as the condition is inverted, this can be reset }
  11801. while assigned(hp1) and
  11802. (hp1 <> BlockStop) do
  11803. begin
  11804. case hp1.typ of
  11805. ait_instruction:
  11806. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11807. begin
  11808. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11809. begin
  11810. Inc(Result);
  11811. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11812. Assigned(fCondition) and
  11813. { Will have 2 operands }
  11814. (
  11815. (
  11816. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11817. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11818. ) or
  11819. (
  11820. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11821. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11822. )
  11823. ) then
  11824. { It is no longer safe to use the reference in the condition.
  11825. this prevents problems such as:
  11826. mov (%reg),%reg
  11827. mov (%reg),...
  11828. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11829. (fixes #40165)
  11830. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11831. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11832. }
  11833. RefModified := True;
  11834. end
  11835. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11836. { CMOV with constants grows the code size }
  11837. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11838. begin
  11839. { Register was reserved by TryCMOVConst and
  11840. stored on ConstRegs }
  11841. end
  11842. else
  11843. begin
  11844. Result := -1;
  11845. Exit;
  11846. end;
  11847. end
  11848. else
  11849. begin
  11850. Result := -1;
  11851. Exit;
  11852. end;
  11853. else
  11854. { Most likely an align };
  11855. end;
  11856. fOptimizer.GetNextInstruction(hp1, hp1);
  11857. end;
  11858. end;
  11859. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11860. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11861. (this is done as a separate stage because the double types are extensions of the branching type,
  11862. but we can't discount the conditional jump until the last step) }
  11863. procedure EvaluateBranchingType;
  11864. begin
  11865. Inc(CMOVScore);
  11866. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11867. { Too many instructions to be worthwhile }
  11868. fState := tsInvalid;
  11869. end;
  11870. var
  11871. hp1: tai;
  11872. Count: Integer;
  11873. begin
  11874. { Table of valid CMOV block types
  11875. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11876. ---------- --------- --------- --------- --------- ---------
  11877. tsSimple X Yes X X X
  11878. tsDetour = 1st X X X X
  11879. tsBranching <> Mid Yes X X X
  11880. tsDouble End-label Yes * Yes X Yes
  11881. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11882. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11883. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11884. * Only one reference allowed
  11885. }
  11886. hp1 := nil; { To prevent compiler warnings }
  11887. Optimizer.CopyUsedRegs(RegisterTracking);
  11888. fOptimizer := Optimizer;
  11889. fLabel := AFirstLabel;
  11890. CMOVScore := 0;
  11891. ConstCount := 0;
  11892. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11893. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11894. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11895. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11896. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11897. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11898. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11899. fInsertionPoint := p_initialjump;
  11900. fCondition := nil;
  11901. fInitialJump := p_initialjump;
  11902. fFirstMovBlock := p_initialmov;
  11903. fFirstMovBlockStop := nil;
  11904. fSecondJump := nil;
  11905. fSecondMovBlock := nil;
  11906. fSecondMovBlockStop := nil;
  11907. fMidLabel := nil;
  11908. fSecondJump := nil;
  11909. fSecondMovBlock := nil;
  11910. fEndLabel := nil;
  11911. fAllocationRange := nil;
  11912. { Assume it all goes horribly wrong! }
  11913. fState := tsInvalid;
  11914. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11915. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11916. 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
  11917. begin
  11918. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11919. for Count := 0 to 1 do
  11920. with taicpu(fCondition).oper[Count]^ do
  11921. case typ of
  11922. top_reg:
  11923. if getregtype(reg) = R_INTREGISTER then
  11924. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11925. top_ref:
  11926. begin
  11927. if
  11928. {$ifdef x86_64}
  11929. (ref^.base <> NR_RIP) and
  11930. {$endif x86_64}
  11931. (ref^.base <> NR_NO) then
  11932. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11933. if (ref^.index <> NR_NO) then
  11934. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11935. end
  11936. else
  11937. ;
  11938. end;
  11939. { When inserting instructions before hp_prev, try to insert them
  11940. before the allocation of the FLAGS register }
  11941. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11942. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11943. { If not found, set it equal to the condition so it's something sensible }
  11944. fInsertionPoint := fCondition;
  11945. { When dealing with a comparison against zero, take note of the
  11946. instruction before it to see if we can move instructions further
  11947. back in order to benefit PostPeepholeOptTestOr.
  11948. }
  11949. if (
  11950. (
  11951. (taicpu(fCondition).opcode = A_CMP) and
  11952. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11953. ) or
  11954. (
  11955. (taicpu(fCondition).opcode = A_TEST) and
  11956. (
  11957. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11958. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11959. )
  11960. )
  11961. ) and
  11962. Optimizer.GetLastInstruction(fCondition, hp1) then
  11963. begin
  11964. { These instructions set the zero flag if the result is zero }
  11965. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11966. begin
  11967. fInsertionPoint := hp1;
  11968. { Also mark all the registers in this previous instruction
  11969. as 'in use', even if they've just been deallocated }
  11970. for Count := 0 to 1 do
  11971. with taicpu(hp1).oper[Count]^ do
  11972. case typ of
  11973. top_reg:
  11974. if getregtype(reg) = R_INTREGISTER then
  11975. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11976. top_ref:
  11977. begin
  11978. if
  11979. {$ifdef x86_64}
  11980. (ref^.base <> NR_RIP) and
  11981. {$endif x86_64}
  11982. (ref^.base <> NR_NO) then
  11983. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11984. if (ref^.index <> NR_NO) then
  11985. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11986. end
  11987. else
  11988. ;
  11989. end;
  11990. end;
  11991. end;
  11992. end
  11993. else
  11994. fCondition := nil;
  11995. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11996. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11997. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11998. { If not found, set it equal to p so it's something sensible }
  11999. fInsertionPoint := hp1;
  12000. hp1 := p_initialmov;
  12001. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  12002. Exit;
  12003. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  12004. if (hp1.typ <> ait_label) then { should be on a jump }
  12005. begin
  12006. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  12007. { Need a label afterwards }
  12008. Exit;
  12009. end
  12010. else
  12011. fMidLabel := hp1;
  12012. if tai_label(fMidLabel).labsym <> AFirstLabel then
  12013. { Not the correct label }
  12014. fMidLabel := nil;
  12015. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12016. { If there's neither a 2nd jump nor correct label, then it's invalid
  12017. (see above table) }
  12018. Exit;
  12019. { Analyse the first block of MOVs more closely }
  12020. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12021. if Assigned(fSecondJump) then
  12022. begin
  12023. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12024. begin
  12025. fState := tsDetour
  12026. end
  12027. else
  12028. begin
  12029. { Need the correct mid-label for this one }
  12030. if not Assigned(fMidLabel) then
  12031. Exit;
  12032. fState := tsBranching;
  12033. end;
  12034. end
  12035. else
  12036. { No jump. but mid-label is present }
  12037. fState := tsSimple;
  12038. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12039. begin
  12040. { Invalid or too many instructions to be worthwhile }
  12041. fState := tsInvalid;
  12042. Exit;
  12043. end;
  12044. { check further for
  12045. jCC xxx
  12046. <several movs 1>
  12047. jmp yyy
  12048. xxx:
  12049. <several movs 2>
  12050. yyy:
  12051. etc.
  12052. }
  12053. if (fState = tsBranching) and
  12054. { Estimate for required savings for extra jump }
  12055. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12056. { Only one reference is allowed for double blocks }
  12057. (AFirstLabel.getrefs = 1) then
  12058. begin
  12059. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12060. fSecondMovBlock := hp1;
  12061. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12062. begin
  12063. EvaluateBranchingType;
  12064. Exit;
  12065. end;
  12066. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12067. if (hp1.typ <> ait_label) then { should be on a jump }
  12068. begin
  12069. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12070. begin
  12071. { Need a label afterwards }
  12072. EvaluateBranchingType;
  12073. Exit;
  12074. end;
  12075. end
  12076. else
  12077. fEndLabel := hp1;
  12078. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12079. { Second jump doesn't go to the end }
  12080. fEndLabel := nil;
  12081. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12082. begin
  12083. { If there's neither a 3rd jump nor correct end label, then it's
  12084. not a invalid double block, but is a valid single branching
  12085. block (see above table) }
  12086. EvaluateBranchingType;
  12087. Exit;
  12088. end;
  12089. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12090. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12091. { Invalid or too many instructions to be worthwhile }
  12092. Exit;
  12093. Inc(CMOVScore, Count);
  12094. if Assigned(fThirdJump) then
  12095. begin
  12096. if not Assigned(fSecondJump) then
  12097. fState := tsDoubleSecondBranching
  12098. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12099. fState := tsDoubleBranchSame
  12100. else
  12101. fState := tsDoubleBranchDifferent;
  12102. end
  12103. else
  12104. fState := tsDouble;
  12105. end;
  12106. if fState = tsBranching then
  12107. EvaluateBranchingType;
  12108. end;
  12109. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12110. new register to store the constant }
  12111. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12112. var
  12113. RegSize: TSubRegister;
  12114. CurrentVal: TCGInt;
  12115. ANewReg: TRegister;
  12116. X: ShortInt;
  12117. begin
  12118. Result := False;
  12119. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12120. Exit;
  12121. if ConstCount >= MAX_CMOV_REGISTERS then
  12122. { Arrays are full }
  12123. Exit;
  12124. { Remember that CMOV can't encode 8-bit registers }
  12125. case taicpu(p).opsize of
  12126. S_W:
  12127. RegSize := R_SUBW;
  12128. S_L:
  12129. RegSize := R_SUBD;
  12130. {$ifdef x86_64}
  12131. S_Q:
  12132. RegSize := R_SUBQ;
  12133. {$endif x86_64}
  12134. else
  12135. InternalError(2021100401);
  12136. end;
  12137. { See if the value has already been reserved for another CMOV instruction }
  12138. CurrentVal := taicpu(p).oper[0]^.val;
  12139. for X := 0 to ConstCount - 1 do
  12140. if ConstVals[X] = CurrentVal then
  12141. begin
  12142. ConstRegs[ConstCount] := ConstRegs[X];
  12143. ConstSizes[ConstCount] := RegSize;
  12144. ConstVals[ConstCount] := CurrentVal;
  12145. Inc(ConstCount);
  12146. Inc(Count);
  12147. Result := True;
  12148. Exit;
  12149. end;
  12150. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12151. if ANewReg = NR_NO then
  12152. { No free registers }
  12153. Exit;
  12154. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12155. up vying for the same register }
  12156. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12157. ConstRegs[ConstCount] := ANewReg;
  12158. ConstSizes[ConstCount] := RegSize;
  12159. ConstVals[ConstCount] := CurrentVal;
  12160. Inc(ConstCount);
  12161. Inc(Count);
  12162. Result := True;
  12163. end;
  12164. destructor TCMOVTracking.Done;
  12165. begin
  12166. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12167. end;
  12168. procedure TCMOVTracking.Process(out new_p: tai);
  12169. var
  12170. Count, Writes: LongInt;
  12171. RegMatch: Boolean;
  12172. hp1, hp_new: tai;
  12173. inverted_condition, condition: TAsmCond;
  12174. begin
  12175. if (fState in [tsInvalid, tsProcessed]) then
  12176. InternalError(2023110701);
  12177. { Repurpose RegisterTracking to mark registers that we've defined }
  12178. RegisterTracking[R_INTREGISTER].Clear;
  12179. Count := 0;
  12180. Writes := 0;
  12181. condition := taicpu(fInitialJump).condition;
  12182. inverted_condition := inverse_cond(condition);
  12183. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12184. doesn't get CMOVs in this case }
  12185. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12186. begin
  12187. { Include the jump in the flag tracking }
  12188. if Assigned(fThirdJump) then
  12189. begin
  12190. if (fState = tsDoubleBranchSame) then
  12191. begin
  12192. { Will be an unconditional jump, so track to the instruction before it }
  12193. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12194. InternalError(2023110710);
  12195. end
  12196. else
  12197. hp1 := fThirdJump;
  12198. end
  12199. else
  12200. hp1 := fSecondMovBlockStop;
  12201. end
  12202. else
  12203. begin
  12204. { Include a conditional jump in the flag tracking }
  12205. if Assigned(fSecondJump) then
  12206. begin
  12207. if (fState = tsDetour) then
  12208. begin
  12209. { Will be an unconditional jump, so track to the instruction before it }
  12210. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12211. InternalError(2023110711);
  12212. end
  12213. else
  12214. hp1 := fSecondJump;
  12215. end
  12216. else
  12217. hp1 := fFirstMovBlockStop;
  12218. end;
  12219. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12220. { Process the second set of MOVs first, because if a destination
  12221. register is shared between the first and second MOV sets, it is more
  12222. efficient to turn the first one into a MOV instruction and place it
  12223. before the CMP if possible, but we won't know which registers are
  12224. shared until we've processed at least one list, so we might as well
  12225. make it the second one since that won't be modified again. }
  12226. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12227. begin
  12228. hp1 := fSecondMovBlock;
  12229. repeat
  12230. if not Assigned(hp1) then
  12231. InternalError(2018062902);
  12232. if (hp1.typ = ait_instruction) then
  12233. begin
  12234. { Extra safeguard }
  12235. if (taicpu(hp1).opcode <> A_MOV) then
  12236. InternalError(2018062903);
  12237. { Note: tsDoubleBranchDifferent is essentially identical to
  12238. tsBranching and the 2nd block is best left largely
  12239. untouched, but we need to evaluate which registers the MOVs
  12240. write to in order to track what would be complementary CMOV
  12241. pairs that can be further optimised. [Kit] }
  12242. if fState <> tsDoubleBranchDifferent then
  12243. begin
  12244. if taicpu(hp1).oper[0]^.typ = top_const then
  12245. begin
  12246. RegMatch := False;
  12247. for Count := 0 to ConstCount - 1 do
  12248. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12249. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12250. begin
  12251. RegMatch := True;
  12252. { If it's in RegisterTracking, then this register
  12253. is being used more than once and hence has
  12254. already had its value defined (it gets added to
  12255. UsedRegs through AllocRegBetween below) }
  12256. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12257. begin
  12258. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12259. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12260. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12261. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12262. ConstMovs[Count] := hp_new;
  12263. end
  12264. else
  12265. { We just need an instruction between hp_prev and hp1
  12266. where we know the register is marked as in use }
  12267. hp_new := fSecondMovBlock;
  12268. { Keep track of largest write for this register so it can be optimised later }
  12269. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12270. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12271. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12272. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12273. Break;
  12274. end;
  12275. if not RegMatch then
  12276. InternalError(2021100411);
  12277. end;
  12278. taicpu(hp1).opcode := A_CMOVcc;
  12279. taicpu(hp1).condition := condition;
  12280. end;
  12281. { Store these writes to search for duplicates later on }
  12282. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12283. Inc(Writes);
  12284. end;
  12285. fOptimizer.GetNextInstruction(hp1, hp1);
  12286. until (hp1 = fSecondMovBlockStop);
  12287. end;
  12288. { Now do the first set of MOVs }
  12289. hp1 := fFirstMovBlock;
  12290. repeat
  12291. if not Assigned(hp1) then
  12292. InternalError(2018062904);
  12293. if (hp1.typ = ait_instruction) then
  12294. begin
  12295. RegMatch := False;
  12296. { Extra safeguard }
  12297. if (taicpu(hp1).opcode <> A_MOV) then
  12298. InternalError(2018062905);
  12299. { Search through the RegWrites list to see if there are any
  12300. opposing CMOV pairs that write to the same register }
  12301. for Count := 0 to Writes - 1 do
  12302. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12303. begin
  12304. { We have a match. Keep this as a MOV }
  12305. { Move ahead in preparation }
  12306. fOptimizer.GetNextInstruction(hp1, hp1);
  12307. RegMatch := True;
  12308. Break;
  12309. end;
  12310. if RegMatch then
  12311. Continue;
  12312. if taicpu(hp1).oper[0]^.typ = top_const then
  12313. begin
  12314. for Count := 0 to ConstCount - 1 do
  12315. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12316. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12317. begin
  12318. RegMatch := True;
  12319. { If it's in RegisterTracking, then this register is
  12320. being used more than once and hence has already had
  12321. its value defined (it gets added to UsedRegs through
  12322. AllocRegBetween below) }
  12323. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12324. begin
  12325. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12326. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12327. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12328. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12329. ConstMovs[Count] := hp_new;
  12330. end
  12331. else
  12332. { We just need an instruction between hp_prev and hp1
  12333. where we know the register is marked as in use }
  12334. hp_new := fFirstMovBlock;
  12335. { Keep track of largest write for this register so it can be optimised later }
  12336. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12337. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12338. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12339. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12340. Break;
  12341. end;
  12342. if not RegMatch then
  12343. InternalError(2021100412);
  12344. end;
  12345. taicpu(hp1).opcode := A_CMOVcc;
  12346. taicpu(hp1).condition := inverted_condition;
  12347. if (fState = tsDoubleBranchDifferent) then
  12348. begin
  12349. { Store these writes to search for duplicates later on }
  12350. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12351. Inc(Writes);
  12352. end;
  12353. end;
  12354. fOptimizer.GetNextInstruction(hp1, hp1);
  12355. until (hp1 = fFirstMovBlockStop);
  12356. { Update initialisation MOVs to the smallest possible size }
  12357. for Count := 0 to ConstCount - 1 do
  12358. if Assigned(ConstMovs[Count]) then
  12359. begin
  12360. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12361. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12362. end;
  12363. case fState of
  12364. tsSimple:
  12365. begin
  12366. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12367. { No branch to delete }
  12368. end;
  12369. tsDetour:
  12370. begin
  12371. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12372. { Preserve jump }
  12373. end;
  12374. tsBranching, tsDoubleBranchDifferent:
  12375. begin
  12376. if (fState = tsBranching) then
  12377. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12378. else
  12379. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12380. taicpu(fSecondJump).opcode := A_JCC;
  12381. taicpu(fSecondJump).condition := inverted_condition;
  12382. end;
  12383. tsDouble, tsDoubleBranchSame:
  12384. begin
  12385. if (fState = tsDouble) then
  12386. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12387. else
  12388. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12389. { Delete second jump }
  12390. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12391. fOptimizer.RemoveInstruction(fSecondJump);
  12392. end;
  12393. tsDoubleSecondBranching:
  12394. begin
  12395. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12396. { Delete second jump, preserve third jump as conditional }
  12397. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12398. fOptimizer.RemoveInstruction(fSecondJump);
  12399. taicpu(fThirdJump).opcode := A_JCC;
  12400. taicpu(fThirdJump).condition := condition;
  12401. end;
  12402. else
  12403. InternalError(2023110720);
  12404. end;
  12405. { Now we can safely decrement the reference count }
  12406. tasmlabel(fLabel).decrefs;
  12407. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12408. { Remove the original jump }
  12409. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12410. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12411. fState := tsProcessed;
  12412. end;
  12413. {$endif 8086}
  12414. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12415. var
  12416. hp1,hp2: tai;
  12417. carryadd_opcode : TAsmOp;
  12418. symbol: TAsmSymbol;
  12419. increg, tmpreg: TRegister;
  12420. {$ifndef i8086}
  12421. CMOVTracking: PCMOVTracking;
  12422. hp3,hp4,hp5: tai;
  12423. {$endif i8086}
  12424. TempBool: Boolean;
  12425. begin
  12426. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12427. DoJumpOptimizations(p, TempBool) then
  12428. Exit(True);
  12429. result:=false;
  12430. if GetNextInstruction(p,hp1) then
  12431. begin
  12432. if (hp1.typ=ait_label) then
  12433. begin
  12434. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12435. Exit;
  12436. end
  12437. else if (hp1.typ<>ait_instruction) then
  12438. Exit;
  12439. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12440. if (
  12441. (
  12442. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12443. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12444. (Taicpu(hp1).oper[0]^.val=1)
  12445. ) or
  12446. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12447. ) and
  12448. GetNextInstruction(hp1,hp2) and
  12449. FindLabel(TAsmLabel(symbol), hp2) then
  12450. { jb @@1 cmc
  12451. inc/dec operand --> adc/sbb operand,0
  12452. @@1:
  12453. ... and ...
  12454. jnb @@1
  12455. inc/dec operand --> adc/sbb operand,0
  12456. @@1: }
  12457. begin
  12458. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12459. begin
  12460. case taicpu(hp1).opcode of
  12461. A_INC,
  12462. A_ADD:
  12463. carryadd_opcode:=A_ADC;
  12464. A_DEC,
  12465. A_SUB:
  12466. carryadd_opcode:=A_SBB;
  12467. else
  12468. InternalError(2021011001);
  12469. end;
  12470. Taicpu(p).clearop(0);
  12471. Taicpu(p).ops:=0;
  12472. Taicpu(p).is_jmp:=false;
  12473. Taicpu(p).opcode:=A_CMC;
  12474. Taicpu(p).condition:=C_NONE;
  12475. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12476. Taicpu(hp1).ops:=2;
  12477. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12478. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12479. else
  12480. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12481. Taicpu(hp1).loadconst(0,0);
  12482. Taicpu(hp1).opcode:=carryadd_opcode;
  12483. result:=true;
  12484. exit;
  12485. end
  12486. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12487. begin
  12488. case taicpu(hp1).opcode of
  12489. A_INC,
  12490. A_ADD:
  12491. carryadd_opcode:=A_ADC;
  12492. A_DEC,
  12493. A_SUB:
  12494. carryadd_opcode:=A_SBB;
  12495. else
  12496. InternalError(2021011002);
  12497. end;
  12498. Taicpu(hp1).ops:=2;
  12499. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12500. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12501. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12502. else
  12503. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12504. Taicpu(hp1).loadconst(0,0);
  12505. Taicpu(hp1).opcode:=carryadd_opcode;
  12506. RemoveCurrentP(p, hp1);
  12507. result:=true;
  12508. exit;
  12509. end
  12510. {
  12511. jcc @@1 setcc tmpreg
  12512. inc/dec/add/sub operand -> (movzx tmpreg)
  12513. @@1: add/sub tmpreg,operand
  12514. While this increases code size slightly, it makes the code much faster if the
  12515. jump is unpredictable
  12516. }
  12517. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12518. begin
  12519. { search for an available register which is volatile }
  12520. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12521. if increg <> NR_NO then
  12522. begin
  12523. { We don't need to check if tmpreg is in hp1 or not, because
  12524. it will be marked as in use at p (if not, this is
  12525. indictive of a compiler bug). }
  12526. TAsmLabel(symbol).decrefs;
  12527. Taicpu(p).clearop(0);
  12528. Taicpu(p).ops:=1;
  12529. Taicpu(p).is_jmp:=false;
  12530. Taicpu(p).opcode:=A_SETcc;
  12531. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12532. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12533. Taicpu(p).loadreg(0,increg);
  12534. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12535. begin
  12536. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12537. R_SUBW:
  12538. begin
  12539. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12540. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12541. end;
  12542. R_SUBD:
  12543. begin
  12544. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12545. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12546. end;
  12547. {$ifdef x86_64}
  12548. R_SUBQ:
  12549. begin
  12550. { MOVZX doesn't have a 64-bit variant, because
  12551. the 32-bit version implicitly zeroes the
  12552. upper 32-bits of the destination register }
  12553. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12554. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12555. setsubreg(tmpreg, R_SUBQ);
  12556. end;
  12557. {$endif x86_64}
  12558. else
  12559. Internalerror(2020030601);
  12560. end;
  12561. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12562. asml.InsertAfter(hp2,p);
  12563. end
  12564. else
  12565. tmpreg := increg;
  12566. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12567. begin
  12568. Taicpu(hp1).ops:=2;
  12569. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12570. end;
  12571. Taicpu(hp1).loadreg(0,tmpreg);
  12572. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12573. Result := True;
  12574. { p is no longer a Jcc instruction, so exit }
  12575. Exit;
  12576. end;
  12577. end;
  12578. end;
  12579. { Detect the following:
  12580. jmp<cond> @Lbl1
  12581. jmp @Lbl2
  12582. ...
  12583. @Lbl1:
  12584. ret
  12585. Change to:
  12586. jmp<inv_cond> @Lbl2
  12587. ret
  12588. }
  12589. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12590. begin
  12591. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12592. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12593. MatchInstruction(hp2,A_RET,[S_NO]) then
  12594. begin
  12595. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12596. { Change label address to that of the unconditional jump }
  12597. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12598. TAsmLabel(symbol).DecRefs;
  12599. taicpu(hp1).opcode := A_RET;
  12600. taicpu(hp1).is_jmp := false;
  12601. taicpu(hp1).ops := taicpu(hp2).ops;
  12602. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12603. case taicpu(hp2).ops of
  12604. 0:
  12605. taicpu(hp1).clearop(0);
  12606. 1:
  12607. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12608. else
  12609. internalerror(2016041302);
  12610. end;
  12611. end;
  12612. {$ifndef i8086}
  12613. end
  12614. {
  12615. convert
  12616. j<c> .L1
  12617. mov 1,reg
  12618. jmp .L2
  12619. .L1
  12620. mov 0,reg
  12621. .L2
  12622. into
  12623. mov 0,reg
  12624. set<not(c)> reg
  12625. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12626. would destroy the flag contents
  12627. }
  12628. else if MatchInstruction(hp1,A_MOV,[]) and
  12629. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12630. {$ifdef i386}
  12631. (
  12632. { Under i386, ESI, EDI, EBP and ESP
  12633. don't have an 8-bit representation }
  12634. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12635. ) and
  12636. {$endif i386}
  12637. (taicpu(hp1).oper[0]^.val=1) and
  12638. GetNextInstruction(hp1,hp2) and
  12639. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12640. GetNextInstruction(hp2,hp3) and
  12641. (hp3.typ=ait_label) and
  12642. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12643. (tai_label(hp3).labsym.getrefs=1) and
  12644. GetNextInstruction(hp3,hp4) and
  12645. MatchInstruction(hp4,A_MOV,[]) and
  12646. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12647. (taicpu(hp4).oper[0]^.val=0) and
  12648. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12649. GetNextInstruction(hp4,hp5) and
  12650. (hp5.typ=ait_label) and
  12651. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12652. (tai_label(hp5).labsym.getrefs=1) then
  12653. begin
  12654. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12655. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12656. { remove last label }
  12657. RemoveInstruction(hp5);
  12658. { remove second label }
  12659. RemoveInstruction(hp3);
  12660. { remove jmp }
  12661. RemoveInstruction(hp2);
  12662. if taicpu(hp1).opsize=S_B then
  12663. RemoveInstruction(hp1)
  12664. else
  12665. taicpu(hp1).loadconst(0,0);
  12666. taicpu(hp4).opcode:=A_SETcc;
  12667. taicpu(hp4).opsize:=S_B;
  12668. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12669. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12670. taicpu(hp4).opercnt:=1;
  12671. taicpu(hp4).ops:=1;
  12672. taicpu(hp4).freeop(1);
  12673. RemoveCurrentP(p);
  12674. Result:=true;
  12675. exit;
  12676. end
  12677. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12678. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12679. begin
  12680. { check for
  12681. jCC xxx
  12682. <several movs>
  12683. xxx:
  12684. Also spot:
  12685. Jcc xxx
  12686. <several movs>
  12687. jmp xxx
  12688. Change to:
  12689. <several cmovs with inverted condition>
  12690. jmp xxx (only for the 2nd case)
  12691. }
  12692. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12693. if CMOVTracking^.State <> tsInvalid then
  12694. begin
  12695. CMovTracking^.Process(p);
  12696. Result := True;
  12697. end;
  12698. CMOVTracking^.Done;
  12699. {$endif i8086}
  12700. end;
  12701. end;
  12702. end;
  12703. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12704. var
  12705. hp1,hp2,hp3: tai;
  12706. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12707. NewSize: TOpSize;
  12708. NewRegSize: TSubRegister;
  12709. Limit: TCgInt;
  12710. SwapOper: POper;
  12711. begin
  12712. result:=false;
  12713. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12714. GetNextInstruction(p,hp1) and
  12715. (hp1.typ = ait_instruction);
  12716. if reg_and_hp1_is_instr and
  12717. (
  12718. (taicpu(hp1).opcode <> A_LEA) or
  12719. { If the LEA instruction can be converted into an arithmetic instruction,
  12720. it may be possible to then fold it. }
  12721. (
  12722. { If the flags register is in use, don't change the instruction
  12723. to an ADD otherwise this will scramble the flags. [Kit] }
  12724. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12725. ConvertLEA(taicpu(hp1))
  12726. )
  12727. ) and
  12728. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12729. GetNextInstruction(hp1,hp2) and
  12730. MatchInstruction(hp2,A_MOV,[]) and
  12731. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12732. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12733. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12734. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12735. {$ifdef i386}
  12736. { not all registers have byte size sub registers on i386 }
  12737. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12738. {$endif i386}
  12739. (((taicpu(hp1).ops=2) and
  12740. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12741. ((taicpu(hp1).ops=1) and
  12742. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12743. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12744. begin
  12745. { change movsX/movzX reg/ref, reg2
  12746. add/sub/or/... reg3/$const, reg2
  12747. mov reg2 reg/ref
  12748. to add/sub/or/... reg3/$const, reg/ref }
  12749. { by example:
  12750. movswl %si,%eax movswl %si,%eax p
  12751. decl %eax addl %edx,%eax hp1
  12752. movw %ax,%si movw %ax,%si hp2
  12753. ->
  12754. movswl %si,%eax movswl %si,%eax p
  12755. decw %eax addw %edx,%eax hp1
  12756. movw %ax,%si movw %ax,%si hp2
  12757. }
  12758. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12759. {
  12760. ->
  12761. movswl %si,%eax movswl %si,%eax p
  12762. decw %si addw %dx,%si hp1
  12763. movw %ax,%si movw %ax,%si hp2
  12764. }
  12765. case taicpu(hp1).ops of
  12766. 1:
  12767. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12768. 2:
  12769. begin
  12770. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12771. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12772. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12773. end;
  12774. else
  12775. internalerror(2008042702);
  12776. end;
  12777. {
  12778. ->
  12779. decw %si addw %dx,%si p
  12780. }
  12781. DebugMsg(SPeepholeOptimization + 'var3',p);
  12782. RemoveCurrentP(p, hp1);
  12783. RemoveInstruction(hp2);
  12784. Result := True;
  12785. Exit;
  12786. end;
  12787. if reg_and_hp1_is_instr and
  12788. (taicpu(hp1).opcode = A_MOV) and
  12789. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12790. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12791. {$ifdef x86_64}
  12792. { check for implicit extension to 64 bit }
  12793. or
  12794. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12795. (taicpu(hp1).opsize=S_Q) and
  12796. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12797. )
  12798. {$endif x86_64}
  12799. )
  12800. then
  12801. begin
  12802. { change
  12803. movx %reg1,%reg2
  12804. mov %reg2,%reg3
  12805. dealloc %reg2
  12806. into
  12807. movx %reg,%reg3
  12808. }
  12809. TransferUsedRegs(TmpUsedRegs);
  12810. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12811. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12812. begin
  12813. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12814. {$ifdef x86_64}
  12815. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12816. (taicpu(hp1).opsize=S_Q) then
  12817. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12818. else
  12819. {$endif x86_64}
  12820. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12821. RemoveInstruction(hp1);
  12822. Result := True;
  12823. Exit;
  12824. end;
  12825. end;
  12826. if reg_and_hp1_is_instr and
  12827. ((taicpu(hp1).opcode=A_MOV) or
  12828. (taicpu(hp1).opcode=A_ADD) or
  12829. (taicpu(hp1).opcode=A_SUB) or
  12830. (taicpu(hp1).opcode=A_CMP) or
  12831. (taicpu(hp1).opcode=A_OR) or
  12832. (taicpu(hp1).opcode=A_XOR) or
  12833. (taicpu(hp1).opcode=A_AND)
  12834. ) and
  12835. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12836. begin
  12837. AndTest := (taicpu(hp1).opcode=A_AND) and
  12838. GetNextInstruction(hp1, hp2) and
  12839. (hp2.typ = ait_instruction) and
  12840. (
  12841. (
  12842. (taicpu(hp2).opcode=A_TEST) and
  12843. (
  12844. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12845. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12846. (
  12847. { If the AND and TEST instructions share a constant, this is also valid }
  12848. (taicpu(hp1).oper[0]^.typ = top_const) and
  12849. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12850. )
  12851. ) and
  12852. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12853. ) or
  12854. (
  12855. (taicpu(hp2).opcode=A_CMP) and
  12856. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12857. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12858. )
  12859. );
  12860. { change
  12861. movx (oper),%reg2
  12862. and $x,%reg2
  12863. test %reg2,%reg2
  12864. dealloc %reg2
  12865. into
  12866. op %reg1,%reg3
  12867. if the second op accesses only the bits stored in reg1
  12868. }
  12869. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12870. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12871. (taicpu(hp1).oper[0]^.typ = top_const) and
  12872. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12873. AndTest then
  12874. begin
  12875. { Check if the AND constant is in range }
  12876. case taicpu(p).opsize of
  12877. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12878. begin
  12879. NewSize := S_B;
  12880. Limit := $FF;
  12881. end;
  12882. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12883. begin
  12884. NewSize := S_W;
  12885. Limit := $FFFF;
  12886. end;
  12887. {$ifdef x86_64}
  12888. S_LQ:
  12889. begin
  12890. NewSize := S_L;
  12891. Limit := $FFFFFFFF;
  12892. end;
  12893. {$endif x86_64}
  12894. else
  12895. InternalError(2021120303);
  12896. end;
  12897. if (
  12898. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12899. { Check for negative operands }
  12900. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12901. ) and
  12902. GetNextInstruction(hp2,hp3) and
  12903. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12904. (taicpu(hp3).condition in [C_E,C_NE]) then
  12905. begin
  12906. TransferUsedRegs(TmpUsedRegs);
  12907. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12908. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12909. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12910. begin
  12911. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12912. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12913. taicpu(hp1).opcode := A_TEST;
  12914. taicpu(hp1).opsize := NewSize;
  12915. RemoveInstruction(hp2);
  12916. RemoveCurrentP(p, hp1);
  12917. Result:=true;
  12918. exit;
  12919. end;
  12920. end;
  12921. end;
  12922. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12923. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12924. (taicpu(hp1).opsize=S_B)) or
  12925. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12926. (taicpu(hp1).opsize=S_W))
  12927. {$ifdef x86_64}
  12928. or ((taicpu(p).opsize=S_LQ) and
  12929. (taicpu(hp1).opsize=S_L))
  12930. {$endif x86_64}
  12931. ) and
  12932. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12933. begin
  12934. { change
  12935. movx %reg1,%reg2
  12936. op %reg2,%reg3
  12937. dealloc %reg2
  12938. into
  12939. op %reg1,%reg3
  12940. if the second op accesses only the bits stored in reg1
  12941. }
  12942. TransferUsedRegs(TmpUsedRegs);
  12943. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12944. if AndTest then
  12945. begin
  12946. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12947. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12948. end
  12949. else
  12950. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12951. if not RegUsed then
  12952. begin
  12953. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12954. if taicpu(p).oper[0]^.typ=top_reg then
  12955. begin
  12956. case taicpu(hp1).opsize of
  12957. S_B:
  12958. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12959. S_W:
  12960. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12961. S_L:
  12962. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12963. else
  12964. Internalerror(2020102301);
  12965. end;
  12966. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12967. end
  12968. else
  12969. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12970. RemoveCurrentP(p);
  12971. if AndTest then
  12972. RemoveInstruction(hp2);
  12973. result:=true;
  12974. exit;
  12975. end;
  12976. end
  12977. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12978. (
  12979. { Bitwise operations only }
  12980. (taicpu(hp1).opcode=A_AND) or
  12981. (taicpu(hp1).opcode=A_TEST) or
  12982. (
  12983. (taicpu(hp1).oper[0]^.typ = top_const) and
  12984. (
  12985. (taicpu(hp1).opcode=A_OR) or
  12986. (taicpu(hp1).opcode=A_XOR)
  12987. )
  12988. )
  12989. ) and
  12990. (
  12991. (taicpu(hp1).oper[0]^.typ = top_const) or
  12992. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12993. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12994. ) then
  12995. begin
  12996. { change
  12997. movx %reg2,%reg2
  12998. op const,%reg2
  12999. into
  13000. op const,%reg2 (smaller version)
  13001. movx %reg2,%reg2
  13002. also change
  13003. movx %reg1,%reg2
  13004. and/test (oper),%reg2
  13005. dealloc %reg2
  13006. into
  13007. and/test (oper),%reg1
  13008. }
  13009. case taicpu(p).opsize of
  13010. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13011. begin
  13012. NewSize := S_B;
  13013. NewRegSize := R_SUBL;
  13014. Limit := $FF;
  13015. end;
  13016. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13017. begin
  13018. NewSize := S_W;
  13019. NewRegSize := R_SUBW;
  13020. Limit := $FFFF;
  13021. end;
  13022. {$ifdef x86_64}
  13023. S_LQ:
  13024. begin
  13025. NewSize := S_L;
  13026. NewRegSize := R_SUBD;
  13027. Limit := $FFFFFFFF;
  13028. end;
  13029. {$endif x86_64}
  13030. else
  13031. Internalerror(2021120302);
  13032. end;
  13033. TransferUsedRegs(TmpUsedRegs);
  13034. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13035. if AndTest then
  13036. begin
  13037. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13038. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13039. end
  13040. else
  13041. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13042. if
  13043. (
  13044. (taicpu(p).opcode = A_MOVZX) and
  13045. (
  13046. (taicpu(hp1).opcode=A_AND) or
  13047. (taicpu(hp1).opcode=A_TEST)
  13048. ) and
  13049. not (
  13050. { If both are references, then the final instruction will have
  13051. both operands as references, which is not allowed }
  13052. (taicpu(p).oper[0]^.typ = top_ref) and
  13053. (taicpu(hp1).oper[0]^.typ = top_ref)
  13054. ) and
  13055. not RegUsed
  13056. ) or
  13057. (
  13058. (
  13059. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13060. not RegUsed
  13061. ) and
  13062. (taicpu(p).oper[0]^.typ = top_reg) and
  13063. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13064. (taicpu(hp1).oper[0]^.typ = top_const) and
  13065. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13066. ) then
  13067. begin
  13068. {$if defined(i386) or defined(i8086)}
  13069. { If the target size is 8-bit, make sure we can actually encode it }
  13070. 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
  13071. Exit;
  13072. {$endif i386 or i8086}
  13073. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13074. taicpu(hp1).opsize := NewSize;
  13075. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13076. if AndTest then
  13077. begin
  13078. RemoveInstruction(hp2);
  13079. if not RegUsed then
  13080. begin
  13081. taicpu(hp1).opcode := A_TEST;
  13082. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13083. begin
  13084. { Make sure the reference is the second operand }
  13085. SwapOper := taicpu(hp1).oper[0];
  13086. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13087. taicpu(hp1).oper[1] := SwapOper;
  13088. end;
  13089. end;
  13090. end;
  13091. case taicpu(hp1).oper[0]^.typ of
  13092. top_reg:
  13093. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13094. top_const:
  13095. { For the AND/TEST case }
  13096. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13097. else
  13098. ;
  13099. end;
  13100. if RegUsed then
  13101. begin
  13102. AsmL.Remove(p);
  13103. AsmL.InsertAfter(p, hp1);
  13104. p := hp1;
  13105. end
  13106. else
  13107. RemoveCurrentP(p, hp1);
  13108. result:=true;
  13109. exit;
  13110. end;
  13111. end;
  13112. end;
  13113. if reg_and_hp1_is_instr and
  13114. (taicpu(p).oper[0]^.typ = top_reg) and
  13115. (
  13116. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13117. ) and
  13118. (taicpu(hp1).oper[0]^.typ = top_const) and
  13119. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13120. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13121. { Minimum shift value allowed is the bit difference between the sizes }
  13122. (taicpu(hp1).oper[0]^.val >=
  13123. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13124. 8 * (
  13125. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13126. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13127. )
  13128. ) then
  13129. begin
  13130. { For:
  13131. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13132. shl/sal ##, %reg1
  13133. Remove the movsx/movzx instruction if the shift overwrites the
  13134. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13135. }
  13136. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13137. RemoveCurrentP(p, hp1);
  13138. Result := True;
  13139. Exit;
  13140. end
  13141. else if reg_and_hp1_is_instr and
  13142. (taicpu(p).oper[0]^.typ = top_reg) and
  13143. (
  13144. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13145. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13146. ) and
  13147. (taicpu(hp1).oper[0]^.typ = top_const) and
  13148. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13149. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13150. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13151. (taicpu(hp1).oper[0]^.val <
  13152. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13153. 8 * (
  13154. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13155. )
  13156. ) then
  13157. begin
  13158. { For:
  13159. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13160. sar ##, %reg1 shr ##, %reg1
  13161. Move the shift to before the movx instruction if the shift value
  13162. is not too large.
  13163. }
  13164. asml.Remove(hp1);
  13165. asml.InsertBefore(hp1, p);
  13166. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13167. case taicpu(p).opsize of
  13168. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13169. taicpu(hp1).opsize := S_B;
  13170. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13171. taicpu(hp1).opsize := S_W;
  13172. {$ifdef x86_64}
  13173. S_LQ:
  13174. taicpu(hp1).opsize := S_L;
  13175. {$endif}
  13176. else
  13177. InternalError(2020112401);
  13178. end;
  13179. if (taicpu(hp1).opcode = A_SHR) then
  13180. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13181. else
  13182. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13183. Result := True;
  13184. end;
  13185. if reg_and_hp1_is_instr and
  13186. (taicpu(p).oper[0]^.typ = top_reg) and
  13187. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13188. (
  13189. (taicpu(hp1).opcode = taicpu(p).opcode)
  13190. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13191. {$ifdef x86_64}
  13192. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13193. {$endif x86_64}
  13194. ) then
  13195. begin
  13196. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13197. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13198. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13199. begin
  13200. {
  13201. For example:
  13202. movzbw %al,%ax
  13203. movzwl %ax,%eax
  13204. Compress into:
  13205. movzbl %al,%eax
  13206. }
  13207. RegUsed := False;
  13208. case taicpu(p).opsize of
  13209. S_BW:
  13210. case taicpu(hp1).opsize of
  13211. S_WL:
  13212. begin
  13213. taicpu(p).opsize := S_BL;
  13214. RegUsed := True;
  13215. end;
  13216. {$ifdef x86_64}
  13217. S_WQ:
  13218. begin
  13219. if taicpu(p).opcode = A_MOVZX then
  13220. begin
  13221. taicpu(p).opsize := S_BL;
  13222. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13223. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13224. end
  13225. else
  13226. taicpu(p).opsize := S_BQ;
  13227. RegUsed := True;
  13228. end;
  13229. {$endif x86_64}
  13230. else
  13231. ;
  13232. end;
  13233. {$ifdef x86_64}
  13234. S_BL:
  13235. case taicpu(hp1).opsize of
  13236. S_LQ:
  13237. begin
  13238. if taicpu(p).opcode = A_MOVZX then
  13239. begin
  13240. taicpu(p).opsize := S_BL;
  13241. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13242. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13243. end
  13244. else
  13245. taicpu(p).opsize := S_BQ;
  13246. RegUsed := True;
  13247. end;
  13248. else
  13249. ;
  13250. end;
  13251. S_WL:
  13252. case taicpu(hp1).opsize of
  13253. S_LQ:
  13254. begin
  13255. if taicpu(p).opcode = A_MOVZX then
  13256. begin
  13257. taicpu(p).opsize := S_WL;
  13258. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13259. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13260. end
  13261. else
  13262. taicpu(p).opsize := S_WQ;
  13263. RegUsed := True;
  13264. end;
  13265. else
  13266. ;
  13267. end;
  13268. {$endif x86_64}
  13269. else
  13270. ;
  13271. end;
  13272. if RegUsed then
  13273. begin
  13274. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13275. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13276. RemoveInstruction(hp1);
  13277. Result := True;
  13278. Exit;
  13279. end;
  13280. end;
  13281. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13282. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13283. GetNextInstruction(hp1, hp2) and
  13284. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13285. (
  13286. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13287. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13288. {$ifdef x86_64}
  13289. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13290. {$endif x86_64}
  13291. ) and
  13292. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13293. (
  13294. (
  13295. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13296. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13297. ) or
  13298. (
  13299. { Only allow the operands in reverse order for TEST instructions }
  13300. (taicpu(hp2).opcode = A_TEST) and
  13301. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13302. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13303. )
  13304. ) then
  13305. begin
  13306. {
  13307. For example:
  13308. movzbl %al,%eax
  13309. movzbl (ref),%edx
  13310. andl %edx,%eax
  13311. (%edx deallocated)
  13312. Change to:
  13313. andb (ref),%al
  13314. movzbl %al,%eax
  13315. Rules are:
  13316. - First two instructions have the same opcode and opsize
  13317. - First instruction's operands are the same super-register
  13318. - Second instruction operates on a different register
  13319. - Third instruction is AND, OR, XOR or TEST
  13320. - Third instruction's operands are the destination registers of the first two instructions
  13321. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13322. - Second instruction's destination register is deallocated afterwards
  13323. }
  13324. TransferUsedRegs(TmpUsedRegs);
  13325. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13326. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13327. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13328. begin
  13329. case taicpu(p).opsize of
  13330. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13331. NewSize := S_B;
  13332. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13333. NewSize := S_W;
  13334. {$ifdef x86_64}
  13335. S_LQ:
  13336. NewSize := S_L;
  13337. {$endif x86_64}
  13338. else
  13339. InternalError(2021120301);
  13340. end;
  13341. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13342. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13343. taicpu(hp2).opsize := NewSize;
  13344. RemoveInstruction(hp1);
  13345. { With TEST, it's best to keep the MOVX instruction at the top }
  13346. if (taicpu(hp2).opcode <> A_TEST) then
  13347. begin
  13348. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13349. asml.Remove(p);
  13350. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13351. asml.InsertAfter(p, hp2);
  13352. p := hp2;
  13353. end
  13354. else
  13355. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13356. Result := True;
  13357. Exit;
  13358. end;
  13359. end;
  13360. end;
  13361. if taicpu(p).opcode=A_MOVZX then
  13362. begin
  13363. { removes superfluous And's after movzx's }
  13364. if reg_and_hp1_is_instr and
  13365. (taicpu(hp1).opcode = A_AND) and
  13366. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13367. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13368. {$ifdef x86_64}
  13369. { check for implicit extension to 64 bit }
  13370. or
  13371. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13372. (taicpu(hp1).opsize=S_Q) and
  13373. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13374. )
  13375. {$endif x86_64}
  13376. )
  13377. then
  13378. begin
  13379. case taicpu(p).opsize Of
  13380. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13381. if (taicpu(hp1).oper[0]^.val = $ff) then
  13382. begin
  13383. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13384. RemoveInstruction(hp1);
  13385. Result:=true;
  13386. exit;
  13387. end;
  13388. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13389. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13390. begin
  13391. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13392. RemoveInstruction(hp1);
  13393. Result:=true;
  13394. exit;
  13395. end;
  13396. {$ifdef x86_64}
  13397. S_LQ:
  13398. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13399. begin
  13400. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13401. RemoveInstruction(hp1);
  13402. Result:=true;
  13403. exit;
  13404. end;
  13405. {$endif x86_64}
  13406. else
  13407. ;
  13408. end;
  13409. { we cannot get rid of the and, but can we get rid of the movz ?}
  13410. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13411. begin
  13412. case taicpu(p).opsize Of
  13413. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13414. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13415. begin
  13416. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13417. RemoveCurrentP(p,hp1);
  13418. Result:=true;
  13419. exit;
  13420. end;
  13421. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13422. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13423. begin
  13424. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13425. RemoveCurrentP(p,hp1);
  13426. Result:=true;
  13427. exit;
  13428. end;
  13429. {$ifdef x86_64}
  13430. S_LQ:
  13431. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13432. begin
  13433. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13434. RemoveCurrentP(p,hp1);
  13435. Result:=true;
  13436. exit;
  13437. end;
  13438. {$endif x86_64}
  13439. else
  13440. ;
  13441. end;
  13442. end;
  13443. end;
  13444. { changes some movzx constructs to faster synonyms (all examples
  13445. are given with eax/ax, but are also valid for other registers)}
  13446. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13447. begin
  13448. case taicpu(p).opsize of
  13449. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13450. (the machine code is equivalent to movzbl %al,%eax), but the
  13451. code generator still generates that assembler instruction and
  13452. it is silently converted. This should probably be checked.
  13453. [Kit] }
  13454. S_BW:
  13455. begin
  13456. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13457. (
  13458. not IsMOVZXAcceptable
  13459. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13460. or (
  13461. (cs_opt_size in current_settings.optimizerswitches) and
  13462. (taicpu(p).oper[1]^.reg = NR_AX)
  13463. )
  13464. ) then
  13465. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13466. begin
  13467. DebugMsg(SPeepholeOptimization + 'var7',p);
  13468. taicpu(p).opcode := A_AND;
  13469. taicpu(p).changeopsize(S_W);
  13470. taicpu(p).loadConst(0,$ff);
  13471. Result := True;
  13472. end
  13473. else if not IsMOVZXAcceptable and
  13474. GetNextInstruction(p, hp1) and
  13475. (tai(hp1).typ = ait_instruction) and
  13476. (taicpu(hp1).opcode = A_AND) and
  13477. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13478. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13479. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13480. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13481. begin
  13482. DebugMsg(SPeepholeOptimization + 'var8',p);
  13483. taicpu(p).opcode := A_MOV;
  13484. taicpu(p).changeopsize(S_W);
  13485. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13486. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13487. Result := True;
  13488. end;
  13489. end;
  13490. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13491. S_BL:
  13492. if not IsMOVZXAcceptable then
  13493. begin
  13494. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13495. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13496. begin
  13497. DebugMsg(SPeepholeOptimization + 'var9',p);
  13498. taicpu(p).opcode := A_AND;
  13499. taicpu(p).changeopsize(S_L);
  13500. taicpu(p).loadConst(0,$ff);
  13501. Result := True;
  13502. end
  13503. else if GetNextInstruction(p, hp1) and
  13504. (tai(hp1).typ = ait_instruction) and
  13505. (taicpu(hp1).opcode = A_AND) and
  13506. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13507. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13508. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13509. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13510. begin
  13511. DebugMsg(SPeepholeOptimization + 'var10',p);
  13512. taicpu(p).opcode := A_MOV;
  13513. taicpu(p).changeopsize(S_L);
  13514. { do not use R_SUBWHOLE
  13515. as movl %rdx,%eax
  13516. is invalid in assembler PM }
  13517. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13518. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13519. Result := True;
  13520. end;
  13521. end;
  13522. {$endif i8086}
  13523. S_WL:
  13524. if not IsMOVZXAcceptable then
  13525. begin
  13526. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13527. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13528. begin
  13529. DebugMsg(SPeepholeOptimization + 'var11',p);
  13530. taicpu(p).opcode := A_AND;
  13531. taicpu(p).changeopsize(S_L);
  13532. taicpu(p).loadConst(0,$ffff);
  13533. Result := True;
  13534. end
  13535. else if GetNextInstruction(p, hp1) and
  13536. (tai(hp1).typ = ait_instruction) and
  13537. (taicpu(hp1).opcode = A_AND) and
  13538. (taicpu(hp1).oper[0]^.typ = top_const) and
  13539. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13540. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13541. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13542. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13543. begin
  13544. DebugMsg(SPeepholeOptimization + 'var12',p);
  13545. taicpu(p).opcode := A_MOV;
  13546. taicpu(p).changeopsize(S_L);
  13547. { do not use R_SUBWHOLE
  13548. as movl %rdx,%eax
  13549. is invalid in assembler PM }
  13550. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13551. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13552. Result := True;
  13553. end;
  13554. end;
  13555. else
  13556. InternalError(2017050705);
  13557. end;
  13558. end
  13559. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13560. begin
  13561. if GetNextInstruction(p, hp1) and
  13562. (tai(hp1).typ = ait_instruction) and
  13563. (taicpu(hp1).opcode = A_AND) and
  13564. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13565. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13566. begin
  13567. case taicpu(p).opsize Of
  13568. S_BL:
  13569. if (taicpu(hp1).opsize <> S_L) or
  13570. (taicpu(hp1).oper[0]^.val > $FF) then
  13571. begin
  13572. DebugMsg(SPeepholeOptimization + 'var13',p);
  13573. taicpu(hp1).changeopsize(S_L);
  13574. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13575. Include(OptsToCheck, aoc_ForceNewIteration);
  13576. end;
  13577. S_WL:
  13578. if (taicpu(hp1).opsize <> S_L) or
  13579. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13580. begin
  13581. DebugMsg(SPeepholeOptimization + 'var14',p);
  13582. taicpu(hp1).changeopsize(S_L);
  13583. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13584. Include(OptsToCheck, aoc_ForceNewIteration);
  13585. end;
  13586. S_BW:
  13587. if (taicpu(hp1).opsize <> S_W) or
  13588. (taicpu(hp1).oper[0]^.val > $FF) then
  13589. begin
  13590. DebugMsg(SPeepholeOptimization + 'var15',p);
  13591. taicpu(hp1).changeopsize(S_W);
  13592. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13593. Include(OptsToCheck, aoc_ForceNewIteration);
  13594. end;
  13595. else
  13596. Internalerror(2017050704)
  13597. end;
  13598. end;
  13599. end;
  13600. end;
  13601. end;
  13602. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13603. var
  13604. hp1, hp2 : tai;
  13605. MaskLength : Cardinal;
  13606. MaskedBits : TCgInt;
  13607. ActiveReg : TRegister;
  13608. begin
  13609. Result:=false;
  13610. { There are no optimisations for reference targets }
  13611. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13612. Exit;
  13613. while GetNextInstruction(p, hp1) and
  13614. (hp1.typ = ait_instruction) do
  13615. begin
  13616. if (taicpu(p).oper[0]^.typ = top_const) then
  13617. begin
  13618. case taicpu(hp1).opcode of
  13619. A_AND:
  13620. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13621. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13622. { the second register must contain the first one, so compare their subreg types }
  13623. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13624. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13625. { change
  13626. and const1, reg
  13627. and const2, reg
  13628. to
  13629. and (const1 and const2), reg
  13630. }
  13631. begin
  13632. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13633. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13634. RemoveCurrentP(p, hp1);
  13635. Result:=true;
  13636. exit;
  13637. end;
  13638. A_CMP:
  13639. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13640. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13641. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13642. { Just check that the condition on the next instruction is compatible }
  13643. GetNextInstruction(hp1, hp2) and
  13644. (hp2.typ = ait_instruction) and
  13645. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13646. then
  13647. { change
  13648. and 2^n, reg
  13649. cmp 2^n, reg
  13650. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13651. to
  13652. and 2^n, reg
  13653. test reg, reg
  13654. j(~c) / set(~c) / cmov(~c)
  13655. }
  13656. begin
  13657. { Keep TEST instruction in, rather than remove it, because
  13658. it may trigger other optimisations such as MovAndTest2Test }
  13659. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13660. taicpu(hp1).opcode := A_TEST;
  13661. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13662. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13663. Result := True;
  13664. Exit;
  13665. end
  13666. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13667. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13668. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13669. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13670. { change
  13671. and $ff/$ff/$ffff, reg
  13672. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13673. dealloc reg
  13674. to
  13675. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13676. }
  13677. begin
  13678. TransferUsedRegs(TmpUsedRegs);
  13679. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13680. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13681. begin
  13682. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13683. case taicpu(p).oper[0]^.val of
  13684. $ff:
  13685. begin
  13686. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13687. taicpu(hp1).opsize:=S_B;
  13688. end;
  13689. $ffff:
  13690. begin
  13691. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13692. taicpu(hp1).opsize:=S_W;
  13693. end;
  13694. $ffffffff:
  13695. begin
  13696. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13697. taicpu(hp1).opsize:=S_L;
  13698. end;
  13699. else
  13700. Internalerror(2023030401);
  13701. end;
  13702. RemoveCurrentP(p);
  13703. Result := True;
  13704. Exit;
  13705. end;
  13706. end;
  13707. A_MOVZX:
  13708. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13709. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13710. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13711. (
  13712. (
  13713. (taicpu(p).opsize=S_W) and
  13714. (taicpu(hp1).opsize=S_BW)
  13715. ) or
  13716. (
  13717. (taicpu(p).opsize=S_L) and
  13718. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13719. )
  13720. {$ifdef x86_64}
  13721. or
  13722. (
  13723. (taicpu(p).opsize=S_Q) and
  13724. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13725. )
  13726. {$endif x86_64}
  13727. ) then
  13728. begin
  13729. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13730. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13731. ) or
  13732. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13733. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13734. then
  13735. begin
  13736. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13737. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13738. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13739. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13740. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13741. }
  13742. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13743. RemoveInstruction(hp1);
  13744. { See if there are other optimisations possible }
  13745. Continue;
  13746. end;
  13747. end;
  13748. A_SHL:
  13749. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13750. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13751. begin
  13752. {$ifopt R+}
  13753. {$define RANGE_WAS_ON}
  13754. {$R-}
  13755. {$endif}
  13756. { get length of potential and mask }
  13757. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13758. { really a mask? }
  13759. {$ifdef RANGE_WAS_ON}
  13760. {$R+}
  13761. {$endif}
  13762. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13763. { unmasked part shifted out? }
  13764. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13765. begin
  13766. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13767. RemoveCurrentP(p, hp1);
  13768. Result:=true;
  13769. exit;
  13770. end;
  13771. end;
  13772. A_SHR:
  13773. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13774. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13775. (taicpu(hp1).oper[0]^.val <= 63) then
  13776. begin
  13777. { Does SHR combined with the AND cover all the bits?
  13778. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13779. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13780. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13781. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13782. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13783. begin
  13784. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13785. RemoveCurrentP(p, hp1);
  13786. Result := True;
  13787. Exit;
  13788. end;
  13789. end;
  13790. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13791. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13792. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13793. begin
  13794. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13795. (
  13796. (
  13797. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13798. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13799. ) or (
  13800. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13801. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13802. {$ifdef x86_64}
  13803. ) or (
  13804. (taicpu(hp1).opsize = S_LQ) and
  13805. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13806. {$endif x86_64}
  13807. )
  13808. ) then
  13809. begin
  13810. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13811. begin
  13812. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13813. RemoveInstruction(hp1);
  13814. { See if there are other optimisations possible }
  13815. Continue;
  13816. end;
  13817. { The super-registers are the same though.
  13818. Note that this change by itself doesn't improve
  13819. code speed, but it opens up other optimisations. }
  13820. {$ifdef x86_64}
  13821. { Convert 64-bit register to 32-bit }
  13822. case taicpu(hp1).opsize of
  13823. S_BQ:
  13824. begin
  13825. taicpu(hp1).opsize := S_BL;
  13826. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13827. end;
  13828. S_WQ:
  13829. begin
  13830. taicpu(hp1).opsize := S_WL;
  13831. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13832. end
  13833. else
  13834. ;
  13835. end;
  13836. {$endif x86_64}
  13837. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13838. taicpu(hp1).opcode := A_MOVZX;
  13839. { See if there are other optimisations possible }
  13840. Continue;
  13841. end;
  13842. end;
  13843. else
  13844. ;
  13845. end;
  13846. end
  13847. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13848. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13849. begin
  13850. {$ifdef x86_64}
  13851. if (taicpu(p).opsize = S_Q) then
  13852. begin
  13853. { Never necessary }
  13854. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13855. RemoveCurrentP(p, hp1);
  13856. Result := True;
  13857. Exit;
  13858. end;
  13859. {$endif x86_64}
  13860. { Forward check to determine necessity of and %reg,%reg }
  13861. TransferUsedRegs(TmpUsedRegs);
  13862. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13863. { Saves on a bunch of dereferences }
  13864. ActiveReg := taicpu(p).oper[1]^.reg;
  13865. case taicpu(hp1).opcode of
  13866. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13867. if (
  13868. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13869. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13870. ) and
  13871. (
  13872. (taicpu(hp1).opcode <> A_MOV) or
  13873. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13874. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13875. ) and
  13876. not (
  13877. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13878. (taicpu(hp1).opcode = A_MOV) and
  13879. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13880. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13881. ) and
  13882. (
  13883. (
  13884. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13885. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13886. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13887. ) or
  13888. (
  13889. {$ifdef x86_64}
  13890. (
  13891. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13892. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13893. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13894. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13895. ) and
  13896. {$endif x86_64}
  13897. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13898. )
  13899. ) then
  13900. begin
  13901. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13902. RemoveCurrentP(p, hp1);
  13903. Result := True;
  13904. Exit;
  13905. end;
  13906. A_ADD,
  13907. A_AND,
  13908. A_BSF,
  13909. A_BSR,
  13910. A_BTC,
  13911. A_BTR,
  13912. A_BTS,
  13913. A_OR,
  13914. A_SUB,
  13915. A_XOR:
  13916. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13917. if (
  13918. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13919. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13920. ) and
  13921. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13922. begin
  13923. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13924. RemoveCurrentP(p, hp1);
  13925. Result := True;
  13926. Exit;
  13927. end;
  13928. A_CMP,
  13929. A_TEST:
  13930. if (
  13931. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13932. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13933. ) and
  13934. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13935. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13936. begin
  13937. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13938. RemoveCurrentP(p, hp1);
  13939. Result := True;
  13940. Exit;
  13941. end;
  13942. A_BSWAP,
  13943. A_NEG,
  13944. A_NOT:
  13945. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13946. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13947. begin
  13948. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13949. RemoveCurrentP(p, hp1);
  13950. Result := True;
  13951. Exit;
  13952. end;
  13953. else
  13954. ;
  13955. end;
  13956. end;
  13957. if (taicpu(hp1).is_jmp) and
  13958. (taicpu(hp1).opcode<>A_JMP) and
  13959. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13960. begin
  13961. { change
  13962. and x, reg
  13963. jxx
  13964. to
  13965. test x, reg
  13966. jxx
  13967. if reg is deallocated before the
  13968. jump, but only if it's a conditional jump (PFV)
  13969. }
  13970. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13971. taicpu(p).opcode := A_TEST;
  13972. Exit;
  13973. end;
  13974. Break;
  13975. end;
  13976. { Lone AND tests }
  13977. if (taicpu(p).oper[0]^.typ = top_const) then
  13978. begin
  13979. {
  13980. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13981. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13982. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13983. }
  13984. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13985. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13986. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13987. begin
  13988. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13989. if taicpu(p).opsize = S_L then
  13990. begin
  13991. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13992. Result := True;
  13993. end;
  13994. end;
  13995. end;
  13996. { Backward check to determine necessity of and %reg,%reg }
  13997. if (taicpu(p).oper[0]^.typ = top_reg) and
  13998. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13999. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14000. GetLastInstruction(p, hp2) and
  14001. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  14002. { Check size of adjacent instruction to determine if the AND is
  14003. effectively a null operation }
  14004. (
  14005. (taicpu(p).opsize = taicpu(hp2).opsize) or
  14006. { Note: Don't include S_Q }
  14007. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  14008. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  14009. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  14010. ) then
  14011. begin
  14012. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  14013. { If GetNextInstruction returned False, hp1 will be nil }
  14014. RemoveCurrentP(p, hp1);
  14015. Result := True;
  14016. Exit;
  14017. end;
  14018. end;
  14019. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14020. var
  14021. hp1, hp2: tai;
  14022. NewRef: TReference;
  14023. Distance: Cardinal;
  14024. TempTracking: TAllUsedRegs;
  14025. { This entire nested function is used in an if-statement below, but we
  14026. want to avoid all the used reg transfers and GetNextInstruction calls
  14027. until we really have to check }
  14028. function MemRegisterNotUsedLater: Boolean; inline;
  14029. var
  14030. hp2: tai;
  14031. begin
  14032. TransferUsedRegs(TmpUsedRegs);
  14033. hp2 := p;
  14034. repeat
  14035. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14036. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14037. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14038. end;
  14039. begin
  14040. Result := False;
  14041. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14042. (taicpu(p).oper[1]^.typ = top_reg) then
  14043. begin
  14044. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14045. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14046. (hp1.typ <> ait_instruction) or
  14047. not
  14048. (
  14049. (cs_opt_level3 in current_settings.optimizerswitches) or
  14050. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14051. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14052. ) then
  14053. Exit;
  14054. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14055. addq $x, %rax
  14056. movq %rax, %rdx
  14057. sarq $63, %rdx
  14058. (%rax still in use)
  14059. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14060. leaq $x(%rax),%rdx
  14061. addq $x, %rax
  14062. sarq $63, %rdx
  14063. ...which is okay since it breaks the dependency chain between
  14064. addq and movq, but if OptPass2MOV is called first:
  14065. addq $x, %rax
  14066. cqto
  14067. ...which is better in all ways, taking only 2 cycles to execute
  14068. and much smaller in code size.
  14069. }
  14070. { The extra register tracking is quite strenuous }
  14071. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14072. MatchInstruction(hp1, A_MOV, []) then
  14073. begin
  14074. { Update the register tracking to the MOV instruction }
  14075. CopyUsedRegs(TempTracking);
  14076. hp2 := p;
  14077. repeat
  14078. UpdateUsedRegs(tai(hp2.Next));
  14079. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14080. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14081. OptPass2ADD get called again }
  14082. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14083. begin
  14084. { Reset the tracking to the current instruction }
  14085. RestoreUsedRegs(TempTracking);
  14086. ReleaseUsedRegs(TempTracking);
  14087. Result := True;
  14088. Exit;
  14089. end;
  14090. { Reset the tracking to the current instruction }
  14091. RestoreUsedRegs(TempTracking);
  14092. ReleaseUsedRegs(TempTracking);
  14093. { If OptPass2MOV returned True, we don't need to set Result to
  14094. True if hp1 didn't change because the ADD instruction didn't
  14095. get modified and we'll be evaluating hp1 again when the
  14096. peephole optimizer reaches it }
  14097. end;
  14098. { Change:
  14099. add %reg2,%reg1
  14100. (%reg2 not modified in between)
  14101. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14102. To:
  14103. mov/s/z #(%reg1,%reg2),%reg1
  14104. }
  14105. if (taicpu(p).oper[0]^.typ = top_reg) and
  14106. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14107. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14108. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14109. (
  14110. (
  14111. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14112. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14113. { r/esp cannot be an index }
  14114. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14115. ) or (
  14116. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14117. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14118. )
  14119. ) and (
  14120. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14121. (
  14122. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14123. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14124. MemRegisterNotUsedLater
  14125. )
  14126. ) then
  14127. begin
  14128. if (
  14129. { Instructions are guaranteed to be adjacent on -O2 and under }
  14130. (cs_opt_level3 in current_settings.optimizerswitches) and
  14131. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14132. ) then
  14133. begin
  14134. { If the other register is used in between, move the MOV
  14135. instruction to right after the ADD instruction so a
  14136. saving can still be made }
  14137. Asml.Remove(hp1);
  14138. Asml.InsertAfter(hp1, p);
  14139. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14140. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14141. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14142. RemoveCurrentp(p, hp1);
  14143. end
  14144. else
  14145. begin
  14146. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14147. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14148. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14149. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14150. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14151. { hp1 may not be the immediate next instruction under -O3 }
  14152. RemoveCurrentp(p)
  14153. else
  14154. RemoveCurrentp(p, hp1);
  14155. end;
  14156. Result := True;
  14157. Exit;
  14158. end;
  14159. { Change:
  14160. addl/q $x,%reg1
  14161. movl/q %reg1,%reg2
  14162. To:
  14163. leal/q $x(%reg1),%reg2
  14164. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14165. Breaks the dependency chain.
  14166. }
  14167. if (taicpu(p).oper[0]^.typ = top_const) and
  14168. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14169. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14170. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14171. (
  14172. { Instructions are guaranteed to be adjacent on -O2 and under }
  14173. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14174. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14175. ) then
  14176. begin
  14177. TransferUsedRegs(TmpUsedRegs);
  14178. hp2 := p;
  14179. repeat
  14180. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14181. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14182. if (
  14183. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14184. not (cs_opt_size in current_settings.optimizerswitches) or
  14185. (
  14186. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14187. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14188. )
  14189. ) then
  14190. begin
  14191. { Change the MOV instruction to a LEA instruction, and update the
  14192. first operand }
  14193. reference_reset(NewRef, 1, []);
  14194. NewRef.base := taicpu(p).oper[1]^.reg;
  14195. NewRef.scalefactor := 1;
  14196. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14197. taicpu(hp1).opcode := A_LEA;
  14198. taicpu(hp1).loadref(0, NewRef);
  14199. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14200. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14201. begin
  14202. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14203. { Move what is now the LEA instruction to before the ADD instruction }
  14204. Asml.Remove(hp1);
  14205. Asml.InsertBefore(hp1, p);
  14206. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14207. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14208. p := hp1;
  14209. end
  14210. else
  14211. begin
  14212. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14213. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14214. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14215. { hp1 may not be the immediate next instruction under -O3 }
  14216. RemoveCurrentp(p)
  14217. else
  14218. RemoveCurrentp(p, hp1);
  14219. end;
  14220. Result := True;
  14221. end;
  14222. end;
  14223. end;
  14224. end;
  14225. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14226. var
  14227. SubReg: TSubRegister;
  14228. hp1, hp2: tai;
  14229. CallJmp: Boolean;
  14230. begin
  14231. Result := False;
  14232. CallJmp := False;
  14233. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14234. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14235. with taicpu(p).oper[0]^.ref^ do
  14236. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14237. if (offset = 0) then
  14238. begin
  14239. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14240. begin
  14241. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14242. taicpu(p).opcode := A_ADD;
  14243. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14244. Result := True;
  14245. end
  14246. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14247. begin
  14248. if (base <> NR_NO) then
  14249. begin
  14250. if (scalefactor <= 1) then
  14251. begin
  14252. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14253. taicpu(p).opcode := A_ADD;
  14254. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14255. Result := True;
  14256. end;
  14257. end
  14258. else
  14259. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14260. if (scalefactor in [2, 4, 8]) then
  14261. begin
  14262. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14263. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14264. taicpu(p).opcode := A_SHL;
  14265. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14266. Result := True;
  14267. end;
  14268. end;
  14269. end
  14270. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14271. lot of latency, so break off the offset if %reg3 is used soon
  14272. afterwards }
  14273. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14274. { If 3-component addresses don't have additional latency, don't
  14275. perform this optimisation }
  14276. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14277. GetNextInstruction(p, hp1) and
  14278. (hp1.typ = ait_instruction) and
  14279. (
  14280. (
  14281. { Permit jumps and calls since they have a larger degree of overhead }
  14282. (
  14283. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14284. (
  14285. { ... unless the register specifies the location }
  14286. (taicpu(hp1).ops > 0) and
  14287. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14288. )
  14289. ) and
  14290. (
  14291. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14292. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14293. )
  14294. )
  14295. or
  14296. (
  14297. { Check up to two instructions ahead }
  14298. GetNextInstruction(hp1, hp2) and
  14299. (hp2.typ = ait_instruction) and
  14300. (
  14301. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14302. (
  14303. { Same as above }
  14304. (taicpu(hp2).ops > 0) and
  14305. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14306. )
  14307. ) and
  14308. (
  14309. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14310. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14311. )
  14312. )
  14313. ) then
  14314. begin
  14315. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14316. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14317. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14318. offset := 0;
  14319. if Assigned(symbol) or Assigned(relsymbol) then
  14320. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14321. else
  14322. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14323. { Inserting before the next instruction rather than after the
  14324. current instruction gives more accurate register tracking }
  14325. asml.InsertBefore(hp2, hp1);
  14326. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14327. Result := True;
  14328. end;
  14329. end;
  14330. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14331. var
  14332. hp1, hp2: tai;
  14333. NewRef: TReference;
  14334. Distance: Cardinal;
  14335. TempTracking: TAllUsedRegs;
  14336. begin
  14337. Result := False;
  14338. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14339. MatchOpType(taicpu(p),top_const,top_reg) then
  14340. begin
  14341. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14342. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14343. (hp1.typ <> ait_instruction) or
  14344. not
  14345. (
  14346. (cs_opt_level3 in current_settings.optimizerswitches) or
  14347. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14348. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14349. ) then
  14350. Exit;
  14351. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14352. subq $x, %rax
  14353. movq %rax, %rdx
  14354. sarq $63, %rdx
  14355. (%rax still in use)
  14356. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14357. leaq $-x(%rax),%rdx
  14358. movq $x, %rax
  14359. sarq $63, %rdx
  14360. ...which is okay since it breaks the dependency chain between
  14361. subq and movq, but if OptPass2MOV is called first:
  14362. subq $x, %rax
  14363. cqto
  14364. ...which is better in all ways, taking only 2 cycles to execute
  14365. and much smaller in code size.
  14366. }
  14367. { The extra register tracking is quite strenuous }
  14368. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14369. MatchInstruction(hp1, A_MOV, []) then
  14370. begin
  14371. { Update the register tracking to the MOV instruction }
  14372. CopyUsedRegs(TempTracking);
  14373. hp2 := p;
  14374. repeat
  14375. UpdateUsedRegs(tai(hp2.Next));
  14376. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14377. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14378. OptPass2SUB get called again }
  14379. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14380. begin
  14381. { Reset the tracking to the current instruction }
  14382. RestoreUsedRegs(TempTracking);
  14383. ReleaseUsedRegs(TempTracking);
  14384. Result := True;
  14385. Exit;
  14386. end;
  14387. { Reset the tracking to the current instruction }
  14388. RestoreUsedRegs(TempTracking);
  14389. ReleaseUsedRegs(TempTracking);
  14390. { If OptPass2MOV returned True, we don't need to set Result to
  14391. True if hp1 didn't change because the SUB instruction didn't
  14392. get modified and we'll be evaluating hp1 again when the
  14393. peephole optimizer reaches it }
  14394. end;
  14395. { Change:
  14396. subl/q $x,%reg1
  14397. movl/q %reg1,%reg2
  14398. To:
  14399. leal/q $-x(%reg1),%reg2
  14400. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14401. Breaks the dependency chain and potentially permits the removal of
  14402. a CMP instruction if one follows.
  14403. }
  14404. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14405. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14406. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14407. (
  14408. { Instructions are guaranteed to be adjacent on -O2 and under }
  14409. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14410. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14411. ) then
  14412. begin
  14413. TransferUsedRegs(TmpUsedRegs);
  14414. hp2 := p;
  14415. repeat
  14416. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14417. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14418. if (
  14419. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14420. not (cs_opt_size in current_settings.optimizerswitches) or
  14421. (
  14422. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14423. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14424. )
  14425. ) then
  14426. begin
  14427. { Change the MOV instruction to a LEA instruction, and update the
  14428. first operand }
  14429. reference_reset(NewRef, 1, []);
  14430. NewRef.base := taicpu(p).oper[1]^.reg;
  14431. NewRef.scalefactor := 1;
  14432. NewRef.offset := -taicpu(p).oper[0]^.val;
  14433. taicpu(hp1).opcode := A_LEA;
  14434. taicpu(hp1).loadref(0, NewRef);
  14435. TransferUsedRegs(TmpUsedRegs);
  14436. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14437. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14438. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14439. begin
  14440. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14441. { Move what is now the LEA instruction to before the SUB instruction }
  14442. Asml.Remove(hp1);
  14443. Asml.InsertBefore(hp1, p);
  14444. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14445. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14446. p := hp1;
  14447. end
  14448. else
  14449. begin
  14450. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14451. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14452. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14453. { hp1 may not be the immediate next instruction under -O3 }
  14454. RemoveCurrentp(p)
  14455. else
  14456. RemoveCurrentp(p, hp1);
  14457. end;
  14458. Result := True;
  14459. end;
  14460. end;
  14461. end;
  14462. end;
  14463. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14464. begin
  14465. { we can skip all instructions not messing with the stack pointer }
  14466. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14467. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14468. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14469. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14470. ({(taicpu(hp1).ops=0) or }
  14471. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14472. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14473. ) and }
  14474. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14475. )
  14476. ) do
  14477. GetNextInstruction(hp1,hp1);
  14478. Result:=assigned(hp1);
  14479. end;
  14480. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14481. var
  14482. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14483. begin
  14484. Result:=false;
  14485. hp5:=nil;
  14486. hp6:=nil;
  14487. hp7:=nil;
  14488. hp8:=nil;
  14489. { replace
  14490. leal(q) x(<stackpointer>),<stackpointer>
  14491. <optional .seh_stackalloc ...>
  14492. <optional .seh_endprologue ...>
  14493. call procname
  14494. <optional NOP>
  14495. leal(q) -x(<stackpointer>),<stackpointer>
  14496. <optional VZEROUPPER>
  14497. ret
  14498. by
  14499. jmp procname
  14500. but do it only on level 4 because it destroys stack back traces
  14501. }
  14502. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14503. MatchOpType(taicpu(p),top_ref,top_reg) and
  14504. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14505. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14506. { the -8, -24, -40 are not required, but bail out early if possible,
  14507. higher values are unlikely }
  14508. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14509. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14510. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14511. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14512. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14513. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14514. GetNextInstruction(p, hp1) and
  14515. { Take a copy of hp1 }
  14516. SetAndTest(hp1, hp4) and
  14517. { trick to skip label }
  14518. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14519. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14520. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14521. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14522. SkipSimpleInstructions(hp1) and
  14523. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14524. GetNextInstruction(hp1, hp2) and
  14525. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14526. { skip nop instruction on win64 }
  14527. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14528. SetAndTest(hp2,hp6) and
  14529. GetNextInstruction(hp2,hp2) and
  14530. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14531. ) and
  14532. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14533. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14534. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14535. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14536. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14537. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14538. { Segment register will be NR_NO }
  14539. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14540. GetNextInstruction(hp2, hp3) and
  14541. { trick to skip label }
  14542. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14543. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14544. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14545. SetAndTest(hp3,hp5) and
  14546. GetNextInstruction(hp3,hp3) and
  14547. MatchInstruction(hp3,A_RET,[S_NO])
  14548. )
  14549. ) and
  14550. (taicpu(hp3).ops=0) then
  14551. begin
  14552. taicpu(hp1).opcode := A_JMP;
  14553. taicpu(hp1).is_jmp := true;
  14554. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14555. { search for the stackalloc directive and remove it }
  14556. hp7:=tai(p.next);
  14557. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14558. begin
  14559. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14560. begin
  14561. { sanity check }
  14562. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14563. Internalerror(2024012201);
  14564. hp8:=tai(hp7.next);
  14565. RemoveInstruction(tai(hp7));
  14566. hp7:=hp8;
  14567. break;
  14568. end
  14569. else
  14570. hp7:=tai(hp7.next);
  14571. end;
  14572. RemoveCurrentP(p, hp4);
  14573. RemoveInstruction(hp2);
  14574. RemoveInstruction(hp3);
  14575. { if there is a vzeroupper instruction then move it before the jmp }
  14576. if Assigned(hp5) then
  14577. begin
  14578. AsmL.Remove(hp5);
  14579. ASmL.InsertBefore(hp5,hp1)
  14580. end;
  14581. { remove nop on win64 }
  14582. if Assigned(hp6) then
  14583. RemoveInstruction(hp6);
  14584. Result:=true;
  14585. end;
  14586. end;
  14587. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14588. {$ifdef x86_64}
  14589. var
  14590. hp1, hp2, hp3, hp4, hp5: tai;
  14591. {$endif x86_64}
  14592. begin
  14593. Result:=false;
  14594. {$ifdef x86_64}
  14595. hp5:=nil;
  14596. { replace
  14597. push %rax
  14598. call procname
  14599. pop %rcx
  14600. ret
  14601. by
  14602. jmp procname
  14603. but do it only on level 4 because it destroys stack back traces
  14604. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14605. for all supported calling conventions
  14606. }
  14607. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14608. MatchOpType(taicpu(p),top_reg) and
  14609. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14610. GetNextInstruction(p, hp1) and
  14611. { Take a copy of hp1 }
  14612. SetAndTest(hp1, hp4) and
  14613. { trick to skip label }
  14614. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14615. SkipSimpleInstructions(hp1) and
  14616. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14617. GetNextInstruction(hp1, hp2) and
  14618. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14619. MatchOpType(taicpu(hp2),top_reg) and
  14620. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14621. GetNextInstruction(hp2, hp3) and
  14622. { trick to skip label }
  14623. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14624. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14625. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14626. SetAndTest(hp3,hp5) and
  14627. GetNextInstruction(hp3,hp3) and
  14628. MatchInstruction(hp3,A_RET,[S_NO])
  14629. )
  14630. ) and
  14631. (taicpu(hp3).ops=0) then
  14632. begin
  14633. taicpu(hp1).opcode := A_JMP;
  14634. taicpu(hp1).is_jmp := true;
  14635. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14636. RemoveCurrentP(p, hp4);
  14637. RemoveInstruction(hp2);
  14638. RemoveInstruction(hp3);
  14639. if Assigned(hp5) then
  14640. begin
  14641. AsmL.Remove(hp5);
  14642. ASmL.InsertBefore(hp5,hp1)
  14643. end;
  14644. Result:=true;
  14645. end;
  14646. {$endif x86_64}
  14647. end;
  14648. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14649. var
  14650. Value, RegName: string;
  14651. hp1: tai;
  14652. begin
  14653. Result:=false;
  14654. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14655. begin
  14656. case taicpu(p).oper[0]^.val of
  14657. 0:
  14658. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14659. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14660. (
  14661. { See if we can still convert the instruction }
  14662. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14663. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14664. ) then
  14665. begin
  14666. { change "mov $0,%reg" into "xor %reg,%reg" }
  14667. taicpu(p).opcode := A_XOR;
  14668. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14669. Result := True;
  14670. {$ifdef x86_64}
  14671. end
  14672. else if (taicpu(p).opsize = S_Q) then
  14673. begin
  14674. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14675. { The actual optimization }
  14676. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14677. taicpu(p).changeopsize(S_L);
  14678. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14679. Result := True;
  14680. end;
  14681. $1..$FFFFFFFF:
  14682. begin
  14683. { Code size reduction by J. Gareth "Kit" Moreton }
  14684. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14685. case taicpu(p).opsize of
  14686. S_Q:
  14687. begin
  14688. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14689. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14690. { The actual optimization }
  14691. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14692. taicpu(p).changeopsize(S_L);
  14693. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14694. Result := True;
  14695. end;
  14696. else
  14697. { Do nothing };
  14698. end;
  14699. {$endif x86_64}
  14700. end;
  14701. -1:
  14702. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14703. if (cs_opt_size in current_settings.optimizerswitches) and
  14704. (taicpu(p).opsize <> S_B) and
  14705. (
  14706. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14707. (
  14708. { See if we can still convert the instruction }
  14709. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14710. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14711. )
  14712. ) then
  14713. begin
  14714. { change "mov $-1,%reg" into "or $-1,%reg" }
  14715. { NOTES:
  14716. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14717. - This operation creates a false dependency on the register, so only do it when optimising for size
  14718. - 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
  14719. }
  14720. taicpu(p).opcode := A_OR;
  14721. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14722. Result := True;
  14723. end;
  14724. else
  14725. { Do nothing };
  14726. end;
  14727. end;
  14728. end;
  14729. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14730. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14731. begin
  14732. Result := False;
  14733. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14734. Exit;
  14735. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14736. so don't bother optimising }
  14737. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14738. Exit;
  14739. if (taicpu(p).oper[0]^.typ <> top_const) or
  14740. { If the value can fit into an 8-bit signed integer, a smaller
  14741. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14742. falls within this range }
  14743. (
  14744. (taicpu(p).oper[0]^.val > -128) and
  14745. (taicpu(p).oper[0]^.val <= 127)
  14746. ) then
  14747. Exit;
  14748. { If we're optimising for size, this is acceptable }
  14749. if (cs_opt_size in current_settings.optimizerswitches) then
  14750. Exit(True);
  14751. if (taicpu(p).oper[1]^.typ = top_reg) and
  14752. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14753. Exit(True);
  14754. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14755. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14756. Exit(True);
  14757. end;
  14758. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14759. var
  14760. hp1: tai;
  14761. Value: TCGInt;
  14762. begin
  14763. Result := False;
  14764. if MatchOpType(taicpu(p), top_const, top_reg) then
  14765. begin
  14766. { Detect:
  14767. andw x, %ax (0 <= x < $8000)
  14768. ...
  14769. movzwl %ax,%eax
  14770. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14771. }
  14772. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14773. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14774. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14775. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14776. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14777. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14778. begin
  14779. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14780. taicpu(hp1).opcode := A_CWDE;
  14781. taicpu(hp1).clearop(0);
  14782. taicpu(hp1).clearop(1);
  14783. taicpu(hp1).ops := 0;
  14784. { A change was made, but not with p, so don't set Result, but
  14785. notify the compiler that a change was made }
  14786. Include(OptsToCheck, aoc_ForceNewIteration);
  14787. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14788. end;
  14789. end;
  14790. { If "not x" is a power of 2 (popcnt = 1), change:
  14791. and $x, %reg/ref
  14792. To:
  14793. btr lb(x), %reg/ref
  14794. }
  14795. if IsBTXAcceptable(p) and
  14796. (
  14797. { Make sure a TEST doesn't follow that plays with the register }
  14798. not GetNextInstruction(p, hp1) or
  14799. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14800. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14801. ) then
  14802. begin
  14803. {$push}{$R-}{$Q-}
  14804. { Value is a sign-extended 32-bit integer - just correct it
  14805. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14806. checks to see if this operand is an immediate. }
  14807. Value := not taicpu(p).oper[0]^.val;
  14808. {$pop}
  14809. {$ifdef x86_64}
  14810. if taicpu(p).opsize = S_L then
  14811. {$endif x86_64}
  14812. Value := Value and $FFFFFFFF;
  14813. if (PopCnt(QWord(Value)) = 1) then
  14814. begin
  14815. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14816. taicpu(p).opcode := A_BTR;
  14817. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14818. Result := True;
  14819. Exit;
  14820. end;
  14821. end;
  14822. end;
  14823. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14824. begin
  14825. Result := False;
  14826. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14827. Exit;
  14828. { Convert:
  14829. movswl %ax,%eax -> cwtl
  14830. movslq %eax,%rax -> cdqe
  14831. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14832. refer to the same opcode and depends only on the assembler's
  14833. current operand-size attribute. [Kit]
  14834. }
  14835. with taicpu(p) do
  14836. case opsize of
  14837. S_WL:
  14838. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14839. begin
  14840. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14841. opcode := A_CWDE;
  14842. clearop(0);
  14843. clearop(1);
  14844. ops := 0;
  14845. Result := True;
  14846. end;
  14847. {$ifdef x86_64}
  14848. S_LQ:
  14849. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14850. begin
  14851. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14852. opcode := A_CDQE;
  14853. clearop(0);
  14854. clearop(1);
  14855. ops := 0;
  14856. Result := True;
  14857. end;
  14858. {$endif x86_64}
  14859. else
  14860. ;
  14861. end;
  14862. end;
  14863. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14864. var
  14865. hp1, hp2: tai;
  14866. IdentityMask, Shift: TCGInt;
  14867. LimitSize: Topsize;
  14868. DoNotMerge: Boolean;
  14869. begin
  14870. Result := False;
  14871. { All these optimisations work on "shr const,%reg" }
  14872. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14873. Exit;
  14874. DoNotMerge := False;
  14875. Shift := taicpu(p).oper[0]^.val;
  14876. LimitSize := taicpu(p).opsize;
  14877. hp1 := p;
  14878. repeat
  14879. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14880. Break;
  14881. { Detect:
  14882. shr x, %reg
  14883. and y, %reg
  14884. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14885. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14886. }
  14887. case taicpu(hp1).opcode of
  14888. A_AND:
  14889. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14890. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14891. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14892. begin
  14893. { Make sure the FLAGS register isn't in use }
  14894. TransferUsedRegs(TmpUsedRegs);
  14895. hp2 := p;
  14896. repeat
  14897. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14898. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14899. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14900. begin
  14901. { Generate the identity mask }
  14902. case taicpu(p).opsize of
  14903. S_B:
  14904. IdentityMask := $FF shr Shift;
  14905. S_W:
  14906. IdentityMask := $FFFF shr Shift;
  14907. S_L:
  14908. IdentityMask := $FFFFFFFF shr Shift;
  14909. {$ifdef x86_64}
  14910. S_Q:
  14911. { We need to force the operands to be unsigned 64-bit
  14912. integers otherwise the wrong value is generated }
  14913. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14914. {$endif x86_64}
  14915. else
  14916. InternalError(2022081501);
  14917. end;
  14918. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14919. begin
  14920. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14921. { All the possible 1 bits are covered, so we can remove the AND }
  14922. hp2 := tai(hp1.Previous);
  14923. RemoveInstruction(hp1);
  14924. { p wasn't actually changed, so don't set Result to True,
  14925. but a change was nonetheless made elsewhere }
  14926. Include(OptsToCheck, aoc_ForceNewIteration);
  14927. { Do another pass in case other AND or MOVZX instructions
  14928. follow }
  14929. hp1 := hp2;
  14930. Continue;
  14931. end;
  14932. end;
  14933. end;
  14934. A_TEST, A_CMP, A_Jcc:
  14935. { Skip over conditional jumps and relevant comparisons }
  14936. Continue;
  14937. A_MOVZX:
  14938. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14939. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14940. begin
  14941. { Since the original register is being read as is, subsequent
  14942. SHRs must not be merged at this point }
  14943. DoNotMerge := True;
  14944. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14945. begin
  14946. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14947. begin
  14948. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14949. { All the possible 1 bits are covered, so we can remove the AND }
  14950. hp2 := tai(hp1.Previous);
  14951. RemoveInstruction(hp1);
  14952. hp1 := hp2;
  14953. end
  14954. else { Different register target }
  14955. begin
  14956. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14957. taicpu(hp1).opcode := A_MOV;
  14958. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14959. case taicpu(hp1).opsize of
  14960. S_BW:
  14961. taicpu(hp1).opsize := S_W;
  14962. S_BL, S_WL:
  14963. taicpu(hp1).opsize := S_L;
  14964. else
  14965. InternalError(2022081503);
  14966. end;
  14967. end;
  14968. end
  14969. else if (Shift > 0) and
  14970. (taicpu(p).opsize = S_W) and
  14971. (taicpu(hp1).opsize = S_WL) and
  14972. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14973. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14974. begin
  14975. { Detect:
  14976. shr x, %ax (x > 0)
  14977. ...
  14978. movzwl %ax,%eax
  14979. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14980. }
  14981. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14982. taicpu(hp1).opcode := A_CWDE;
  14983. taicpu(hp1).clearop(0);
  14984. taicpu(hp1).clearop(1);
  14985. taicpu(hp1).ops := 0;
  14986. end;
  14987. { Move onto the next instruction }
  14988. Continue;
  14989. end;
  14990. A_SHL, A_SAL, A_SHR:
  14991. if (taicpu(hp1).opsize <= LimitSize) and
  14992. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14993. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14994. begin
  14995. { Make sure the sizes don't exceed the register size limit
  14996. (measured by the shift value falling below the limit) }
  14997. if taicpu(hp1).opsize < LimitSize then
  14998. LimitSize := taicpu(hp1).opsize;
  14999. if taicpu(hp1).opcode = A_SHR then
  15000. Inc(Shift, taicpu(hp1).oper[0]^.val)
  15001. else
  15002. begin
  15003. Dec(Shift, taicpu(hp1).oper[0]^.val);
  15004. DoNotMerge := True;
  15005. end;
  15006. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  15007. Break;
  15008. { Since we've established that the combined shift is within
  15009. limits, we can actually combine the adjacent SHR
  15010. instructions even if they're different sizes }
  15011. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  15012. begin
  15013. hp2 := tai(hp1.Previous);
  15014. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  15015. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  15016. RemoveInstruction(hp1);
  15017. hp1 := hp2;
  15018. end;
  15019. { Move onto the next instruction }
  15020. Continue;
  15021. end;
  15022. else
  15023. { If the register isn't actually modified, move onto the next instruction,
  15024. but set DoNotMerge to True since the register is being read }
  15025. if (
  15026. { Under -O2 and below, GetNextInstructionUsingReg only returns
  15027. the next instruction, whether or not it contains the register }
  15028. (cs_opt_level3 in current_settings.optimizerswitches) or
  15029. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1)
  15030. ) and not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  15031. begin
  15032. DoNotMerge := True;
  15033. Continue;
  15034. end;
  15035. end;
  15036. Break;
  15037. until False;
  15038. { Detect the following (looking backwards):
  15039. shr %cl,%reg
  15040. shr x, %reg
  15041. Swap the two SHR instructions to minimise a pipeline stall.
  15042. }
  15043. if GetLastInstruction(p, hp1) and
  15044. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15045. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15046. { First operand will be %cl }
  15047. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15048. { Just to be sure }
  15049. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15050. begin
  15051. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15052. { Moving the entries this way ensures the register tracking remains correct }
  15053. Asml.Remove(p);
  15054. Asml.InsertBefore(p, hp1);
  15055. p := hp1;
  15056. { Don't set Result to True because the current instruction is now
  15057. "shr %cl,%reg" and there's nothing more we can do with it }
  15058. end;
  15059. end;
  15060. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15061. var
  15062. hp1, hp2: tai;
  15063. Opposite, SecondOpposite: TAsmOp;
  15064. NewCond: TAsmCond;
  15065. begin
  15066. Result := False;
  15067. { Change:
  15068. add/sub 128,(dest)
  15069. To:
  15070. sub/add -128,(dest)
  15071. This generaally takes fewer bytes to encode because -128 can be stored
  15072. in a signed byte, whereas +128 cannot.
  15073. }
  15074. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15075. begin
  15076. if taicpu(p).opcode = A_ADD then
  15077. Opposite := A_SUB
  15078. else
  15079. Opposite := A_ADD;
  15080. { Be careful if the flags are in use, because the CF flag inverts
  15081. when changing from ADD to SUB and vice versa }
  15082. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15083. GetNextInstruction(p, hp1) then
  15084. begin
  15085. TransferUsedRegs(TmpUsedRegs);
  15086. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15087. hp2 := hp1;
  15088. { Scan ahead to check if everything's safe }
  15089. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15090. begin
  15091. if (hp1.typ <> ait_instruction) then
  15092. { Probably unsafe since the flags are still in use }
  15093. Exit;
  15094. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15095. { Stop searching at an unconditional jump }
  15096. Break;
  15097. if not
  15098. (
  15099. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15100. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15101. ) and
  15102. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15103. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15104. Exit;
  15105. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15106. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15107. { Move to the next instruction }
  15108. GetNextInstruction(hp1, hp1);
  15109. end;
  15110. while Assigned(hp2) and (hp2 <> hp1) do
  15111. begin
  15112. NewCond := C_None;
  15113. case taicpu(hp2).condition of
  15114. C_A, C_NBE:
  15115. NewCond := C_BE;
  15116. C_B, C_C, C_NAE:
  15117. NewCond := C_AE;
  15118. C_AE, C_NB, C_NC:
  15119. NewCond := C_B;
  15120. C_BE, C_NA:
  15121. NewCond := C_A;
  15122. else
  15123. { No change needed };
  15124. end;
  15125. if NewCond <> C_None then
  15126. begin
  15127. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15128. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15129. taicpu(hp2).condition := NewCond;
  15130. end
  15131. else
  15132. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15133. begin
  15134. { Because of the flipping of the carry bit, to ensure
  15135. the operation remains equivalent, ADC becomes SBB
  15136. and vice versa, and the constant is not-inverted.
  15137. If multiple ADCs or SBBs appear in a row, each one
  15138. changed causes the carry bit to invert, so they all
  15139. need to be flipped }
  15140. if taicpu(hp2).opcode = A_ADC then
  15141. SecondOpposite := A_SBB
  15142. else
  15143. SecondOpposite := A_ADC;
  15144. if taicpu(hp2).oper[0]^.typ <> top_const then
  15145. { Should have broken out of this optimisation already }
  15146. InternalError(2021112901);
  15147. 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]^) + ' -> ' +
  15148. 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);
  15149. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15150. taicpu(hp2).opcode := SecondOpposite;
  15151. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15152. end;
  15153. { Move to the next instruction }
  15154. GetNextInstruction(hp2, hp2);
  15155. end;
  15156. if (hp2 <> hp1) then
  15157. InternalError(2021111501);
  15158. end;
  15159. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15160. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15161. taicpu(p).opcode := Opposite;
  15162. taicpu(p).oper[0]^.val := -128;
  15163. { No further optimisations can be made on this instruction, so move
  15164. onto the next one to save time }
  15165. p := tai(p.Next);
  15166. UpdateUsedRegs(p);
  15167. Result := True;
  15168. Exit;
  15169. end;
  15170. { Detect:
  15171. add/sub %reg2,(dest)
  15172. add/sub x, (dest)
  15173. (dest can be a register or a reference)
  15174. Swap the instructions to minimise a pipeline stall. This reverses the
  15175. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15176. optimisations could be made.
  15177. }
  15178. if (taicpu(p).oper[0]^.typ = top_reg) and
  15179. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15180. (
  15181. (
  15182. (taicpu(p).oper[1]^.typ = top_reg) and
  15183. { We can try searching further ahead if we're writing to a register }
  15184. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15185. ) or
  15186. (
  15187. (taicpu(p).oper[1]^.typ = top_ref) and
  15188. GetNextInstruction(p, hp1)
  15189. )
  15190. ) and
  15191. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15192. (taicpu(hp1).oper[0]^.typ = top_const) and
  15193. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15194. begin
  15195. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15196. TransferUsedRegs(TmpUsedRegs);
  15197. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15198. hp2 := p;
  15199. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15200. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15201. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15202. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15203. begin
  15204. asml.remove(hp1);
  15205. asml.InsertBefore(hp1, p);
  15206. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15207. Result := True;
  15208. end;
  15209. end;
  15210. end;
  15211. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15212. var
  15213. hp1: tai;
  15214. begin
  15215. Result:=false;
  15216. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15217. while GetNextInstruction(p, hp1) and
  15218. TrySwapMovCmp(p, hp1) do
  15219. begin
  15220. if MatchInstruction(hp1, A_MOV, []) then
  15221. begin
  15222. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15223. begin
  15224. { A little hacky, but since CMP doesn't read the flags, only
  15225. modify them, it's safe if they get scrambled by MOV -> XOR }
  15226. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15227. Result := PostPeepholeOptMov(hp1);
  15228. {$ifdef x86_64}
  15229. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15230. { Used to shrink instruction size }
  15231. PostPeepholeOptXor(hp1);
  15232. {$endif x86_64}
  15233. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15234. end
  15235. else
  15236. begin
  15237. Result := PostPeepholeOptMov(hp1);
  15238. {$ifdef x86_64}
  15239. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15240. { Used to shrink instruction size }
  15241. PostPeepholeOptXor(hp1);
  15242. {$endif x86_64}
  15243. end;
  15244. end;
  15245. { Enabling this flag is actually a null operation, but it marks
  15246. the code as 'modified' during this pass }
  15247. Include(OptsToCheck, aoc_ForceNewIteration);
  15248. end;
  15249. { change "cmp $0, %reg" to "test %reg, %reg" }
  15250. if MatchOpType(taicpu(p),top_const,top_reg) and
  15251. (taicpu(p).oper[0]^.val = 0) then
  15252. begin
  15253. taicpu(p).opcode := A_TEST;
  15254. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15255. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15256. Result:=true;
  15257. end;
  15258. end;
  15259. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15260. var
  15261. IsTestConstX, IsValid : Boolean;
  15262. hp1,hp2 : tai;
  15263. begin
  15264. Result:=false;
  15265. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15266. if (taicpu(p).opcode = A_TEST) then
  15267. while GetNextInstruction(p, hp1) and
  15268. TrySwapMovCmp(p, hp1) do
  15269. begin
  15270. if MatchInstruction(hp1, A_MOV, []) then
  15271. begin
  15272. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15273. begin
  15274. { A little hacky, but since TEST doesn't read the flags, only
  15275. modify them, it's safe if they get scrambled by MOV -> XOR }
  15276. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15277. Result := PostPeepholeOptMov(hp1);
  15278. {$ifdef x86_64}
  15279. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15280. { Used to shrink instruction size }
  15281. PostPeepholeOptXor(hp1);
  15282. {$endif x86_64}
  15283. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15284. end
  15285. else
  15286. begin
  15287. Result := PostPeepholeOptMov(hp1);
  15288. {$ifdef x86_64}
  15289. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15290. { Used to shrink instruction size }
  15291. PostPeepholeOptXor(hp1);
  15292. {$endif x86_64}
  15293. end;
  15294. end;
  15295. { Enabling this flag is actually a null operation, but it marks
  15296. the code as 'modified' during this pass }
  15297. Include(OptsToCheck, aoc_ForceNewIteration);
  15298. end;
  15299. { If x is a power of 2 (popcnt = 1), change:
  15300. or $x, %reg/ref
  15301. To:
  15302. bts lb(x), %reg/ref
  15303. }
  15304. if (taicpu(p).opcode = A_OR) and
  15305. IsBTXAcceptable(p) and
  15306. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15307. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15308. (
  15309. { Don't optimise if a test instruction follows }
  15310. not GetNextInstruction(p, hp1) or
  15311. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15312. ) then
  15313. begin
  15314. 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);
  15315. taicpu(p).opcode := A_BTS;
  15316. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15317. Result := True;
  15318. Exit;
  15319. end;
  15320. { If x is a power of 2 (popcnt = 1), change:
  15321. test $x, %reg/ref
  15322. je / sete / cmove (or jne / setne)
  15323. To:
  15324. bt lb(x), %reg/ref
  15325. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15326. }
  15327. if (taicpu(p).opcode = A_TEST) and
  15328. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15329. (taicpu(p).oper[0]^.typ = top_const) and
  15330. (
  15331. (cs_opt_size in current_settings.optimizerswitches) or
  15332. (
  15333. (taicpu(p).oper[1]^.typ = top_reg) and
  15334. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15335. ) or
  15336. (
  15337. (taicpu(p).oper[1]^.typ <> top_reg) and
  15338. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15339. )
  15340. ) and
  15341. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15342. { For sizes less than S_L, the byte size is equal or larger with BT,
  15343. so don't bother optimising }
  15344. (taicpu(p).opsize >= S_L) then
  15345. begin
  15346. IsValid := True;
  15347. { Check the next set of instructions, watching the FLAGS register
  15348. and the conditions used }
  15349. TransferUsedRegs(TmpUsedRegs);
  15350. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15351. hp1 := p;
  15352. hp2 := nil;
  15353. while GetNextInstruction(hp1, hp1) do
  15354. begin
  15355. if not Assigned(hp2) then
  15356. { The first instruction after TEST }
  15357. hp2 := hp1;
  15358. if (hp1.typ <> ait_instruction) then
  15359. begin
  15360. { If the flags are no longer in use, everything is fine }
  15361. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15362. IsValid := False;
  15363. Break;
  15364. end;
  15365. case taicpu(hp1).condition of
  15366. C_None:
  15367. begin
  15368. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15369. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15370. { Something is not quite normal, so play safe and don't change }
  15371. IsValid := False;
  15372. Break;
  15373. end;
  15374. C_E, C_Z, C_NE, C_NZ:
  15375. { This is fine };
  15376. else
  15377. begin
  15378. { Unsupported condition }
  15379. IsValid := False;
  15380. Break;
  15381. end;
  15382. end;
  15383. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15384. end;
  15385. if IsValid then
  15386. begin
  15387. while hp2 <> hp1 do
  15388. begin
  15389. case taicpu(hp2).condition of
  15390. C_Z, C_E:
  15391. taicpu(hp2).condition := C_NC;
  15392. C_NZ, C_NE:
  15393. taicpu(hp2).condition := C_C;
  15394. else
  15395. { Should not get this by this point }
  15396. InternalError(2022110701);
  15397. end;
  15398. GetNextInstruction(hp2, hp2);
  15399. end;
  15400. 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);
  15401. taicpu(p).opcode := A_BT;
  15402. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15403. Result := True;
  15404. Exit;
  15405. end;
  15406. end;
  15407. { removes the line marked with (x) from the sequence
  15408. and/or/xor/add/sub/... $x, %y
  15409. test/or %y, %y | test $-1, %y (x)
  15410. j(n)z _Label
  15411. as the first instruction already adjusts the ZF
  15412. %y operand may also be a reference }
  15413. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15414. MatchOperand(taicpu(p).oper[0]^,-1);
  15415. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15416. GetLastInstruction(p, hp1) and
  15417. (tai(hp1).typ = ait_instruction) and
  15418. GetNextInstruction(p,hp2) and
  15419. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15420. case taicpu(hp1).opcode Of
  15421. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15422. { These two instructions set the zero flag if the result is zero }
  15423. A_POPCNT, A_LZCNT:
  15424. begin
  15425. if (
  15426. { With POPCNT, an input of zero will set the zero flag
  15427. because the population count of zero is zero }
  15428. (taicpu(hp1).opcode = A_POPCNT) and
  15429. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15430. (
  15431. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15432. { Faster than going through the second half of the 'or'
  15433. condition below }
  15434. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15435. )
  15436. ) or (
  15437. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15438. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15439. { and in case of carry for A(E)/B(E)/C/NC }
  15440. (
  15441. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15442. (
  15443. (taicpu(hp1).opcode <> A_ADD) and
  15444. (taicpu(hp1).opcode <> A_SUB) and
  15445. (taicpu(hp1).opcode <> A_LZCNT)
  15446. )
  15447. )
  15448. ) then
  15449. begin
  15450. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15451. RemoveCurrentP(p, hp2);
  15452. Result:=true;
  15453. Exit;
  15454. end;
  15455. end;
  15456. A_SHL, A_SAL, A_SHR, A_SAR:
  15457. begin
  15458. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15459. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15460. { therefore, it's only safe to do this optimization for }
  15461. { shifts by a (nonzero) constant }
  15462. (taicpu(hp1).oper[0]^.typ = top_const) and
  15463. (taicpu(hp1).oper[0]^.val <> 0) and
  15464. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15465. { and in case of carry for A(E)/B(E)/C/NC }
  15466. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15467. begin
  15468. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15469. RemoveCurrentP(p, hp2);
  15470. Result:=true;
  15471. Exit;
  15472. end;
  15473. end;
  15474. A_DEC, A_INC, A_NEG:
  15475. begin
  15476. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15477. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15478. { and in case of carry for A(E)/B(E)/C/NC }
  15479. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15480. begin
  15481. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15482. RemoveCurrentP(p, hp2);
  15483. Result:=true;
  15484. Exit;
  15485. end;
  15486. end;
  15487. A_ANDN, A_BZHI:
  15488. begin
  15489. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15490. { Only the zero and sign flags are consistent with what the result is }
  15491. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15492. begin
  15493. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15494. RemoveCurrentP(p, hp2);
  15495. Result:=true;
  15496. Exit;
  15497. end;
  15498. end;
  15499. A_BEXTR:
  15500. begin
  15501. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15502. { Only the zero flag is set }
  15503. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15504. begin
  15505. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15506. RemoveCurrentP(p, hp2);
  15507. Result:=true;
  15508. Exit;
  15509. end;
  15510. end;
  15511. else
  15512. ;
  15513. end; { case }
  15514. { change "test $-1,%reg" into "test %reg,%reg" }
  15515. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15516. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15517. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15518. if MatchInstruction(p, A_OR, []) and
  15519. { Can only match if they're both registers }
  15520. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15521. begin
  15522. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15523. taicpu(p).opcode := A_TEST;
  15524. { No need to set Result to True, as we've done all the optimisations we can }
  15525. end;
  15526. end;
  15527. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15528. var
  15529. hp1,hp3 : tai;
  15530. {$ifndef x86_64}
  15531. hp2 : taicpu;
  15532. {$endif x86_64}
  15533. begin
  15534. Result:=false;
  15535. hp3:=nil;
  15536. {$ifndef x86_64}
  15537. { don't do this on modern CPUs, this really hurts them due to
  15538. broken call/ret pairing }
  15539. if (current_settings.optimizecputype < cpu_Pentium2) and
  15540. not(cs_create_pic in current_settings.moduleswitches) and
  15541. GetNextInstruction(p, hp1) and
  15542. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15543. MatchOpType(taicpu(hp1),top_ref) and
  15544. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15545. begin
  15546. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15547. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15548. InsertLLItem(p.previous, p, hp2);
  15549. taicpu(p).opcode := A_JMP;
  15550. taicpu(p).is_jmp := true;
  15551. RemoveInstruction(hp1);
  15552. Result:=true;
  15553. end
  15554. else
  15555. {$endif x86_64}
  15556. { replace
  15557. call procname
  15558. ret
  15559. by
  15560. jmp procname
  15561. but do it only on level 4 because it destroys stack back traces
  15562. else if the subroutine is marked as no return, remove the ret
  15563. }
  15564. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15565. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15566. GetNextInstruction(p, hp1) and
  15567. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15568. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15569. SetAndTest(hp1,hp3) and
  15570. GetNextInstruction(hp1,hp1) and
  15571. MatchInstruction(hp1,A_RET,[S_NO])
  15572. )
  15573. ) and
  15574. (taicpu(hp1).ops=0) then
  15575. begin
  15576. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15577. { we might destroy stack alignment here if we do not do a call }
  15578. (target_info.stackalign<=sizeof(SizeUInt)) then
  15579. begin
  15580. taicpu(p).opcode := A_JMP;
  15581. taicpu(p).is_jmp := true;
  15582. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15583. end
  15584. else
  15585. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15586. RemoveInstruction(hp1);
  15587. if Assigned(hp3) then
  15588. begin
  15589. AsmL.Remove(hp3);
  15590. AsmL.InsertBefore(hp3,p)
  15591. end;
  15592. Result:=true;
  15593. end;
  15594. end;
  15595. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15596. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15597. begin
  15598. case OpSize of
  15599. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15600. Result := (Val <= $FF) and (Val >= -128);
  15601. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15602. Result := (Val <= $FFFF) and (Val >= -32768);
  15603. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15604. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15605. else
  15606. Result := True;
  15607. end;
  15608. end;
  15609. var
  15610. hp1, hp2 : tai;
  15611. SizeChange: Boolean;
  15612. PreMessage: string;
  15613. begin
  15614. Result := False;
  15615. if (taicpu(p).oper[0]^.typ = top_reg) and
  15616. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15617. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15618. begin
  15619. { Change (using movzbl %al,%eax as an example):
  15620. movzbl %al, %eax movzbl %al, %eax
  15621. cmpl x, %eax testl %eax,%eax
  15622. To:
  15623. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15624. movzbl %al, %eax movzbl %al, %eax
  15625. Smaller instruction and minimises pipeline stall as the CPU
  15626. doesn't have to wait for the register to get zero-extended. [Kit]
  15627. Also allow if the smaller of the two registers is being checked,
  15628. as this still removes the false dependency.
  15629. }
  15630. if
  15631. (
  15632. (
  15633. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15634. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15635. ) or (
  15636. { If MatchOperand returns True, they must both be registers }
  15637. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15638. )
  15639. ) and
  15640. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15641. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15642. begin
  15643. 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);
  15644. asml.Remove(hp1);
  15645. asml.InsertBefore(hp1, p);
  15646. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15647. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15648. begin
  15649. taicpu(hp1).opcode := A_TEST;
  15650. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15651. end;
  15652. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15653. case taicpu(p).opsize of
  15654. S_BW, S_BL:
  15655. begin
  15656. SizeChange := taicpu(hp1).opsize <> S_B;
  15657. taicpu(hp1).changeopsize(S_B);
  15658. end;
  15659. S_WL:
  15660. begin
  15661. SizeChange := taicpu(hp1).opsize <> S_W;
  15662. taicpu(hp1).changeopsize(S_W);
  15663. end
  15664. else
  15665. InternalError(2020112701);
  15666. end;
  15667. UpdateUsedRegs(tai(p.Next));
  15668. { Check if the register is used aferwards - if not, we can
  15669. remove the movzx instruction completely }
  15670. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15671. begin
  15672. { Hp1 is a better position than p for debugging purposes }
  15673. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15674. RemoveCurrentp(p, hp1);
  15675. Result := True;
  15676. end;
  15677. if SizeChange then
  15678. DebugMsg(SPeepholeOptimization + PreMessage +
  15679. 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)
  15680. else
  15681. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15682. Exit;
  15683. end;
  15684. { Change (using movzwl %ax,%eax as an example):
  15685. movzwl %ax, %eax
  15686. movb %al, (dest) (Register is smaller than read register in movz)
  15687. To:
  15688. movb %al, (dest) (Move one back to avoid a false dependency)
  15689. movzwl %ax, %eax
  15690. }
  15691. if (taicpu(hp1).opcode = A_MOV) and
  15692. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15693. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15694. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15695. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15696. begin
  15697. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15698. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15699. asml.Remove(hp1);
  15700. asml.InsertBefore(hp1, p);
  15701. if taicpu(hp1).oper[1]^.typ = top_reg then
  15702. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15703. { Check if the register is used aferwards - if not, we can
  15704. remove the movzx instruction completely }
  15705. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15706. begin
  15707. { Hp1 is a better position than p for debugging purposes }
  15708. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15709. RemoveCurrentp(p, hp1);
  15710. Result := True;
  15711. end;
  15712. Exit;
  15713. end;
  15714. end;
  15715. end;
  15716. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15717. var
  15718. hp1: tai;
  15719. {$ifdef x86_64}
  15720. PreMessage, RegName: string;
  15721. {$endif x86_64}
  15722. begin
  15723. Result := False;
  15724. { If x is a power of 2 (popcnt = 1), change:
  15725. xor $x, %reg/ref
  15726. To:
  15727. btc lb(x), %reg/ref
  15728. }
  15729. if IsBTXAcceptable(p) and
  15730. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15731. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15732. (
  15733. { Don't optimise if a test instruction follows }
  15734. not GetNextInstruction(p, hp1) or
  15735. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15736. ) then
  15737. begin
  15738. 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);
  15739. taicpu(p).opcode := A_BTC;
  15740. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15741. Result := True;
  15742. Exit;
  15743. end;
  15744. {$ifdef x86_64}
  15745. { Code size reduction by J. Gareth "Kit" Moreton }
  15746. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15747. as this removes the REX prefix }
  15748. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15749. Exit;
  15750. if taicpu(p).oper[0]^.typ <> top_reg then
  15751. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15752. InternalError(2018011500);
  15753. case taicpu(p).opsize of
  15754. S_Q:
  15755. begin
  15756. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15757. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15758. { The actual optimization }
  15759. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15760. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15761. taicpu(p).changeopsize(S_L);
  15762. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15763. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15764. end;
  15765. else
  15766. ;
  15767. end;
  15768. {$endif x86_64}
  15769. end;
  15770. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15771. var
  15772. XReg: TRegister;
  15773. begin
  15774. Result := False;
  15775. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15776. Smaller encoding and slightly faster on some platforms (also works for
  15777. ZMM-sized registers) }
  15778. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15779. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15780. begin
  15781. XReg := taicpu(p).oper[0]^.reg;
  15782. if (taicpu(p).oper[1]^.reg = XReg) then
  15783. begin
  15784. taicpu(p).changeopsize(S_XMM);
  15785. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15786. if (cs_opt_size in current_settings.optimizerswitches) then
  15787. begin
  15788. { Change input registers to %xmm0 to reduce size. Note that
  15789. there's a risk of a false dependency doing this, so only
  15790. optimise for size here }
  15791. XReg := NR_XMM0;
  15792. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15793. end
  15794. else
  15795. begin
  15796. setsubreg(XReg, R_SUBMMX);
  15797. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15798. end;
  15799. taicpu(p).oper[0]^.reg := XReg;
  15800. taicpu(p).oper[1]^.reg := XReg;
  15801. Result := True;
  15802. end;
  15803. end;
  15804. end;
  15805. function TX86AsmOptimizer.PostPeepholeOptRET(var p: tai): Boolean;
  15806. var
  15807. hp1, p_new: tai;
  15808. begin
  15809. Result := False;
  15810. { Check for:
  15811. ret
  15812. .Lbl:
  15813. ret
  15814. Remove first 'ret'
  15815. }
  15816. if GetNextInstruction(p, hp1) and
  15817. { Remember where the label is }
  15818. SetAndTest(hp1, p_new) and
  15819. (hp1.typ in [ait_align, ait_label]) and
  15820. SkipLabels(hp1, hp1) and
  15821. MatchInstruction(hp1, A_RET, []) and
  15822. { To be safe, make sure the RET instructions are identical }
  15823. (taicpu(p).ops = taicpu(hp1).ops) and
  15824. (
  15825. (taicpu(p).ops = 0) or
  15826. (
  15827. (taicpu(p).ops = 1) and
  15828. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^)
  15829. )
  15830. ) then
  15831. begin
  15832. DebugMsg(SPeepholeOptimization + 'Removed superfluous RET', p);
  15833. UpdateUsedRegs(tai(p.Next));
  15834. RemoveCurrentP(p, p_new);
  15835. Result := True;
  15836. Exit;
  15837. end;
  15838. end;
  15839. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15840. var
  15841. OperIdx: Integer;
  15842. begin
  15843. for OperIdx := 0 to p.ops - 1 do
  15844. if p.oper[OperIdx]^.typ = top_ref then
  15845. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15846. end;
  15847. end.