aoptx86.pas 719 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957
  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. private
  73. function SkipSimpleInstructions(var hp1: tai): Boolean;
  74. protected
  75. class function IsMOVZXAcceptable: Boolean; static; inline;
  76. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  77. { Attempts to allocate a volatile integer register for use between p and hp,
  78. using AUsedRegs for the current register usage information. Returns NR_NO
  79. if no free register could be found }
  80. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  81. { Attempts to allocate a volatile MM 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 GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  86. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  87. { checks whether reading the value in reg1 depends on the value of reg2. This
  88. is very similar to SuperRegisterEquals, except it takes into account that
  89. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  90. depend on the value in AH). }
  91. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  92. { Replaces all references to AOldReg in a memory reference to ANewReg }
  93. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an operand to ANewReg }
  95. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  96. { Replaces all references to AOldReg in an instruction to ANewReg,
  97. except where the register is being written }
  98. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  99. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  100. or writes to a global symbol }
  101. class function IsRefSafe(const ref: PReference): Boolean; static;
  102. { Returns true if the given MOV instruction can be safely converted to CMOV }
  103. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  104. { Like UpdateUsedRegs, but ignores deallocations }
  105. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  106. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  107. class function IsBTXAcceptable(p : tai) : boolean; static;
  108. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  109. conversion was successful }
  110. function ConvertLEA(const p : taicpu): Boolean;
  111. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  112. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  113. procedure DebugMsg(const s : string; p : tai);inline;
  114. class function IsExitCode(p : tai) : boolean; static;
  115. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  116. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  117. procedure RemoveLastDeallocForFuncRes(p : tai);
  118. function DoArithCombineOpt(var p : tai) : Boolean;
  119. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  120. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  121. function PrePeepholeOptSxx(var p : tai) : boolean;
  122. function PrePeepholeOptIMUL(var p : tai) : boolean;
  123. function PrePeepholeOptAND(var p : tai) : boolean;
  124. function OptPass1Test(var p: tai): boolean;
  125. function OptPass1Add(var p: tai): boolean;
  126. function OptPass1AND(var p : tai) : boolean;
  127. function OptPass1_V_MOVAP(var p : tai) : boolean;
  128. function OptPass1VOP(var p : tai) : boolean;
  129. function OptPass1MOV(var p : tai) : boolean;
  130. function OptPass1Movx(var p : tai) : boolean;
  131. function OptPass1MOVXX(var p : tai) : boolean;
  132. function OptPass1OP(var p : tai) : boolean;
  133. function OptPass1LEA(var p : tai) : boolean;
  134. function OptPass1Sub(var p : tai) : boolean;
  135. function OptPass1SHLSAL(var p : tai) : boolean;
  136. function OptPass1SHR(var p : tai) : boolean;
  137. function OptPass1FSTP(var p : tai) : boolean;
  138. function OptPass1FLD(var p : tai) : boolean;
  139. function OptPass1Cmp(var p : tai) : boolean;
  140. function OptPass1PXor(var p : tai) : boolean;
  141. function OptPass1VPXor(var p: tai): boolean;
  142. function OptPass1Imul(var p : tai) : boolean;
  143. function OptPass1Jcc(var p : tai) : boolean;
  144. function OptPass1SHXX(var p: tai): boolean;
  145. function OptPass1VMOVDQ(var p: tai): Boolean;
  146. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  147. function OptPass1STCCLC(var p: tai): Boolean;
  148. function OptPass2STCCLC(var p: tai): Boolean;
  149. function OptPass2Movx(var p : tai): Boolean;
  150. function OptPass2MOV(var p : tai) : boolean;
  151. function OptPass2Imul(var p : tai) : boolean;
  152. function OptPass2Jmp(var p : tai) : boolean;
  153. function OptPass2Jcc(var p : tai) : boolean;
  154. function OptPass2Lea(var p: tai): Boolean;
  155. function OptPass2SUB(var p: tai): Boolean;
  156. function OptPass2ADD(var p : tai): Boolean;
  157. function OptPass2SETcc(var p : tai) : boolean;
  158. function OptPass2Cmp(var p: tai): Boolean;
  159. function OptPass2Test(var p: tai): Boolean;
  160. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  161. function PostPeepholeOptMov(var p : tai) : Boolean;
  162. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  163. function PostPeepholeOptXor(var p : tai) : Boolean;
  164. function PostPeepholeOptAnd(var p : tai) : boolean;
  165. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  166. function PostPeepholeOptCmp(var p : tai) : Boolean;
  167. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  168. function PostPeepholeOptCall(var p : tai) : Boolean;
  169. function PostPeepholeOptLea(var p : tai) : Boolean;
  170. function PostPeepholeOptPush(var p: tai): Boolean;
  171. function PostPeepholeOptShr(var p : tai) : boolean;
  172. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  173. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  174. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  175. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  176. function TrySwapMovOp(var p, hp1: tai): Boolean;
  177. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  178. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  179. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  180. { Processor-dependent reference optimisation }
  181. class procedure OptimizeRefs(var p: taicpu); static;
  182. end;
  183. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  184. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  185. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  186. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  187. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  188. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  189. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  190. {$if max_operands>2}
  191. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  192. {$endif max_operands>2}
  193. function RefsEqual(const r1, r2: treference): boolean;
  194. { Note that Result is set to True if the references COULD overlap but the
  195. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  196. might still overlap because %reg2 could be equal to %reg1-4 }
  197. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  198. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  199. { returns true, if ref is a reference using only the registers passed as base and index
  200. and having an offset }
  201. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  202. implementation
  203. uses
  204. cutils,verbose,
  205. systems,
  206. globals,
  207. cpuinfo,
  208. procinfo,
  209. paramgr,
  210. aasmbase,
  211. aoptbase,aoptutils,
  212. symconst,symsym,
  213. cgx86,
  214. itcpugas;
  215. {$ifndef 8086}
  216. const
  217. MAX_CMOV_INSTRUCTIONS = 4;
  218. MAX_CMOV_REGISTERS = 8;
  219. type
  220. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  221. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  222. tsProcessed);
  223. { For OptPass2Jcc }
  224. TCMOVTracking = object
  225. private
  226. CMOVScore, ConstCount: LongInt;
  227. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  228. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  229. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  230. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  231. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  232. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  233. fOptimizer: TX86AsmOptimizer;
  234. fLabel: TAsmSymbol;
  235. fInsertionPoint,
  236. fCondition,
  237. fInitialJump,
  238. fFirstMovBlock,
  239. fFirstMovBlockStop,
  240. fSecondJump,
  241. fThirdJump,
  242. fSecondMovBlock,
  243. fSecondMovBlockStop,
  244. fMidLabel,
  245. fEndLabel,
  246. fAllocationRange: tai;
  247. fState: TCMovTrackingState;
  248. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  249. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  250. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  251. public
  252. RegisterTracking: TAllUsedRegs;
  253. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  254. destructor Done;
  255. procedure Process(out new_p: tai);
  256. property State: TCMovTrackingState read fState;
  257. end;
  258. PCMOVTracking = ^TCMOVTracking;
  259. {$endif 8086}
  260. {$ifdef DEBUG_AOPTCPU}
  261. const
  262. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  263. {$else DEBUG_AOPTCPU}
  264. { Empty strings help the optimizer to remove string concatenations that won't
  265. ever appear to the user on release builds. [Kit] }
  266. const
  267. SPeepholeOptimization = '';
  268. {$endif DEBUG_AOPTCPU}
  269. LIST_STEP_SIZE = 4;
  270. type
  271. TJumpTrackingItem = class(TLinkedListItem)
  272. private
  273. FSymbol: TAsmSymbol;
  274. FRefs: LongInt;
  275. public
  276. constructor Create(ASymbol: TAsmSymbol);
  277. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  278. property Symbol: TAsmSymbol read FSymbol;
  279. property Refs: LongInt read FRefs;
  280. end;
  281. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  282. begin
  283. inherited Create;
  284. FSymbol := ASymbol;
  285. FRefs := 0;
  286. end;
  287. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  288. begin
  289. Inc(FRefs);
  290. end;
  291. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  292. begin
  293. result :=
  294. (instr.typ = ait_instruction) and
  295. (taicpu(instr).opcode = op) and
  296. ((opsize = []) or (taicpu(instr).opsize in opsize));
  297. end;
  298. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  299. begin
  300. result :=
  301. (instr.typ = ait_instruction) and
  302. ((taicpu(instr).opcode = op1) or
  303. (taicpu(instr).opcode = op2)
  304. ) and
  305. ((opsize = []) or (taicpu(instr).opsize in opsize));
  306. end;
  307. function MatchInstruction(const instr: tai; const op1,op2,op3: 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) or
  313. (taicpu(instr).opcode = op3)
  314. ) and
  315. ((opsize = []) or (taicpu(instr).opsize in opsize));
  316. end;
  317. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  318. const opsize : topsizes) : boolean;
  319. var
  320. op : TAsmOp;
  321. begin
  322. result:=false;
  323. if (instr.typ <> ait_instruction) or
  324. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  325. exit;
  326. for op in ops do
  327. begin
  328. if taicpu(instr).opcode = op then
  329. begin
  330. result:=true;
  331. exit;
  332. end;
  333. end;
  334. end;
  335. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  336. begin
  337. result := (oper.typ = top_reg) and (oper.reg = reg);
  338. end;
  339. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  340. begin
  341. result := (oper.typ = top_const) and (oper.val = a);
  342. end;
  343. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  344. begin
  345. result := oper1.typ = oper2.typ;
  346. if result then
  347. case oper1.typ of
  348. top_const:
  349. Result:=oper1.val = oper2.val;
  350. top_reg:
  351. Result:=oper1.reg = oper2.reg;
  352. top_ref:
  353. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  354. else
  355. internalerror(2013102801);
  356. end
  357. end;
  358. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  359. begin
  360. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  361. if result then
  362. case oper1.typ of
  363. top_const:
  364. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  365. top_reg:
  366. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  367. top_ref:
  368. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  369. else
  370. internalerror(2020052401);
  371. end
  372. end;
  373. function RefsEqual(const r1, r2: treference): boolean;
  374. begin
  375. RefsEqual :=
  376. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  377. (r1.relsymbol = r2.relsymbol) and
  378. (r1.segment = r2.segment) and (r1.base = r2.base) and
  379. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  380. (r1.offset = r2.offset) and
  381. (r1.volatility + r2.volatility = []);
  382. end;
  383. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  384. begin
  385. if (r1.symbol<>r2.symbol) then
  386. { If the index registers are different, there's a chance one could
  387. be set so it equals the other symbol }
  388. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  389. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  390. (r1.relsymbol = r2.relsymbol) and
  391. (r1.segment = r2.segment) and (r1.base = r2.base) and
  392. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  393. (r1.volatility + r2.volatility = []) then
  394. { In this case, it all depends on the offsets }
  395. Exit(abs(r1.offset - r2.offset) < Range);
  396. { There's a chance things MIGHT overlap, so take no chances }
  397. Result := True;
  398. end;
  399. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  400. begin
  401. Result:=(ref.offset=0) and
  402. (ref.scalefactor in [0,1]) and
  403. (ref.segment=NR_NO) and
  404. (ref.symbol=nil) and
  405. (ref.relsymbol=nil) and
  406. ((base=NR_INVALID) or
  407. (ref.base=base)) and
  408. ((index=NR_INVALID) or
  409. (ref.index=index)) and
  410. (ref.volatility=[]);
  411. end;
  412. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  413. begin
  414. Result:=(ref.scalefactor in [0,1]) and
  415. (ref.segment=NR_NO) and
  416. (ref.symbol=nil) and
  417. (ref.relsymbol=nil) and
  418. ((base=NR_INVALID) or
  419. (ref.base=base)) and
  420. ((index=NR_INVALID) or
  421. (ref.index=index)) and
  422. (ref.volatility=[]);
  423. end;
  424. function InstrReadsFlags(p: tai): boolean;
  425. begin
  426. InstrReadsFlags := true;
  427. case p.typ of
  428. ait_instruction:
  429. if InsProp[taicpu(p).opcode].Ch*
  430. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  431. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  432. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  433. exit;
  434. ait_label:
  435. exit;
  436. else
  437. ;
  438. end;
  439. InstrReadsFlags := false;
  440. end;
  441. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  442. begin
  443. Next:=Current;
  444. repeat
  445. Result:=GetNextInstruction(Next,Next);
  446. until not (Result) or
  447. not(cs_opt_level3 in current_settings.optimizerswitches) or
  448. (Next.typ<>ait_instruction) or
  449. RegInInstruction(reg,Next) or
  450. is_calljmp(taicpu(Next).opcode);
  451. end;
  452. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  453. var
  454. GetNextResult: Boolean;
  455. begin
  456. Result:=0;
  457. Next:=Current;
  458. repeat
  459. GetNextResult := GetNextInstruction(Next,Next);
  460. if GetNextResult then
  461. Inc(Result)
  462. else
  463. { Must return zero upon hitting the end of the linked list without a match }
  464. Result := 0;
  465. until not (GetNextResult) 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.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  472. procedure TrackJump(Symbol: TAsmSymbol);
  473. var
  474. Search: TJumpTrackingItem;
  475. begin
  476. { See if an entry already exists in our jump tracking list
  477. (faster to search backwards due to the higher chance of
  478. matching destinations) }
  479. Search := TJumpTrackingItem(JumpTracking.Last);
  480. while Assigned(Search) do
  481. begin
  482. if Search.Symbol = Symbol then
  483. begin
  484. { Found it - remove it so it can be pushed to the front }
  485. JumpTracking.Remove(Search);
  486. Break;
  487. end;
  488. Search := TJumpTrackingItem(Search.Previous);
  489. end;
  490. if not Assigned(Search) then
  491. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  492. JumpTracking.Concat(Search);
  493. Search.IncRefs;
  494. end;
  495. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  496. var
  497. Search: TJumpTrackingItem;
  498. begin
  499. Result := False;
  500. { See if this label appears in the tracking list }
  501. Search := TJumpTrackingItem(JumpTracking.Last);
  502. while Assigned(Search) do
  503. begin
  504. if Search.Symbol = Symbol then
  505. begin
  506. { Found it - let's see what we can discover }
  507. if Search.Symbol.getrefs = Search.Refs then
  508. begin
  509. { Success - all the references are accounted for }
  510. JumpTracking.Remove(Search);
  511. Search.Free;
  512. { It is logically impossible for CrossJump to be false here
  513. because we must have run into a conditional jump for
  514. this label at some point }
  515. if not CrossJump then
  516. InternalError(2022041710);
  517. if JumpTracking.First = nil then
  518. { Tracking list is now empty - no more cross jumps }
  519. CrossJump := False;
  520. Result := True;
  521. Exit;
  522. end;
  523. { If the references don't match, it's possible to enter
  524. this label through other means, so drop out }
  525. Exit;
  526. end;
  527. Search := TJumpTrackingItem(Search.Previous);
  528. end;
  529. end;
  530. var
  531. Next_Label: tai;
  532. begin
  533. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  534. Next := Current;
  535. repeat
  536. Result := GetNextInstruction(Next,Next);
  537. if not Result then
  538. Break;
  539. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  540. if is_calljmpuncondret(taicpu(Next).opcode) then
  541. begin
  542. if (taicpu(Next).opcode = A_JMP) and
  543. { Remove dead code now to save time }
  544. RemoveDeadCodeAfterJump(taicpu(Next)) then
  545. { A jump was removed, but not the current instruction, and
  546. Result doesn't necessarily translate into an optimisation
  547. routine's Result, so use the "Force New Iteration" flag so
  548. mark a new pass }
  549. Include(OptsToCheck, aoc_ForceNewIteration);
  550. if not Assigned(JumpTracking) then
  551. begin
  552. { Cross-label optimisations often causes other optimisations
  553. to perform worse because they're not given the chance to
  554. optimise locally. In this case, don't do the cross-label
  555. optimisations yet, but flag them as a potential possibility
  556. for the next iteration of Pass 1 }
  557. if not NotFirstIteration then
  558. Include(OptsToCheck, aoc_ForceNewIteration);
  559. end
  560. else if IsJumpToLabel(taicpu(Next)) and
  561. GetNextInstruction(Next, Next_Label) then
  562. begin
  563. { If we have JMP .lbl, and the label after it has all of its
  564. references tracked, then this is probably an if-else style of
  565. block and we can keep tracking. If the label for this jump
  566. then appears later and is fully tracked, then it's the end
  567. of the if-else blocks and the code paths converge (thus
  568. marking the end of the cross-jump) }
  569. if (Next_Label.typ = ait_label) then
  570. begin
  571. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  572. begin
  573. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  574. Next := Next_Label;
  575. { CrossJump gets set to false by LabelAccountedFor if the
  576. list is completely emptied (as it indicates that all
  577. code paths have converged). We could avoid this nuance
  578. by moving the TrackJump call to before the
  579. LabelAccountedFor call, but this is slower in situations
  580. where LabelAccountedFor would return False due to the
  581. creation of a new object that is not used and destroyed
  582. soon after. }
  583. CrossJump := True;
  584. Continue;
  585. end;
  586. end
  587. else if (Next_Label.typ <> ait_marker) then
  588. { We just did a RemoveDeadCodeAfterJump, so either we find
  589. a label, the end of the procedure or some kind of marker}
  590. InternalError(2022041720);
  591. end;
  592. Result := False;
  593. Exit;
  594. end
  595. else
  596. begin
  597. if not Assigned(JumpTracking) then
  598. begin
  599. { Cross-label optimisations often causes other optimisations
  600. to perform worse because they're not given the chance to
  601. optimise locally. In this case, don't do the cross-label
  602. optimisations yet, but flag them as a potential possibility
  603. for the next iteration of Pass 1 }
  604. if not NotFirstIteration then
  605. Include(OptsToCheck, aoc_ForceNewIteration);
  606. end
  607. else if IsJumpToLabel(taicpu(Next)) then
  608. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  609. else
  610. { Conditional jumps should always be a jump to label }
  611. InternalError(2022041701);
  612. CrossJump := True;
  613. Continue;
  614. end;
  615. if Next.typ = ait_label then
  616. begin
  617. if not Assigned(JumpTracking) then
  618. begin
  619. { Cross-label optimisations often causes other optimisations
  620. to perform worse because they're not given the chance to
  621. optimise locally. In this case, don't do the cross-label
  622. optimisations yet, but flag them as a potential possibility
  623. for the next iteration of Pass 1 }
  624. if not NotFirstIteration then
  625. Include(OptsToCheck, aoc_ForceNewIteration);
  626. end
  627. else if LabelAccountedFor(tai_label(Next).labsym) then
  628. Continue;
  629. { If we reach here, we're at a label that hasn't been seen before
  630. (or JumpTracking was nil) }
  631. Break;
  632. end;
  633. until not Result or
  634. not (cs_opt_level3 in current_settings.optimizerswitches) or
  635. not (Next.typ in [ait_label, ait_instruction]) or
  636. RegInInstruction(reg,Next);
  637. end;
  638. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  639. begin
  640. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  641. begin
  642. Result:=GetNextInstruction(Current,Next);
  643. exit;
  644. end;
  645. Next:=tai(Current.Next);
  646. Result:=false;
  647. while assigned(Next) do
  648. begin
  649. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  650. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  651. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  652. exit
  653. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  654. begin
  655. Result:=true;
  656. exit;
  657. end;
  658. Next:=tai(Next.Next);
  659. end;
  660. end;
  661. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  662. begin
  663. Result:=RegReadByInstruction(reg,hp);
  664. end;
  665. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  666. var
  667. p: taicpu;
  668. opcount: longint;
  669. begin
  670. RegReadByInstruction := false;
  671. if hp.typ <> ait_instruction then
  672. exit;
  673. p := taicpu(hp);
  674. case p.opcode of
  675. A_CALL:
  676. regreadbyinstruction := true;
  677. A_IMUL:
  678. case p.ops of
  679. 1:
  680. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  681. (
  682. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  683. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  684. );
  685. 2,3:
  686. regReadByInstruction :=
  687. reginop(reg,p.oper[0]^) or
  688. reginop(reg,p.oper[1]^);
  689. else
  690. InternalError(2019112801);
  691. end;
  692. A_MUL:
  693. begin
  694. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  695. (
  696. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  697. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  698. );
  699. end;
  700. A_IDIV,A_DIV:
  701. begin
  702. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  703. (
  704. (getregtype(reg)=R_INTREGISTER) and
  705. (
  706. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  707. )
  708. );
  709. end;
  710. else
  711. begin
  712. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  713. begin
  714. RegReadByInstruction := false;
  715. exit;
  716. end;
  717. for opcount := 0 to p.ops-1 do
  718. if (p.oper[opCount]^.typ = top_ref) and
  719. RegInRef(reg,p.oper[opcount]^.ref^) then
  720. begin
  721. RegReadByInstruction := true;
  722. exit
  723. end;
  724. { special handling for SSE MOVSD }
  725. if (p.opcode=A_MOVSD) and (p.ops>0) then
  726. begin
  727. if p.ops<>2 then
  728. internalerror(2017042702);
  729. regReadByInstruction := reginop(reg,p.oper[0]^) or
  730. (
  731. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  732. );
  733. exit;
  734. end;
  735. with insprop[p.opcode] do
  736. begin
  737. case getregtype(reg) of
  738. R_INTREGISTER:
  739. begin
  740. case getsupreg(reg) of
  741. RS_EAX:
  742. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  743. begin
  744. RegReadByInstruction := true;
  745. exit
  746. end;
  747. RS_ECX:
  748. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  749. begin
  750. RegReadByInstruction := true;
  751. exit
  752. end;
  753. RS_EDX:
  754. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  755. begin
  756. RegReadByInstruction := true;
  757. exit
  758. end;
  759. RS_EBX:
  760. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  761. begin
  762. RegReadByInstruction := true;
  763. exit
  764. end;
  765. RS_ESP:
  766. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  767. begin
  768. RegReadByInstruction := true;
  769. exit
  770. end;
  771. RS_EBP:
  772. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  773. begin
  774. RegReadByInstruction := true;
  775. exit
  776. end;
  777. RS_ESI:
  778. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  779. begin
  780. RegReadByInstruction := true;
  781. exit
  782. end;
  783. RS_EDI:
  784. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  785. begin
  786. RegReadByInstruction := true;
  787. exit
  788. end;
  789. end;
  790. end;
  791. R_MMREGISTER:
  792. begin
  793. case getsupreg(reg) of
  794. RS_XMM0:
  795. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  796. begin
  797. RegReadByInstruction := true;
  798. exit
  799. end;
  800. end;
  801. end;
  802. else
  803. ;
  804. end;
  805. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  806. begin
  807. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  808. begin
  809. case p.condition of
  810. C_A,C_NBE, { CF=0 and ZF=0 }
  811. C_BE,C_NA: { CF=1 or ZF=1 }
  812. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  813. C_AE,C_NB,C_NC, { CF=0 }
  814. C_B,C_NAE,C_C: { CF=1 }
  815. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  816. C_NE,C_NZ, { ZF=0 }
  817. C_E,C_Z: { ZF=1 }
  818. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  819. C_G,C_NLE, { ZF=0 and SF=OF }
  820. C_LE,C_NG: { ZF=1 or SF<>OF }
  821. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  822. C_GE,C_NL, { SF=OF }
  823. C_L,C_NGE: { SF<>OF }
  824. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  825. C_NO, { OF=0 }
  826. C_O: { OF=1 }
  827. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  828. C_NP,C_PO, { PF=0 }
  829. C_P,C_PE: { PF=1 }
  830. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  831. C_NS, { SF=0 }
  832. C_S: { SF=1 }
  833. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  834. else
  835. internalerror(2017042701);
  836. end;
  837. if RegReadByInstruction then
  838. exit;
  839. end;
  840. case getsubreg(reg) of
  841. R_SUBW,R_SUBD,R_SUBQ:
  842. RegReadByInstruction :=
  843. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  844. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  845. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  846. R_SUBFLAGCARRY:
  847. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  848. R_SUBFLAGPARITY:
  849. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  850. R_SUBFLAGAUXILIARY:
  851. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  852. R_SUBFLAGZERO:
  853. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  854. R_SUBFLAGSIGN:
  855. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  856. R_SUBFLAGOVERFLOW:
  857. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  858. R_SUBFLAGINTERRUPT:
  859. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  860. R_SUBFLAGDIRECTION:
  861. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  862. else
  863. internalerror(2017042601);
  864. end;
  865. exit;
  866. end;
  867. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  868. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  869. (p.oper[0]^.reg=p.oper[1]^.reg) then
  870. exit;
  871. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  872. begin
  873. RegReadByInstruction := true;
  874. exit
  875. end;
  876. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  877. begin
  878. RegReadByInstruction := true;
  879. exit
  880. end;
  881. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  882. begin
  883. RegReadByInstruction := true;
  884. exit
  885. end;
  886. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  887. begin
  888. RegReadByInstruction := true;
  889. exit
  890. end;
  891. end;
  892. end;
  893. end;
  894. end;
  895. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  896. begin
  897. result:=false;
  898. if p1.typ<>ait_instruction then
  899. exit;
  900. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  901. exit(true);
  902. if (getregtype(reg)=R_INTREGISTER) and
  903. { change information for xmm movsd are not correct }
  904. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  905. begin
  906. { Handle instructions that behave differently depending on the size and operand count }
  907. case taicpu(p1).opcode of
  908. A_MUL, A_DIV, A_IDIV:
  909. if taicpu(p1).opsize = S_B then
  910. Result := (getsupreg(Reg) = RS_EAX)
  911. else
  912. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  913. A_IMUL:
  914. if taicpu(p1).ops = 1 then
  915. begin
  916. if taicpu(p1).opsize = S_B then
  917. Result := (getsupreg(Reg) = RS_EAX)
  918. else
  919. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  920. end;
  921. { If ops are greater than 1, call inherited method }
  922. else
  923. case getsupreg(reg) of
  924. { RS_EAX = RS_RAX on x86-64 }
  925. RS_EAX:
  926. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  927. RS_ECX:
  928. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  929. RS_EDX:
  930. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  931. RS_EBX:
  932. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  933. RS_ESP:
  934. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  935. RS_EBP:
  936. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  937. RS_ESI:
  938. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  939. RS_EDI:
  940. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  941. else
  942. ;
  943. end;
  944. end;
  945. if result then
  946. exit;
  947. end
  948. else if getregtype(reg)=R_MMREGISTER then
  949. begin
  950. case getsupreg(reg) of
  951. RS_XMM0:
  952. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  953. else
  954. ;
  955. end;
  956. if result then
  957. exit;
  958. end
  959. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  960. begin
  961. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  962. exit(true);
  963. case getsubreg(reg) of
  964. R_SUBFLAGCARRY:
  965. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  966. R_SUBFLAGPARITY:
  967. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  968. R_SUBFLAGAUXILIARY:
  969. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  970. R_SUBFLAGZERO:
  971. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  972. R_SUBFLAGSIGN:
  973. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  974. R_SUBFLAGOVERFLOW:
  975. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  976. R_SUBFLAGINTERRUPT:
  977. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  978. R_SUBFLAGDIRECTION:
  979. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  980. R_SUBW,R_SUBD,R_SUBQ:
  981. { Everything except the direction bits }
  982. Result:=
  983. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  984. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  985. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  986. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  987. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  988. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  989. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  990. else
  991. ;
  992. end;
  993. if result then
  994. exit;
  995. end
  996. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  997. exit(true);
  998. Result:=inherited RegInInstruction(Reg, p1);
  999. end;
  1000. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1001. const
  1002. WriteOps: array[0..3] of set of TInsChange =
  1003. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1004. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1005. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1006. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1007. var
  1008. OperIdx: Integer;
  1009. begin
  1010. Result := False;
  1011. if p1.typ <> ait_instruction then
  1012. exit;
  1013. with insprop[taicpu(p1).opcode] do
  1014. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1015. begin
  1016. case getsubreg(reg) of
  1017. R_SUBW,R_SUBD,R_SUBQ:
  1018. Result :=
  1019. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1020. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1021. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1022. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1023. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1024. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1025. R_SUBFLAGCARRY:
  1026. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1027. R_SUBFLAGPARITY:
  1028. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1029. R_SUBFLAGAUXILIARY:
  1030. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1031. R_SUBFLAGZERO:
  1032. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1033. R_SUBFLAGSIGN:
  1034. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1035. R_SUBFLAGOVERFLOW:
  1036. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1037. R_SUBFLAGINTERRUPT:
  1038. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1039. R_SUBFLAGDIRECTION:
  1040. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1041. else
  1042. internalerror(2017042602);
  1043. end;
  1044. exit;
  1045. end;
  1046. case taicpu(p1).opcode of
  1047. A_CALL:
  1048. { We could potentially set Result to False if the register in
  1049. question is non-volatile for the subroutine's calling convention,
  1050. but this would require detecting the calling convention in use and
  1051. also assuming that the routine doesn't contain malformed assembly
  1052. language, for example... so it could only be done under -O4 as it
  1053. would be considered a side-effect. [Kit] }
  1054. Result := True;
  1055. A_MOVSD:
  1056. { special handling for SSE MOVSD }
  1057. if (taicpu(p1).ops>0) then
  1058. begin
  1059. if taicpu(p1).ops<>2 then
  1060. internalerror(2017042703);
  1061. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1062. end;
  1063. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1064. so fix it here (FK)
  1065. }
  1066. A_VMOVSS,
  1067. A_VMOVSD:
  1068. begin
  1069. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1070. exit;
  1071. end;
  1072. A_MUL, A_DIV, A_IDIV:
  1073. begin
  1074. if taicpu(p1).opsize = S_B then
  1075. Result := (getsupreg(Reg) = RS_EAX)
  1076. else
  1077. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1078. end;
  1079. A_IMUL:
  1080. begin
  1081. if taicpu(p1).ops = 1 then
  1082. begin
  1083. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1084. end
  1085. else
  1086. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1087. Exit;
  1088. end;
  1089. else
  1090. ;
  1091. end;
  1092. if Result then
  1093. exit;
  1094. with insprop[taicpu(p1).opcode] do
  1095. begin
  1096. if getregtype(reg)=R_INTREGISTER then
  1097. begin
  1098. case getsupreg(reg) of
  1099. RS_EAX:
  1100. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1101. begin
  1102. Result := True;
  1103. exit
  1104. end;
  1105. RS_ECX:
  1106. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1107. begin
  1108. Result := True;
  1109. exit
  1110. end;
  1111. RS_EDX:
  1112. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1113. begin
  1114. Result := True;
  1115. exit
  1116. end;
  1117. RS_EBX:
  1118. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1119. begin
  1120. Result := True;
  1121. exit
  1122. end;
  1123. RS_ESP:
  1124. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1125. begin
  1126. Result := True;
  1127. exit
  1128. end;
  1129. RS_EBP:
  1130. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1131. begin
  1132. Result := True;
  1133. exit
  1134. end;
  1135. RS_ESI:
  1136. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1137. begin
  1138. Result := True;
  1139. exit
  1140. end;
  1141. RS_EDI:
  1142. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1143. begin
  1144. Result := True;
  1145. exit
  1146. end;
  1147. end;
  1148. end;
  1149. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1150. if (WriteOps[OperIdx]*Ch<>[]) and
  1151. { The register doesn't get modified inside a reference }
  1152. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1153. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1154. begin
  1155. Result := true;
  1156. exit
  1157. end;
  1158. end;
  1159. end;
  1160. {$ifdef DEBUG_AOPTCPU}
  1161. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1162. begin
  1163. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1164. end;
  1165. function debug_tostr(i: tcgint): string; inline;
  1166. begin
  1167. Result := tostr(i);
  1168. end;
  1169. function debug_hexstr(i: tcgint): string;
  1170. begin
  1171. Result := '0x';
  1172. case i of
  1173. 0..$FF:
  1174. Result := Result + hexstr(i, 2);
  1175. $100..$FFFF:
  1176. Result := Result + hexstr(i, 4);
  1177. $10000..$FFFFFF:
  1178. Result := Result + hexstr(i, 6);
  1179. $1000000..$FFFFFFFF:
  1180. Result := Result + hexstr(i, 8);
  1181. else
  1182. Result := Result + hexstr(i, 16);
  1183. end;
  1184. end;
  1185. function debug_regname(r: TRegister): string; inline;
  1186. begin
  1187. Result := '%' + std_regname(r);
  1188. end;
  1189. { Debug output function - creates a string representation of an operator }
  1190. function debug_operstr(oper: TOper): string;
  1191. begin
  1192. case oper.typ of
  1193. top_const:
  1194. Result := '$' + debug_tostr(oper.val);
  1195. top_reg:
  1196. Result := debug_regname(oper.reg);
  1197. top_ref:
  1198. begin
  1199. if oper.ref^.offset <> 0 then
  1200. Result := debug_tostr(oper.ref^.offset) + '('
  1201. else
  1202. Result := '(';
  1203. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1204. begin
  1205. Result := Result + debug_regname(oper.ref^.base);
  1206. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1207. Result := Result + ',' + debug_regname(oper.ref^.index);
  1208. end
  1209. else
  1210. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1211. Result := Result + debug_regname(oper.ref^.index);
  1212. if (oper.ref^.scalefactor > 1) then
  1213. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1214. else
  1215. Result := Result + ')';
  1216. end;
  1217. else
  1218. Result := '[UNKNOWN]';
  1219. end;
  1220. end;
  1221. function debug_op2str(opcode: tasmop): string; inline;
  1222. begin
  1223. Result := std_op2str[opcode];
  1224. end;
  1225. function debug_opsize2str(opsize: topsize): string; inline;
  1226. begin
  1227. Result := gas_opsize2str[opsize];
  1228. end;
  1229. {$else DEBUG_AOPTCPU}
  1230. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1231. begin
  1232. end;
  1233. function debug_tostr(i: tcgint): string; inline;
  1234. begin
  1235. Result := '';
  1236. end;
  1237. function debug_hexstr(i: tcgint): string; inline;
  1238. begin
  1239. Result := '';
  1240. end;
  1241. function debug_regname(r: TRegister): string; inline;
  1242. begin
  1243. Result := '';
  1244. end;
  1245. function debug_operstr(oper: TOper): string; inline;
  1246. begin
  1247. Result := '';
  1248. end;
  1249. function debug_op2str(opcode: tasmop): string; inline;
  1250. begin
  1251. Result := '';
  1252. end;
  1253. function debug_opsize2str(opsize: topsize): string; inline;
  1254. begin
  1255. Result := '';
  1256. end;
  1257. {$endif DEBUG_AOPTCPU}
  1258. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1259. begin
  1260. {$ifdef x86_64}
  1261. { Always fine on x86-64 }
  1262. Result := True;
  1263. {$else x86_64}
  1264. Result :=
  1265. {$ifdef i8086}
  1266. (current_settings.cputype >= cpu_386) and
  1267. {$endif i8086}
  1268. (
  1269. { Always accept if optimising for size }
  1270. (cs_opt_size in current_settings.optimizerswitches) or
  1271. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1272. (current_settings.optimizecputype >= cpu_Pentium2)
  1273. );
  1274. {$endif x86_64}
  1275. end;
  1276. { Attempts to allocate a volatile integer register for use between p and hp,
  1277. using AUsedRegs for the current register usage information. Returns NR_NO
  1278. if no free register could be found }
  1279. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1280. var
  1281. RegSet: TCPURegisterSet;
  1282. CurrentSuperReg: Integer;
  1283. CurrentReg: TRegister;
  1284. Currentp: tai;
  1285. Breakout: Boolean;
  1286. begin
  1287. Result := NR_NO;
  1288. RegSet :=
  1289. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1290. current_procinfo.saved_regs_int;
  1291. (*
  1292. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1293. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1294. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1295. *)
  1296. for CurrentSuperReg in RegSet do
  1297. begin
  1298. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1299. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1300. {$if defined(i386) or defined(i8086)}
  1301. { If the target size is 8-bit, make sure we can actually encode it }
  1302. and (
  1303. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1304. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1305. )
  1306. {$endif i386 or i8086}
  1307. then
  1308. begin
  1309. Currentp := p;
  1310. Breakout := False;
  1311. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1312. begin
  1313. case Currentp.typ of
  1314. ait_instruction:
  1315. begin
  1316. if RegInInstruction(CurrentReg, Currentp) then
  1317. begin
  1318. Breakout := True;
  1319. Break;
  1320. end;
  1321. { Cannot allocate across an unconditional jump }
  1322. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1323. Exit;
  1324. end;
  1325. ait_marker:
  1326. { Don't try anything more if a marker is hit }
  1327. Exit;
  1328. ait_regalloc:
  1329. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1330. begin
  1331. Breakout := True;
  1332. Break;
  1333. end;
  1334. else
  1335. ;
  1336. end;
  1337. end;
  1338. if Breakout then
  1339. { Try the next register }
  1340. Continue;
  1341. { We have a free register available }
  1342. Result := CurrentReg;
  1343. if not DontAlloc then
  1344. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1345. Exit;
  1346. end;
  1347. end;
  1348. end;
  1349. { Attempts to allocate a volatile MM register for use between p and hp,
  1350. using AUsedRegs for the current register usage information. Returns NR_NO
  1351. if no free register could be found }
  1352. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1353. var
  1354. RegSet: TCPURegisterSet;
  1355. CurrentSuperReg: Integer;
  1356. CurrentReg: TRegister;
  1357. Currentp: tai;
  1358. Breakout: Boolean;
  1359. begin
  1360. Result := NR_NO;
  1361. RegSet :=
  1362. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1363. current_procinfo.saved_regs_mm;
  1364. for CurrentSuperReg in RegSet do
  1365. begin
  1366. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1367. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1368. begin
  1369. Currentp := p;
  1370. Breakout := False;
  1371. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1372. begin
  1373. case Currentp.typ of
  1374. ait_instruction:
  1375. begin
  1376. if RegInInstruction(CurrentReg, Currentp) then
  1377. begin
  1378. Breakout := True;
  1379. Break;
  1380. end;
  1381. { Cannot allocate across an unconditional jump }
  1382. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1383. Exit;
  1384. end;
  1385. ait_marker:
  1386. { Don't try anything more if a marker is hit }
  1387. Exit;
  1388. ait_regalloc:
  1389. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1390. begin
  1391. Breakout := True;
  1392. Break;
  1393. end;
  1394. else
  1395. ;
  1396. end;
  1397. end;
  1398. if Breakout then
  1399. { Try the next register }
  1400. Continue;
  1401. { We have a free register available }
  1402. Result := CurrentReg;
  1403. if not DontAlloc then
  1404. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1405. Exit;
  1406. end;
  1407. end;
  1408. end;
  1409. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1410. begin
  1411. if not SuperRegistersEqual(reg1,reg2) then
  1412. exit(false);
  1413. if getregtype(reg1)<>R_INTREGISTER then
  1414. exit(true); {because SuperRegisterEqual is true}
  1415. case getsubreg(reg1) of
  1416. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1417. higher, it preserves the high bits, so the new value depends on
  1418. reg2's previous value. In other words, it is equivalent to doing:
  1419. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1420. R_SUBL:
  1421. exit(getsubreg(reg2)=R_SUBL);
  1422. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1423. higher, it actually does a:
  1424. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1425. R_SUBH:
  1426. exit(getsubreg(reg2)=R_SUBH);
  1427. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1428. bits of reg2:
  1429. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1430. R_SUBW:
  1431. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1432. { a write to R_SUBD always overwrites every other subregister,
  1433. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1434. R_SUBD,
  1435. R_SUBQ:
  1436. exit(true);
  1437. else
  1438. internalerror(2017042801);
  1439. end;
  1440. end;
  1441. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1442. begin
  1443. if not SuperRegistersEqual(reg1,reg2) then
  1444. exit(false);
  1445. if getregtype(reg1)<>R_INTREGISTER then
  1446. exit(true); {because SuperRegisterEqual is true}
  1447. case getsubreg(reg1) of
  1448. R_SUBL:
  1449. exit(getsubreg(reg2)<>R_SUBH);
  1450. R_SUBH:
  1451. exit(getsubreg(reg2)<>R_SUBL);
  1452. R_SUBW,
  1453. R_SUBD,
  1454. R_SUBQ:
  1455. exit(true);
  1456. else
  1457. internalerror(2017042802);
  1458. end;
  1459. end;
  1460. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1461. var
  1462. hp1 : tai;
  1463. l : TCGInt;
  1464. begin
  1465. result:=false;
  1466. if not(GetNextInstruction(p, hp1)) then
  1467. exit;
  1468. { changes the code sequence
  1469. shr/sar const1, x
  1470. shl const2, x
  1471. to
  1472. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1473. if (taicpu(p).oper[0]^.typ = top_const) and
  1474. MatchInstruction(hp1,A_SHL,[]) and
  1475. (taicpu(hp1).oper[0]^.typ = top_const) and
  1476. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1477. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1478. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1479. begin
  1480. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1481. not(cs_opt_size in current_settings.optimizerswitches) then
  1482. begin
  1483. { shr/sar const1, %reg
  1484. shl const2, %reg
  1485. with const1 > const2 }
  1486. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1487. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1488. taicpu(hp1).opcode := A_AND;
  1489. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1490. case taicpu(p).opsize Of
  1491. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1492. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1493. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1494. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1495. else
  1496. Internalerror(2017050703)
  1497. end;
  1498. end
  1499. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1500. not(cs_opt_size in current_settings.optimizerswitches) then
  1501. begin
  1502. { shr/sar const1, %reg
  1503. shl const2, %reg
  1504. with const1 < const2 }
  1505. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1506. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1507. taicpu(p).opcode := A_AND;
  1508. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1509. case taicpu(p).opsize Of
  1510. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1511. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1512. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1513. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1514. else
  1515. Internalerror(2017050702)
  1516. end;
  1517. end
  1518. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1519. begin
  1520. { shr/sar const1, %reg
  1521. shl const2, %reg
  1522. with const1 = const2 }
  1523. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1524. taicpu(p).opcode := A_AND;
  1525. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1526. case taicpu(p).opsize Of
  1527. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1528. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1529. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1530. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1531. else
  1532. Internalerror(2017050701)
  1533. end;
  1534. RemoveInstruction(hp1);
  1535. end;
  1536. end;
  1537. end;
  1538. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1539. var
  1540. opsize : topsize;
  1541. hp1, hp2 : tai;
  1542. tmpref : treference;
  1543. ShiftValue : Cardinal;
  1544. BaseValue : TCGInt;
  1545. begin
  1546. result:=false;
  1547. opsize:=taicpu(p).opsize;
  1548. { changes certain "imul const, %reg"'s to lea sequences }
  1549. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1550. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1551. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1552. if (taicpu(p).oper[0]^.val = 1) then
  1553. if (taicpu(p).ops = 2) then
  1554. { remove "imul $1, reg" }
  1555. begin
  1556. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1557. Result := RemoveCurrentP(p);
  1558. end
  1559. else
  1560. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1561. begin
  1562. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1563. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1564. asml.InsertAfter(hp1, p);
  1565. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1566. RemoveCurrentP(p, hp1);
  1567. Result := True;
  1568. end
  1569. else if ((taicpu(p).ops <= 2) or
  1570. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1571. not(cs_opt_size in current_settings.optimizerswitches) and
  1572. (not(GetNextInstruction(p, hp1)) or
  1573. not((tai(hp1).typ = ait_instruction) and
  1574. ((taicpu(hp1).opcode=A_Jcc) and
  1575. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1576. begin
  1577. {
  1578. imul X, reg1, reg2 to
  1579. lea (reg1,reg1,Y), reg2
  1580. shl ZZ,reg2
  1581. imul XX, reg1 to
  1582. lea (reg1,reg1,YY), reg1
  1583. shl ZZ,reg2
  1584. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1585. it does not exist as a separate optimization target in FPC though.
  1586. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1587. at most two zeros
  1588. }
  1589. reference_reset(tmpref,1,[]);
  1590. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1591. begin
  1592. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1593. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1594. TmpRef.base := taicpu(p).oper[1]^.reg;
  1595. TmpRef.index := taicpu(p).oper[1]^.reg;
  1596. if not(BaseValue in [3,5,9]) then
  1597. Internalerror(2018110101);
  1598. TmpRef.ScaleFactor := BaseValue-1;
  1599. if (taicpu(p).ops = 2) then
  1600. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1601. else
  1602. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1603. AsmL.InsertAfter(hp1,p);
  1604. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1605. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1606. RemoveCurrentP(p, hp1);
  1607. if ShiftValue>0 then
  1608. begin
  1609. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1610. AsmL.InsertAfter(hp2,hp1);
  1611. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1612. end;
  1613. Result := True;
  1614. end;
  1615. end;
  1616. end;
  1617. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1618. begin
  1619. Result := False;
  1620. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1621. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1622. begin
  1623. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1624. taicpu(p).opcode := A_MOV;
  1625. Result := True;
  1626. end;
  1627. end;
  1628. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1629. var
  1630. p: taicpu absolute hp; { Implicit typecast }
  1631. i: Integer;
  1632. begin
  1633. Result := False;
  1634. if not assigned(hp) or
  1635. (hp.typ <> ait_instruction) then
  1636. Exit;
  1637. Prefetch(insprop[p.opcode]);
  1638. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1639. with insprop[p.opcode] do
  1640. begin
  1641. case getsubreg(reg) of
  1642. R_SUBW,R_SUBD,R_SUBQ:
  1643. Result:=
  1644. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1645. uncommon flags are checked first }
  1646. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1647. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1648. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1649. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1650. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1651. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1652. R_SUBFLAGCARRY:
  1653. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1654. R_SUBFLAGPARITY:
  1655. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1656. R_SUBFLAGAUXILIARY:
  1657. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1658. R_SUBFLAGZERO:
  1659. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1660. R_SUBFLAGSIGN:
  1661. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1662. R_SUBFLAGOVERFLOW:
  1663. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1664. R_SUBFLAGINTERRUPT:
  1665. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1666. R_SUBFLAGDIRECTION:
  1667. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1668. else
  1669. internalerror(2017050501);
  1670. end;
  1671. exit;
  1672. end;
  1673. { Handle special cases first }
  1674. case p.opcode of
  1675. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1676. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1677. begin
  1678. Result :=
  1679. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1680. (p.oper[1]^.typ = top_reg) and
  1681. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1682. (
  1683. (p.oper[0]^.typ = top_const) or
  1684. (
  1685. (p.oper[0]^.typ = top_reg) and
  1686. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1687. ) or (
  1688. (p.oper[0]^.typ = top_ref) and
  1689. not RegInRef(reg,p.oper[0]^.ref^)
  1690. )
  1691. );
  1692. end;
  1693. A_MUL, A_IMUL:
  1694. Result :=
  1695. (
  1696. (p.ops=3) and { IMUL only }
  1697. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1698. (
  1699. (
  1700. (p.oper[1]^.typ=top_reg) and
  1701. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1702. ) or (
  1703. (p.oper[1]^.typ=top_ref) and
  1704. not RegInRef(reg,p.oper[1]^.ref^)
  1705. )
  1706. )
  1707. ) or (
  1708. (
  1709. (p.ops=1) and
  1710. (
  1711. (
  1712. (
  1713. (p.oper[0]^.typ=top_reg) and
  1714. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1715. )
  1716. ) or (
  1717. (p.oper[0]^.typ=top_ref) and
  1718. not RegInRef(reg,p.oper[0]^.ref^)
  1719. )
  1720. ) and (
  1721. (
  1722. (p.opsize=S_B) and
  1723. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1724. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1725. ) or (
  1726. (p.opsize=S_W) and
  1727. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1728. ) or (
  1729. (p.opsize=S_L) and
  1730. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1731. {$ifdef x86_64}
  1732. ) or (
  1733. (p.opsize=S_Q) and
  1734. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1735. {$endif x86_64}
  1736. )
  1737. )
  1738. )
  1739. );
  1740. A_CBW:
  1741. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1742. {$ifndef x86_64}
  1743. A_LDS:
  1744. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1745. A_LES:
  1746. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1747. {$endif not x86_64}
  1748. A_LFS:
  1749. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1750. A_LGS:
  1751. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1752. A_LSS:
  1753. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1754. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1755. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1756. A_LODSB:
  1757. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1758. A_LODSW:
  1759. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1760. {$ifdef x86_64}
  1761. A_LODSQ:
  1762. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1763. {$endif x86_64}
  1764. A_LODSD:
  1765. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1766. A_FSTSW, A_FNSTSW:
  1767. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1768. else
  1769. begin
  1770. with insprop[p.opcode] do
  1771. begin
  1772. if (
  1773. { xor %reg,%reg etc. is classed as a new value }
  1774. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1775. MatchOpType(p, top_reg, top_reg) and
  1776. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1777. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1778. ) then
  1779. begin
  1780. Result := True;
  1781. Exit;
  1782. end;
  1783. { Make sure the entire register is overwritten }
  1784. if (getregtype(reg) = R_INTREGISTER) then
  1785. begin
  1786. if (p.ops > 0) then
  1787. begin
  1788. if RegInOp(reg, p.oper[0]^) then
  1789. begin
  1790. if (p.oper[0]^.typ = top_ref) then
  1791. begin
  1792. if RegInRef(reg, p.oper[0]^.ref^) then
  1793. begin
  1794. Result := False;
  1795. Exit;
  1796. end;
  1797. end
  1798. else if (p.oper[0]^.typ = top_reg) then
  1799. begin
  1800. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1801. begin
  1802. Result := False;
  1803. Exit;
  1804. end
  1805. else if ([Ch_WOp1]*Ch<>[]) then
  1806. begin
  1807. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1808. Result := True
  1809. else
  1810. begin
  1811. Result := False;
  1812. Exit;
  1813. end;
  1814. end;
  1815. end;
  1816. end;
  1817. if (p.ops > 1) then
  1818. begin
  1819. if RegInOp(reg, p.oper[1]^) then
  1820. begin
  1821. if (p.oper[1]^.typ = top_ref) then
  1822. begin
  1823. if RegInRef(reg, p.oper[1]^.ref^) then
  1824. begin
  1825. Result := False;
  1826. Exit;
  1827. end;
  1828. end
  1829. else if (p.oper[1]^.typ = top_reg) then
  1830. begin
  1831. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1832. begin
  1833. Result := False;
  1834. Exit;
  1835. end
  1836. else if ([Ch_WOp2]*Ch<>[]) then
  1837. begin
  1838. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1839. Result := True
  1840. else
  1841. begin
  1842. Result := False;
  1843. Exit;
  1844. end;
  1845. end;
  1846. end;
  1847. end;
  1848. if (p.ops > 2) then
  1849. begin
  1850. if RegInOp(reg, p.oper[2]^) then
  1851. begin
  1852. if (p.oper[2]^.typ = top_ref) then
  1853. begin
  1854. if RegInRef(reg, p.oper[2]^.ref^) then
  1855. begin
  1856. Result := False;
  1857. Exit;
  1858. end;
  1859. end
  1860. else if (p.oper[2]^.typ = top_reg) then
  1861. begin
  1862. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1863. begin
  1864. Result := False;
  1865. Exit;
  1866. end
  1867. else if ([Ch_WOp3]*Ch<>[]) then
  1868. begin
  1869. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1870. Result := True
  1871. else
  1872. begin
  1873. Result := False;
  1874. Exit;
  1875. end;
  1876. end;
  1877. end;
  1878. end;
  1879. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1880. begin
  1881. if (p.oper[3]^.typ = top_ref) then
  1882. begin
  1883. if RegInRef(reg, p.oper[3]^.ref^) then
  1884. begin
  1885. Result := False;
  1886. Exit;
  1887. end;
  1888. end
  1889. else if (p.oper[3]^.typ = top_reg) then
  1890. begin
  1891. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1892. begin
  1893. Result := False;
  1894. Exit;
  1895. end
  1896. else if ([Ch_WOp4]*Ch<>[]) then
  1897. begin
  1898. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1899. Result := True
  1900. else
  1901. begin
  1902. Result := False;
  1903. Exit;
  1904. end;
  1905. end;
  1906. end;
  1907. end;
  1908. end;
  1909. end;
  1910. end;
  1911. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1912. case getsupreg(reg) of
  1913. RS_EAX:
  1914. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1915. begin
  1916. Result := True;
  1917. Exit;
  1918. end;
  1919. RS_ECX:
  1920. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1921. begin
  1922. Result := True;
  1923. Exit;
  1924. end;
  1925. RS_EDX:
  1926. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1927. begin
  1928. Result := True;
  1929. Exit;
  1930. end;
  1931. RS_EBX:
  1932. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1933. begin
  1934. Result := True;
  1935. Exit;
  1936. end;
  1937. RS_ESP:
  1938. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1939. begin
  1940. Result := True;
  1941. Exit;
  1942. end;
  1943. RS_EBP:
  1944. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1945. begin
  1946. Result := True;
  1947. Exit;
  1948. end;
  1949. RS_ESI:
  1950. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1951. begin
  1952. Result := True;
  1953. Exit;
  1954. end;
  1955. RS_EDI:
  1956. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1957. begin
  1958. Result := True;
  1959. Exit;
  1960. end;
  1961. else
  1962. ;
  1963. end;
  1964. end;
  1965. end;
  1966. end;
  1967. end;
  1968. end;
  1969. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1970. var
  1971. hp2,hp3 : tai;
  1972. begin
  1973. { some x86-64 issue a NOP before the real exit code }
  1974. if MatchInstruction(p,A_NOP,[]) then
  1975. GetNextInstruction(p,p);
  1976. result:=assigned(p) and (p.typ=ait_instruction) and
  1977. ((taicpu(p).opcode = A_RET) or
  1978. ((taicpu(p).opcode=A_LEAVE) and
  1979. GetNextInstruction(p,hp2) and
  1980. MatchInstruction(hp2,A_RET,[S_NO])
  1981. ) or
  1982. (((taicpu(p).opcode=A_LEA) and
  1983. MatchOpType(taicpu(p),top_ref,top_reg) and
  1984. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1985. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1986. ) and
  1987. GetNextInstruction(p,hp2) and
  1988. MatchInstruction(hp2,A_RET,[S_NO])
  1989. ) or
  1990. ((((taicpu(p).opcode=A_MOV) and
  1991. MatchOpType(taicpu(p),top_reg,top_reg) and
  1992. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1993. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1994. ((taicpu(p).opcode=A_LEA) and
  1995. MatchOpType(taicpu(p),top_ref,top_reg) and
  1996. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1997. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1998. )
  1999. ) and
  2000. GetNextInstruction(p,hp2) and
  2001. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2002. MatchOpType(taicpu(hp2),top_reg) and
  2003. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2004. GetNextInstruction(hp2,hp3) and
  2005. MatchInstruction(hp3,A_RET,[S_NO])
  2006. )
  2007. );
  2008. end;
  2009. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2010. begin
  2011. isFoldableArithOp := False;
  2012. case hp1.opcode of
  2013. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2014. isFoldableArithOp :=
  2015. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2016. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2017. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2018. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2019. (taicpu(hp1).oper[1]^.reg = reg);
  2020. A_INC,A_DEC,A_NEG,A_NOT:
  2021. isFoldableArithOp :=
  2022. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2023. (taicpu(hp1).oper[0]^.reg = reg);
  2024. else
  2025. ;
  2026. end;
  2027. end;
  2028. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2029. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2030. var
  2031. hp2: tai;
  2032. begin
  2033. hp2 := p;
  2034. repeat
  2035. hp2 := tai(hp2.previous);
  2036. if assigned(hp2) and
  2037. (hp2.typ = ait_regalloc) and
  2038. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2039. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2040. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2041. begin
  2042. RemoveInstruction(hp2);
  2043. break;
  2044. end;
  2045. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2046. end;
  2047. begin
  2048. case current_procinfo.procdef.returndef.typ of
  2049. arraydef,recorddef,pointerdef,
  2050. stringdef,enumdef,procdef,objectdef,errordef,
  2051. filedef,setdef,procvardef,
  2052. classrefdef,forwarddef:
  2053. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2054. orddef:
  2055. if current_procinfo.procdef.returndef.size <> 0 then
  2056. begin
  2057. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2058. { for int64/qword }
  2059. if current_procinfo.procdef.returndef.size = 8 then
  2060. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2061. end;
  2062. else
  2063. ;
  2064. end;
  2065. end;
  2066. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2067. var
  2068. hp1,hp2 : tai;
  2069. begin
  2070. result:=false;
  2071. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2072. begin
  2073. { vmova* reg1,reg1
  2074. =>
  2075. <nop> }
  2076. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2077. begin
  2078. RemoveCurrentP(p);
  2079. result:=true;
  2080. exit;
  2081. end;
  2082. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2083. (hp1.typ = ait_instruction) and
  2084. (
  2085. { Under -O2 and below, the instructions are always adjacent }
  2086. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2087. (taicpu(hp1).ops <= 1) or
  2088. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2089. { If reg1 = reg3, reg1 must not be modified in between }
  2090. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2091. ) then
  2092. begin
  2093. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2094. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2095. begin
  2096. { vmova* reg1,reg2
  2097. ...
  2098. vmova* reg2,reg3
  2099. dealloc reg2
  2100. =>
  2101. vmova* reg1,reg3 }
  2102. TransferUsedRegs(TmpUsedRegs);
  2103. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2104. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2105. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2106. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2107. begin
  2108. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2109. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2110. TransferUsedRegs(TmpUsedRegs);
  2111. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2112. RemoveInstruction(hp1);
  2113. result:=true;
  2114. exit;
  2115. end;
  2116. { special case:
  2117. vmova* reg1,<op>
  2118. ...
  2119. vmova* <op>,reg1
  2120. =>
  2121. vmova* reg1,<op> }
  2122. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2123. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2124. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2125. ) then
  2126. begin
  2127. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2128. RemoveInstruction(hp1);
  2129. result:=true;
  2130. exit;
  2131. end
  2132. end
  2133. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2134. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2135. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2136. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2137. ) and
  2138. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2139. begin
  2140. { vmova* reg1,reg2
  2141. ...
  2142. vmovs* reg2,<op>
  2143. dealloc reg2
  2144. =>
  2145. vmovs* reg1,<op> }
  2146. TransferUsedRegs(TmpUsedRegs);
  2147. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2148. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2149. begin
  2150. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2151. taicpu(p).opcode:=taicpu(hp1).opcode;
  2152. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2153. TransferUsedRegs(TmpUsedRegs);
  2154. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2155. RemoveInstruction(hp1);
  2156. result:=true;
  2157. exit;
  2158. end
  2159. end;
  2160. if MatchInstruction(hp1,[A_VFMADDPD,
  2161. A_VFMADD132PD,
  2162. A_VFMADD132PS,
  2163. A_VFMADD132SD,
  2164. A_VFMADD132SS,
  2165. A_VFMADD213PD,
  2166. A_VFMADD213PS,
  2167. A_VFMADD213SD,
  2168. A_VFMADD213SS,
  2169. A_VFMADD231PD,
  2170. A_VFMADD231PS,
  2171. A_VFMADD231SD,
  2172. A_VFMADD231SS,
  2173. A_VFMADDSUB132PD,
  2174. A_VFMADDSUB132PS,
  2175. A_VFMADDSUB213PD,
  2176. A_VFMADDSUB213PS,
  2177. A_VFMADDSUB231PD,
  2178. A_VFMADDSUB231PS,
  2179. A_VFMSUB132PD,
  2180. A_VFMSUB132PS,
  2181. A_VFMSUB132SD,
  2182. A_VFMSUB132SS,
  2183. A_VFMSUB213PD,
  2184. A_VFMSUB213PS,
  2185. A_VFMSUB213SD,
  2186. A_VFMSUB213SS,
  2187. A_VFMSUB231PD,
  2188. A_VFMSUB231PS,
  2189. A_VFMSUB231SD,
  2190. A_VFMSUB231SS,
  2191. A_VFMSUBADD132PD,
  2192. A_VFMSUBADD132PS,
  2193. A_VFMSUBADD213PD,
  2194. A_VFMSUBADD213PS,
  2195. A_VFMSUBADD231PD,
  2196. A_VFMSUBADD231PS,
  2197. A_VFNMADD132PD,
  2198. A_VFNMADD132PS,
  2199. A_VFNMADD132SD,
  2200. A_VFNMADD132SS,
  2201. A_VFNMADD213PD,
  2202. A_VFNMADD213PS,
  2203. A_VFNMADD213SD,
  2204. A_VFNMADD213SS,
  2205. A_VFNMADD231PD,
  2206. A_VFNMADD231PS,
  2207. A_VFNMADD231SD,
  2208. A_VFNMADD231SS,
  2209. A_VFNMSUB132PD,
  2210. A_VFNMSUB132PS,
  2211. A_VFNMSUB132SD,
  2212. A_VFNMSUB132SS,
  2213. A_VFNMSUB213PD,
  2214. A_VFNMSUB213PS,
  2215. A_VFNMSUB213SD,
  2216. A_VFNMSUB213SS,
  2217. A_VFNMSUB231PD,
  2218. A_VFNMSUB231PS,
  2219. A_VFNMSUB231SD,
  2220. A_VFNMSUB231SS],[S_NO]) and
  2221. { we mix single and double opperations here because we assume that the compiler
  2222. generates vmovapd only after double operations and vmovaps only after single operations }
  2223. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2224. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2225. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2226. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2227. begin
  2228. TransferUsedRegs(TmpUsedRegs);
  2229. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2230. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2231. begin
  2232. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2233. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2234. RemoveCurrentP(p)
  2235. else
  2236. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2237. RemoveInstruction(hp2);
  2238. end;
  2239. end
  2240. else if (hp1.typ = ait_instruction) and
  2241. (((taicpu(p).opcode=A_MOVAPS) and
  2242. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2243. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2244. ((taicpu(p).opcode=A_MOVAPD) and
  2245. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2246. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2247. ) and
  2248. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2249. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2250. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2251. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2252. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2253. { change
  2254. movapX reg,reg2
  2255. addsX/subsX/... reg3, reg2
  2256. movapX reg2,reg
  2257. to
  2258. addsX/subsX/... reg3,reg
  2259. }
  2260. begin
  2261. TransferUsedRegs(TmpUsedRegs);
  2262. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2263. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2264. begin
  2265. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2266. debug_op2str(taicpu(p).opcode)+' '+
  2267. debug_op2str(taicpu(hp1).opcode)+' '+
  2268. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2269. { we cannot eliminate the first move if
  2270. the operations uses the same register for source and dest }
  2271. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2272. { Remember that hp1 is not necessarily the immediate
  2273. next instruction }
  2274. RemoveCurrentP(p);
  2275. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2276. RemoveInstruction(hp2);
  2277. result:=true;
  2278. end;
  2279. end
  2280. else if (hp1.typ = ait_instruction) and
  2281. (((taicpu(p).opcode=A_VMOVAPD) and
  2282. (taicpu(hp1).opcode=A_VCOMISD)) or
  2283. ((taicpu(p).opcode=A_VMOVAPS) and
  2284. ((taicpu(hp1).opcode=A_VCOMISS))
  2285. )
  2286. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2287. { change
  2288. movapX reg,reg1
  2289. vcomisX reg1,reg1
  2290. to
  2291. vcomisX reg,reg
  2292. }
  2293. begin
  2294. TransferUsedRegs(TmpUsedRegs);
  2295. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2296. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2297. begin
  2298. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2299. debug_op2str(taicpu(p).opcode)+' '+
  2300. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2301. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2302. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2303. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2304. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2305. RemoveCurrentP(p);
  2306. result:=true;
  2307. exit;
  2308. end;
  2309. end
  2310. end;
  2311. end;
  2312. end;
  2313. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2314. var
  2315. hp1 : tai;
  2316. begin
  2317. result:=false;
  2318. { replace
  2319. V<Op>X %mreg1,%mreg2,%mreg3
  2320. VMovX %mreg3,%mreg4
  2321. dealloc %mreg3
  2322. by
  2323. V<Op>X %mreg1,%mreg2,%mreg4
  2324. ?
  2325. }
  2326. if GetNextInstruction(p,hp1) and
  2327. { we mix single and double operations here because we assume that the compiler
  2328. generates vmovapd only after double operations and vmovaps only after single operations }
  2329. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2330. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2331. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2332. begin
  2333. TransferUsedRegs(TmpUsedRegs);
  2334. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2335. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2336. begin
  2337. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2338. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2339. RemoveInstruction(hp1);
  2340. result:=true;
  2341. end;
  2342. end;
  2343. end;
  2344. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2345. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2346. begin
  2347. Result := False;
  2348. { For safety reasons, only check for exact register matches }
  2349. { Check base register }
  2350. if (ref.base = AOldReg) then
  2351. begin
  2352. ref.base := ANewReg;
  2353. Result := True;
  2354. end;
  2355. { Check index register }
  2356. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2357. begin
  2358. ref.index := ANewReg;
  2359. Result := True;
  2360. end;
  2361. end;
  2362. { Replaces all references to AOldReg in an operand to ANewReg }
  2363. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2364. var
  2365. OldSupReg, NewSupReg: TSuperRegister;
  2366. OldSubReg, NewSubReg: TSubRegister;
  2367. OldRegType: TRegisterType;
  2368. ThisOper: POper;
  2369. begin
  2370. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2371. Result := False;
  2372. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2373. InternalError(2020011801);
  2374. OldSupReg := getsupreg(AOldReg);
  2375. OldSubReg := getsubreg(AOldReg);
  2376. OldRegType := getregtype(AOldReg);
  2377. NewSupReg := getsupreg(ANewReg);
  2378. NewSubReg := getsubreg(ANewReg);
  2379. if OldRegType <> getregtype(ANewReg) then
  2380. InternalError(2020011802);
  2381. if OldSubReg <> NewSubReg then
  2382. InternalError(2020011803);
  2383. case ThisOper^.typ of
  2384. top_reg:
  2385. if (
  2386. (ThisOper^.reg = AOldReg) or
  2387. (
  2388. (OldRegType = R_INTREGISTER) and
  2389. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2390. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2391. (
  2392. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2393. {$ifndef x86_64}
  2394. and (
  2395. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2396. don't have an 8-bit representation }
  2397. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2398. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2399. )
  2400. {$endif x86_64}
  2401. )
  2402. )
  2403. ) then
  2404. begin
  2405. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2406. Result := True;
  2407. end;
  2408. top_ref:
  2409. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2410. Result := True;
  2411. else
  2412. ;
  2413. end;
  2414. end;
  2415. { Replaces all references to AOldReg in an instruction to ANewReg }
  2416. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2417. const
  2418. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2419. var
  2420. OperIdx: Integer;
  2421. begin
  2422. Result := False;
  2423. for OperIdx := 0 to p.ops - 1 do
  2424. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2425. begin
  2426. { The shift and rotate instructions can only use CL }
  2427. if not (
  2428. (OperIdx = 0) and
  2429. { This second condition just helps to avoid unnecessarily
  2430. calling MatchInstruction for 10 different opcodes }
  2431. (p.oper[0]^.reg = NR_CL) and
  2432. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2433. ) then
  2434. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2435. end
  2436. else if p.oper[OperIdx]^.typ = top_ref then
  2437. { It's okay to replace registers in references that get written to }
  2438. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2439. end;
  2440. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2441. begin
  2442. Result :=
  2443. (ref^.index = NR_NO) and
  2444. (
  2445. {$ifdef x86_64}
  2446. (
  2447. (ref^.base = NR_RIP) and
  2448. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2449. ) or
  2450. {$endif x86_64}
  2451. (ref^.refaddr = addr_full) or
  2452. (ref^.base = NR_STACK_POINTER_REG) or
  2453. (ref^.base = current_procinfo.framepointer)
  2454. );
  2455. end;
  2456. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2457. var
  2458. l: asizeint;
  2459. begin
  2460. Result := False;
  2461. { Should have been checked previously }
  2462. if p.opcode <> A_LEA then
  2463. InternalError(2020072501);
  2464. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2465. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2466. not(cs_opt_size in current_settings.optimizerswitches) then
  2467. exit;
  2468. with p.oper[0]^.ref^ do
  2469. begin
  2470. if (base <> p.oper[1]^.reg) or
  2471. (index <> NR_NO) or
  2472. assigned(symbol) then
  2473. exit;
  2474. l:=offset;
  2475. if (l=1) and UseIncDec then
  2476. begin
  2477. p.opcode:=A_INC;
  2478. p.loadreg(0,p.oper[1]^.reg);
  2479. p.ops:=1;
  2480. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2481. end
  2482. else if (l=-1) and UseIncDec then
  2483. begin
  2484. p.opcode:=A_DEC;
  2485. p.loadreg(0,p.oper[1]^.reg);
  2486. p.ops:=1;
  2487. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2488. end
  2489. else
  2490. begin
  2491. if (l<0) and (l<>-2147483648) then
  2492. begin
  2493. p.opcode:=A_SUB;
  2494. p.loadConst(0,-l);
  2495. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2496. end
  2497. else
  2498. begin
  2499. p.opcode:=A_ADD;
  2500. p.loadConst(0,l);
  2501. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2502. end;
  2503. end;
  2504. end;
  2505. Result := True;
  2506. end;
  2507. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2508. var
  2509. CurrentReg, ReplaceReg: TRegister;
  2510. begin
  2511. Result := False;
  2512. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2513. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2514. case hp.opcode of
  2515. A_FSTSW, A_FNSTSW,
  2516. A_IN, A_INS, A_OUT, A_OUTS,
  2517. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2518. { These routines have explicit operands, but they are restricted in
  2519. what they can be (e.g. IN and OUT can only read from AL, AX or
  2520. EAX. }
  2521. Exit;
  2522. A_IMUL:
  2523. begin
  2524. { The 1-operand version writes to implicit registers
  2525. The 2-operand version reads from the first operator, and reads
  2526. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2527. the 3-operand version reads from a register that it doesn't write to
  2528. }
  2529. case hp.ops of
  2530. 1:
  2531. if (
  2532. (
  2533. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2534. ) or
  2535. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2536. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2537. begin
  2538. Result := True;
  2539. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2540. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2541. end;
  2542. 2:
  2543. { Only modify the first parameter }
  2544. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2545. begin
  2546. Result := True;
  2547. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2548. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2549. end;
  2550. 3:
  2551. { Only modify the second parameter }
  2552. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2553. begin
  2554. Result := True;
  2555. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2556. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2557. end;
  2558. else
  2559. InternalError(2020012901);
  2560. end;
  2561. end;
  2562. else
  2563. if (hp.ops > 0) and
  2564. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2565. begin
  2566. Result := True;
  2567. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2568. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2569. end;
  2570. end;
  2571. end;
  2572. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2573. var
  2574. hp2: tai;
  2575. p_SourceReg, p_TargetReg: TRegister;
  2576. begin
  2577. Result := False;
  2578. { Backward optimisation. If we have:
  2579. func. %reg1,%reg2
  2580. mov %reg2,%reg3
  2581. (dealloc %reg2)
  2582. Change to:
  2583. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2584. Perform similar optimisations with 1, 3 and 4-operand instructions
  2585. that only have one output.
  2586. }
  2587. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2588. begin
  2589. p_SourceReg := taicpu(p).oper[0]^.reg;
  2590. p_TargetReg := taicpu(p).oper[1]^.reg;
  2591. TransferUsedRegs(TmpUsedRegs);
  2592. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2593. GetLastInstruction(p, hp2) and
  2594. (hp2.typ = ait_instruction) and
  2595. { Have to make sure it's an instruction that only reads from
  2596. the first operands and only writes (not reads or modifies) to
  2597. the last one; in essence, a pure function such as BSR, POPCNT
  2598. or ANDN }
  2599. (
  2600. (
  2601. (taicpu(hp2).ops = 1) and
  2602. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2603. ) or
  2604. (
  2605. (taicpu(hp2).ops = 2) and
  2606. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2607. ) or
  2608. (
  2609. (taicpu(hp2).ops = 3) and
  2610. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2611. ) or
  2612. (
  2613. (taicpu(hp2).ops = 4) and
  2614. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2615. )
  2616. ) and
  2617. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2618. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2619. begin
  2620. case taicpu(hp2).opcode of
  2621. A_FSTSW, A_FNSTSW,
  2622. A_IN, A_INS, A_OUT, A_OUTS,
  2623. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2624. { These routines have explicit operands, but they are restricted in
  2625. what they can be (e.g. IN and OUT can only read from AL, AX or
  2626. EAX. }
  2627. ;
  2628. else
  2629. begin
  2630. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2631. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2632. if not RegInInstruction(p_TargetReg, hp2) then
  2633. begin
  2634. { Since we're allocating from an earlier point, we
  2635. need to remove the register from the tracking }
  2636. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2637. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2638. end;
  2639. RemoveCurrentp(p, hp1);
  2640. { If the Func was another MOV instruction, we might get
  2641. "mov %reg,%reg" that doesn't get removed in Pass 2
  2642. otherwise, so deal with it here (also do something
  2643. similar with lea (%reg),%reg}
  2644. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2645. begin
  2646. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2647. if p = hp2 then
  2648. RemoveCurrentp(p)
  2649. else
  2650. RemoveInstruction(hp2);
  2651. end;
  2652. Result := True;
  2653. Exit;
  2654. end;
  2655. end;
  2656. end;
  2657. end;
  2658. end;
  2659. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2660. begin
  2661. Result := False;
  2662. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2663. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2664. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2665. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2666. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2667. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2668. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2669. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2670. begin
  2671. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2672. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2673. Result := True;
  2674. end;
  2675. end;
  2676. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2677. var
  2678. hp1, hp2, hp3, hp4: tai;
  2679. DoOptimisation, TempBool: Boolean;
  2680. {$ifdef x86_64}
  2681. NewConst: TCGInt;
  2682. {$endif x86_64}
  2683. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2684. begin
  2685. if taicpu(hp1).opcode = signed_movop then
  2686. begin
  2687. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2688. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2689. end
  2690. else
  2691. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2692. end;
  2693. function TryConstMerge(var p1, p2: tai): Boolean;
  2694. var
  2695. ThisRef: TReference;
  2696. begin
  2697. Result := False;
  2698. ThisRef := taicpu(p2).oper[1]^.ref^;
  2699. { Only permit writes to the stack, since we can guarantee alignment with that }
  2700. if (ThisRef.index = NR_NO) and
  2701. (
  2702. (ThisRef.base = NR_STACK_POINTER_REG) or
  2703. (ThisRef.base = current_procinfo.framepointer)
  2704. ) then
  2705. begin
  2706. case taicpu(p).opsize of
  2707. S_B:
  2708. begin
  2709. { Word writes must be on a 2-byte boundary }
  2710. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2711. begin
  2712. { Reduce offset of second reference to see if it is sequential with the first }
  2713. Dec(ThisRef.offset, 1);
  2714. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2715. begin
  2716. { Make sure the constants aren't represented as a
  2717. negative number, as these won't merge properly }
  2718. taicpu(p1).opsize := S_W;
  2719. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2720. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2721. RemoveInstruction(p2);
  2722. Result := True;
  2723. end;
  2724. end;
  2725. end;
  2726. S_W:
  2727. begin
  2728. { Longword writes must be on a 4-byte boundary }
  2729. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2730. begin
  2731. { Reduce offset of second reference to see if it is sequential with the first }
  2732. Dec(ThisRef.offset, 2);
  2733. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2734. begin
  2735. { Make sure the constants aren't represented as a
  2736. negative number, as these won't merge properly }
  2737. taicpu(p1).opsize := S_L;
  2738. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2739. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2740. RemoveInstruction(p2);
  2741. Result := True;
  2742. end;
  2743. end;
  2744. end;
  2745. {$ifdef x86_64}
  2746. S_L:
  2747. begin
  2748. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2749. see if the constants can be encoded this way. }
  2750. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2751. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2752. { Quadword writes must be on an 8-byte boundary }
  2753. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2754. begin
  2755. { Reduce offset of second reference to see if it is sequential with the first }
  2756. Dec(ThisRef.offset, 4);
  2757. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2758. begin
  2759. { Make sure the constants aren't represented as a
  2760. negative number, as these won't merge properly }
  2761. taicpu(p1).opsize := S_Q;
  2762. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2763. taicpu(p1).oper[0]^.val := NewConst;
  2764. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2765. RemoveInstruction(p2);
  2766. Result := True;
  2767. end;
  2768. end;
  2769. end;
  2770. {$endif x86_64}
  2771. else
  2772. ;
  2773. end;
  2774. end;
  2775. end;
  2776. var
  2777. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2778. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2779. NewSize: topsize; NewOffset: asizeint;
  2780. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2781. SourceRef, TargetRef: TReference;
  2782. MovAligned, MovUnaligned: TAsmOp;
  2783. ThisRef: TReference;
  2784. JumpTracking: TLinkedList;
  2785. begin
  2786. Result:=false;
  2787. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2788. { remove mov reg1,reg1? }
  2789. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2790. then
  2791. begin
  2792. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2793. { take care of the register (de)allocs following p }
  2794. RemoveCurrentP(p, hp1);
  2795. Result:=true;
  2796. exit;
  2797. end;
  2798. { All the next optimisations require a next instruction }
  2799. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2800. Exit;
  2801. { Prevent compiler warnings }
  2802. p_TargetReg := NR_NO;
  2803. if taicpu(p).oper[1]^.typ = top_reg then
  2804. begin
  2805. { Saves on a large number of dereferences }
  2806. p_TargetReg := taicpu(p).oper[1]^.reg;
  2807. { Look for:
  2808. mov %reg1,%reg2
  2809. ??? %reg2,r/m
  2810. Change to:
  2811. mov %reg1,%reg2
  2812. ??? %reg1,r/m
  2813. }
  2814. if taicpu(p).oper[0]^.typ = top_reg then
  2815. begin
  2816. if RegReadByInstruction(p_TargetReg, hp1) and
  2817. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2818. begin
  2819. { A change has occurred, just not in p }
  2820. Result := True;
  2821. TransferUsedRegs(TmpUsedRegs);
  2822. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2823. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2824. { Just in case something didn't get modified (e.g. an
  2825. implicit register) }
  2826. not RegReadByInstruction(p_TargetReg, hp1) then
  2827. begin
  2828. { We can remove the original MOV }
  2829. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2830. RemoveCurrentp(p, hp1);
  2831. { UsedRegs got updated by RemoveCurrentp }
  2832. Result := True;
  2833. Exit;
  2834. end;
  2835. { If we know a MOV instruction has become a null operation, we might as well
  2836. get rid of it now to save time. }
  2837. if (taicpu(hp1).opcode = A_MOV) and
  2838. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2839. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2840. { Just being a register is enough to confirm it's a null operation }
  2841. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2842. begin
  2843. Result := True;
  2844. { Speed-up to reduce a pipeline stall... if we had something like...
  2845. movl %eax,%edx
  2846. movw %dx,%ax
  2847. ... the second instruction would change to movw %ax,%ax, but
  2848. given that it is now %ax that's active rather than %eax,
  2849. penalties might occur due to a partial register write, so instead,
  2850. change it to a MOVZX instruction when optimising for speed.
  2851. }
  2852. if not (cs_opt_size in current_settings.optimizerswitches) and
  2853. IsMOVZXAcceptable and
  2854. (taicpu(hp1).opsize < taicpu(p).opsize)
  2855. {$ifdef x86_64}
  2856. { operations already implicitly set the upper 64 bits to zero }
  2857. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2858. {$endif x86_64}
  2859. then
  2860. begin
  2861. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2862. case taicpu(p).opsize of
  2863. S_W:
  2864. if taicpu(hp1).opsize = S_B then
  2865. taicpu(hp1).opsize := S_BL
  2866. else
  2867. InternalError(2020012911);
  2868. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2869. case taicpu(hp1).opsize of
  2870. S_B:
  2871. taicpu(hp1).opsize := S_BL;
  2872. S_W:
  2873. taicpu(hp1).opsize := S_WL;
  2874. else
  2875. InternalError(2020012912);
  2876. end;
  2877. else
  2878. InternalError(2020012910);
  2879. end;
  2880. taicpu(hp1).opcode := A_MOVZX;
  2881. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2882. end
  2883. else
  2884. begin
  2885. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2886. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2887. RemoveInstruction(hp1);
  2888. { The instruction after what was hp1 is now the immediate next instruction,
  2889. so we can continue to make optimisations if it's present }
  2890. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2891. Exit;
  2892. hp1 := hp2;
  2893. end;
  2894. end;
  2895. end;
  2896. end;
  2897. end;
  2898. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2899. overwrites the original destination register. e.g.
  2900. movl ###,%reg2d
  2901. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2902. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2903. }
  2904. if (taicpu(p).oper[1]^.typ = top_reg) and
  2905. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2906. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2907. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2908. begin
  2909. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2910. begin
  2911. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2912. case taicpu(p).oper[0]^.typ of
  2913. top_const:
  2914. { We have something like:
  2915. movb $x, %regb
  2916. movzbl %regb,%regd
  2917. Change to:
  2918. movl $x, %regd
  2919. }
  2920. begin
  2921. case taicpu(hp1).opsize of
  2922. S_BW:
  2923. begin
  2924. convert_mov_value(A_MOVSX, $FF);
  2925. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2926. taicpu(p).opsize := S_W;
  2927. end;
  2928. S_BL:
  2929. begin
  2930. convert_mov_value(A_MOVSX, $FF);
  2931. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2932. taicpu(p).opsize := S_L;
  2933. end;
  2934. S_WL:
  2935. begin
  2936. convert_mov_value(A_MOVSX, $FFFF);
  2937. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2938. taicpu(p).opsize := S_L;
  2939. end;
  2940. {$ifdef x86_64}
  2941. S_BQ:
  2942. begin
  2943. convert_mov_value(A_MOVSX, $FF);
  2944. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2945. taicpu(p).opsize := S_Q;
  2946. end;
  2947. S_WQ:
  2948. begin
  2949. convert_mov_value(A_MOVSX, $FFFF);
  2950. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2951. taicpu(p).opsize := S_Q;
  2952. end;
  2953. S_LQ:
  2954. begin
  2955. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2956. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2957. taicpu(p).opsize := S_Q;
  2958. end;
  2959. {$endif x86_64}
  2960. else
  2961. { If hp1 was a MOV instruction, it should have been
  2962. optimised already }
  2963. InternalError(2020021001);
  2964. end;
  2965. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2966. RemoveInstruction(hp1);
  2967. Result := True;
  2968. Exit;
  2969. end;
  2970. top_ref:
  2971. begin
  2972. { We have something like:
  2973. movb mem, %regb
  2974. movzbl %regb,%regd
  2975. Change to:
  2976. movzbl mem, %regd
  2977. }
  2978. ThisRef := taicpu(p).oper[0]^.ref^;
  2979. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2980. begin
  2981. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2982. taicpu(hp1).loadref(0, ThisRef);
  2983. { Make sure any registers in the references are properly tracked }
  2984. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2985. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2986. if (ThisRef.index <> NR_NO) then
  2987. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2988. RemoveCurrentP(p, hp1);
  2989. Result := True;
  2990. Exit;
  2991. end;
  2992. end;
  2993. else
  2994. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2995. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2996. Exit;
  2997. end;
  2998. end
  2999. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3000. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3001. optimised }
  3002. else
  3003. begin
  3004. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3005. RemoveCurrentP(p, hp1);
  3006. Result := True;
  3007. Exit;
  3008. end;
  3009. end;
  3010. if (taicpu(hp1).opcode = A_AND) and
  3011. (taicpu(p).oper[1]^.typ = top_reg) and
  3012. MatchOpType(taicpu(hp1),top_const,top_reg) then
  3013. begin
  3014. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  3015. begin
  3016. case taicpu(p).opsize of
  3017. S_L:
  3018. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  3019. begin
  3020. { Optimize out:
  3021. mov x, %reg
  3022. and ffffffffh, %reg
  3023. }
  3024. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  3025. RemoveInstruction(hp1);
  3026. Result:=true;
  3027. exit;
  3028. end;
  3029. S_Q: { TODO: Confirm if this is even possible }
  3030. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  3031. begin
  3032. { Optimize out:
  3033. mov x, %reg
  3034. and ffffffffffffffffh, %reg
  3035. }
  3036. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  3037. RemoveInstruction(hp1);
  3038. Result:=true;
  3039. exit;
  3040. end;
  3041. else
  3042. ;
  3043. end;
  3044. if (
  3045. (taicpu(p).oper[0]^.typ=top_reg) or
  3046. (
  3047. (taicpu(p).oper[0]^.typ=top_ref) and
  3048. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3049. )
  3050. ) and
  3051. GetNextInstruction(hp1,hp2) and
  3052. MatchInstruction(hp2,A_TEST,[]) and
  3053. (
  3054. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3055. (
  3056. { If the register being tested is smaller than the one
  3057. that received a bitwise AND, permit it if the constant
  3058. fits into the smaller size }
  3059. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3060. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3061. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3062. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3063. (
  3064. (
  3065. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3066. (taicpu(hp1).oper[0]^.val <= $FF)
  3067. ) or
  3068. (
  3069. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3070. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3071. {$ifdef x86_64}
  3072. ) or
  3073. (
  3074. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3075. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3076. {$endif x86_64}
  3077. )
  3078. )
  3079. )
  3080. ) and
  3081. (
  3082. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3083. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3084. ) and
  3085. GetNextInstruction(hp2,hp3) and
  3086. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3087. (taicpu(hp3).condition in [C_E,C_NE]) then
  3088. begin
  3089. TransferUsedRegs(TmpUsedRegs);
  3090. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3091. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3092. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3093. begin
  3094. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3095. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3096. taicpu(hp1).opcode:=A_TEST;
  3097. { Shrink the TEST instruction down to the smallest possible size }
  3098. case taicpu(hp1).oper[0]^.val of
  3099. 0..255:
  3100. if (taicpu(hp1).opsize <> S_B)
  3101. {$ifndef x86_64}
  3102. and (
  3103. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3104. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3105. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3106. )
  3107. {$endif x86_64}
  3108. then
  3109. begin
  3110. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3111. { Only print debug message if the TEST instruction
  3112. is a different size before and after }
  3113. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3114. taicpu(hp1).opsize := S_B;
  3115. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3116. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3117. end;
  3118. 256..65535:
  3119. if (taicpu(hp1).opsize <> S_W) then
  3120. begin
  3121. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3122. { Only print debug message if the TEST instruction
  3123. is a different size before and after }
  3124. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3125. taicpu(hp1).opsize := S_W;
  3126. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3127. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3128. end;
  3129. {$ifdef x86_64}
  3130. 65536..$7FFFFFFF:
  3131. if (taicpu(hp1).opsize <> S_L) then
  3132. begin
  3133. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3134. { Only print debug message if the TEST instruction
  3135. is a different size before and after }
  3136. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3137. taicpu(hp1).opsize := S_L;
  3138. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3139. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3140. end;
  3141. {$endif x86_64}
  3142. else
  3143. ;
  3144. end;
  3145. RemoveInstruction(hp2);
  3146. RemoveCurrentP(p, hp1);
  3147. Result:=true;
  3148. exit;
  3149. end;
  3150. end;
  3151. end
  3152. else if IsMOVZXAcceptable and
  3153. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3154. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3155. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3156. then
  3157. begin
  3158. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3159. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3160. case taicpu(p).opsize of
  3161. S_B:
  3162. if (taicpu(hp1).oper[0]^.val = $ff) then
  3163. begin
  3164. { Convert:
  3165. movb x, %regl movb x, %regl
  3166. andw ffh, %regw andl ffh, %regd
  3167. To:
  3168. movzbw x, %regd movzbl x, %regd
  3169. (Identical registers, just different sizes)
  3170. }
  3171. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3172. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3173. case taicpu(hp1).opsize of
  3174. S_W: NewSize := S_BW;
  3175. S_L: NewSize := S_BL;
  3176. {$ifdef x86_64}
  3177. S_Q: NewSize := S_BQ;
  3178. {$endif x86_64}
  3179. else
  3180. InternalError(2018011510);
  3181. end;
  3182. end
  3183. else
  3184. NewSize := S_NO;
  3185. S_W:
  3186. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3187. begin
  3188. { Convert:
  3189. movw x, %regw
  3190. andl ffffh, %regd
  3191. To:
  3192. movzwl x, %regd
  3193. (Identical registers, just different sizes)
  3194. }
  3195. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3196. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3197. case taicpu(hp1).opsize of
  3198. S_L: NewSize := S_WL;
  3199. {$ifdef x86_64}
  3200. S_Q: NewSize := S_WQ;
  3201. {$endif x86_64}
  3202. else
  3203. InternalError(2018011511);
  3204. end;
  3205. end
  3206. else
  3207. NewSize := S_NO;
  3208. else
  3209. NewSize := S_NO;
  3210. end;
  3211. if NewSize <> S_NO then
  3212. begin
  3213. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3214. { The actual optimization }
  3215. taicpu(p).opcode := A_MOVZX;
  3216. taicpu(p).changeopsize(NewSize);
  3217. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3218. { Safeguard if "and" is followed by a conditional command }
  3219. TransferUsedRegs(TmpUsedRegs);
  3220. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3221. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3222. begin
  3223. { At this point, the "and" command is effectively equivalent to
  3224. "test %reg,%reg". This will be handled separately by the
  3225. Peephole Optimizer. [Kit] }
  3226. DebugMsg(SPeepholeOptimization + PreMessage +
  3227. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3228. end
  3229. else
  3230. begin
  3231. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3232. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3233. RemoveInstruction(hp1);
  3234. end;
  3235. Result := True;
  3236. Exit;
  3237. end;
  3238. end;
  3239. end;
  3240. if (taicpu(hp1).opcode = A_OR) and
  3241. (taicpu(p).oper[1]^.typ = top_reg) and
  3242. MatchOperand(taicpu(p).oper[0]^, 0) and
  3243. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3244. begin
  3245. { mov 0, %reg
  3246. or ###,%reg
  3247. Change to (only if the flags are not used):
  3248. mov ###,%reg
  3249. }
  3250. TransferUsedRegs(TmpUsedRegs);
  3251. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3252. DoOptimisation := True;
  3253. { Even if the flags are used, we might be able to do the optimisation
  3254. if the conditions are predictable }
  3255. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3256. begin
  3257. { Only perform if ### = %reg (the same register) or equal to 0,
  3258. so %reg is guaranteed to still have a value of zero }
  3259. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3260. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3261. begin
  3262. hp2 := hp1;
  3263. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3264. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3265. GetNextInstruction(hp2, hp3) do
  3266. begin
  3267. { Don't continue modifying if the flags state is getting changed }
  3268. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3269. Break;
  3270. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3271. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3272. begin
  3273. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3274. begin
  3275. { Condition is always true }
  3276. case taicpu(hp3).opcode of
  3277. A_Jcc:
  3278. begin
  3279. { Check for jump shortcuts before we destroy the condition }
  3280. hp4 := hp3;
  3281. DoJumpOptimizations(hp3, TempBool);
  3282. { Make sure hp3 hasn't changed }
  3283. if (hp4 = hp3) then
  3284. begin
  3285. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3286. MakeUnconditional(taicpu(hp3));
  3287. end;
  3288. Result := True;
  3289. end;
  3290. A_CMOVcc:
  3291. begin
  3292. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3293. taicpu(hp3).opcode := A_MOV;
  3294. taicpu(hp3).condition := C_None;
  3295. Result := True;
  3296. end;
  3297. A_SETcc:
  3298. begin
  3299. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3300. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3301. taicpu(hp3).opcode := A_MOV;
  3302. taicpu(hp3).ops := 2;
  3303. taicpu(hp3).condition := C_None;
  3304. taicpu(hp3).opsize := S_B;
  3305. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3306. taicpu(hp3).loadconst(0, 1);
  3307. Result := True;
  3308. end;
  3309. else
  3310. InternalError(2021090701);
  3311. end;
  3312. end
  3313. 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
  3314. begin
  3315. { Condition is always false }
  3316. case taicpu(hp3).opcode of
  3317. A_Jcc:
  3318. begin
  3319. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3320. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3321. RemoveInstruction(hp3);
  3322. Result := True;
  3323. { Since hp3 was deleted, hp2 must not be updated }
  3324. Continue;
  3325. end;
  3326. A_CMOVcc:
  3327. begin
  3328. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3329. RemoveInstruction(hp3);
  3330. Result := True;
  3331. { Since hp3 was deleted, hp2 must not be updated }
  3332. Continue;
  3333. end;
  3334. A_SETcc:
  3335. begin
  3336. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3337. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3338. taicpu(hp3).opcode := A_MOV;
  3339. taicpu(hp3).ops := 2;
  3340. taicpu(hp3).condition := C_None;
  3341. taicpu(hp3).opsize := S_B;
  3342. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3343. taicpu(hp3).loadconst(0, 0);
  3344. Result := True;
  3345. end;
  3346. else
  3347. InternalError(2021090702);
  3348. end;
  3349. end
  3350. else
  3351. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3352. DoOptimisation := False;
  3353. end;
  3354. hp2 := hp3;
  3355. end;
  3356. { Flags are still in use - don't optimise }
  3357. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3358. DoOptimisation := False;
  3359. end
  3360. else
  3361. DoOptimisation := False;
  3362. end;
  3363. if DoOptimisation then
  3364. begin
  3365. {$ifdef x86_64}
  3366. { OR only supports 32-bit sign-extended constants for 64-bit
  3367. instructions, so compensate for this if the constant is
  3368. encoded as a value greater than or equal to 2^31 }
  3369. if (taicpu(hp1).opsize = S_Q) and
  3370. (taicpu(hp1).oper[0]^.typ = top_const) and
  3371. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3372. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3373. {$endif x86_64}
  3374. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3375. taicpu(hp1).opcode := A_MOV;
  3376. RemoveCurrentP(p, hp1);
  3377. Result := True;
  3378. Exit;
  3379. end;
  3380. end;
  3381. { Next instruction is also a MOV ? }
  3382. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3383. begin
  3384. if MatchOpType(taicpu(p), top_const, top_ref) and
  3385. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3386. TryConstMerge(p, hp1) then
  3387. begin
  3388. Result := True;
  3389. { In case we have four byte writes in a row, check for 2 more
  3390. right now so we don't have to wait for another iteration of
  3391. pass 1
  3392. }
  3393. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3394. case taicpu(p).opsize of
  3395. S_W:
  3396. begin
  3397. if GetNextInstruction(p, hp1) and
  3398. MatchInstruction(hp1, A_MOV, [S_B]) and
  3399. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3400. GetNextInstruction(hp1, hp2) and
  3401. MatchInstruction(hp2, A_MOV, [S_B]) and
  3402. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3403. { Try to merge the two bytes }
  3404. TryConstMerge(hp1, hp2) then
  3405. { Now try to merge the two words (hp2 will get deleted) }
  3406. TryConstMerge(p, hp1);
  3407. end;
  3408. S_L:
  3409. begin
  3410. { Though this only really benefits x86_64 and not i386, it
  3411. gets a potential optimisation done faster and hence
  3412. reduces the number of times OptPass1MOV is entered }
  3413. if GetNextInstruction(p, hp1) and
  3414. MatchInstruction(hp1, A_MOV, [S_W]) and
  3415. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3416. GetNextInstruction(hp1, hp2) and
  3417. MatchInstruction(hp2, A_MOV, [S_W]) and
  3418. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3419. { Try to merge the two words }
  3420. TryConstMerge(hp1, hp2) then
  3421. { This will always fail on i386, so don't bother
  3422. calling it unless we're doing x86_64 }
  3423. {$ifdef x86_64}
  3424. { Now try to merge the two longwords (hp2 will get deleted) }
  3425. TryConstMerge(p, hp1)
  3426. {$endif x86_64}
  3427. ;
  3428. end;
  3429. else
  3430. ;
  3431. end;
  3432. Exit;
  3433. end;
  3434. if (taicpu(p).oper[1]^.typ = top_reg) and
  3435. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3436. begin
  3437. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3438. TransferUsedRegs(TmpUsedRegs);
  3439. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3440. { we have
  3441. mov x, %treg
  3442. mov %treg, y
  3443. }
  3444. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3445. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3446. { we've got
  3447. mov x, %treg
  3448. mov %treg, y
  3449. with %treg is not used after }
  3450. case taicpu(p).oper[0]^.typ Of
  3451. { top_reg is covered by DeepMOVOpt }
  3452. top_const:
  3453. begin
  3454. { change
  3455. mov const, %treg
  3456. mov %treg, y
  3457. to
  3458. mov const, y
  3459. }
  3460. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3461. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3462. begin
  3463. if taicpu(hp1).oper[1]^.typ=top_reg then
  3464. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3465. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3466. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3467. RemoveInstruction(hp1);
  3468. Result:=true;
  3469. Exit;
  3470. end;
  3471. end;
  3472. top_ref:
  3473. case taicpu(hp1).oper[1]^.typ of
  3474. top_reg:
  3475. begin
  3476. { change
  3477. mov mem, %treg
  3478. mov %treg, %reg
  3479. to
  3480. mov mem, %reg"
  3481. }
  3482. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3483. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3484. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3485. RemoveInstruction(hp1);
  3486. Result:=true;
  3487. Exit;
  3488. end;
  3489. top_ref:
  3490. begin
  3491. {$ifdef x86_64}
  3492. { Look for the following to simplify:
  3493. mov x(mem1), %reg
  3494. mov %reg, y(mem2)
  3495. mov x+8(mem1), %reg
  3496. mov %reg, y+8(mem2)
  3497. Change to:
  3498. movdqu x(mem1), %xmmreg
  3499. movdqu %xmmreg, y(mem2)
  3500. ...but only as long as the memory blocks don't overlap
  3501. }
  3502. SourceRef := taicpu(p).oper[0]^.ref^;
  3503. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3504. if (taicpu(p).opsize = S_Q) and
  3505. GetNextInstruction(hp1, hp2) and
  3506. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3507. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3508. begin
  3509. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3510. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3511. Inc(SourceRef.offset, 8);
  3512. if UseAVX then
  3513. begin
  3514. MovAligned := A_VMOVDQA;
  3515. MovUnaligned := A_VMOVDQU;
  3516. end
  3517. else
  3518. begin
  3519. MovAligned := A_MOVDQA;
  3520. MovUnaligned := A_MOVDQU;
  3521. end;
  3522. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3523. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3524. begin
  3525. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3526. Inc(TargetRef.offset, 8);
  3527. if GetNextInstruction(hp2, hp3) and
  3528. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3529. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3530. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3531. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3532. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3533. begin
  3534. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3535. if NewMMReg <> NR_NO then
  3536. begin
  3537. { Remember that the offsets are 8 ahead }
  3538. if ((SourceRef.offset mod 16) = 8) and
  3539. (
  3540. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3541. (SourceRef.base = current_procinfo.framepointer) or
  3542. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3543. ) then
  3544. taicpu(p).opcode := MovAligned
  3545. else
  3546. taicpu(p).opcode := MovUnaligned;
  3547. taicpu(p).opsize := S_XMM;
  3548. taicpu(p).oper[1]^.reg := NewMMReg;
  3549. if ((TargetRef.offset mod 16) = 8) and
  3550. (
  3551. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3552. (TargetRef.base = current_procinfo.framepointer) or
  3553. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3554. ) then
  3555. taicpu(hp1).opcode := MovAligned
  3556. else
  3557. taicpu(hp1).opcode := MovUnaligned;
  3558. taicpu(hp1).opsize := S_XMM;
  3559. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3560. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3561. RemoveInstruction(hp2);
  3562. RemoveInstruction(hp3);
  3563. Result := True;
  3564. Exit;
  3565. end;
  3566. end;
  3567. end
  3568. else
  3569. begin
  3570. { See if the next references are 8 less rather than 8 greater }
  3571. Dec(SourceRef.offset, 16); { -8 the other way }
  3572. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3573. begin
  3574. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3575. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3576. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3577. GetNextInstruction(hp2, hp3) and
  3578. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3579. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3580. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3581. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3582. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3583. begin
  3584. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3585. if NewMMReg <> NR_NO then
  3586. begin
  3587. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3588. if ((SourceRef.offset mod 16) = 0) and
  3589. (
  3590. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3591. (SourceRef.base = current_procinfo.framepointer) or
  3592. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3593. ) then
  3594. taicpu(hp2).opcode := MovAligned
  3595. else
  3596. taicpu(hp2).opcode := MovUnaligned;
  3597. taicpu(hp2).opsize := S_XMM;
  3598. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3599. if ((TargetRef.offset mod 16) = 0) and
  3600. (
  3601. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3602. (TargetRef.base = current_procinfo.framepointer) or
  3603. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3604. ) then
  3605. taicpu(hp3).opcode := MovAligned
  3606. else
  3607. taicpu(hp3).opcode := MovUnaligned;
  3608. taicpu(hp3).opsize := S_XMM;
  3609. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3610. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3611. RemoveInstruction(hp1);
  3612. RemoveCurrentP(p, hp2);
  3613. Result := True;
  3614. Exit;
  3615. end;
  3616. end;
  3617. end;
  3618. end;
  3619. end;
  3620. {$endif x86_64}
  3621. end;
  3622. else
  3623. { The write target should be a reg or a ref }
  3624. InternalError(2021091601);
  3625. end;
  3626. else
  3627. ;
  3628. end
  3629. else
  3630. { %treg is used afterwards, but all eventualities
  3631. other than the first MOV instruction being a constant
  3632. are covered by DeepMOVOpt, so only check for that }
  3633. if (taicpu(p).oper[0]^.typ = top_const) and
  3634. (
  3635. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3636. not (cs_opt_size in current_settings.optimizerswitches) or
  3637. (taicpu(hp1).opsize = S_B)
  3638. ) and
  3639. (
  3640. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3641. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3642. ) then
  3643. begin
  3644. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3645. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3646. end;
  3647. end;
  3648. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3649. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3650. { mov reg1, mem1 or mov mem1, reg1
  3651. mov mem2, reg2 mov reg2, mem2}
  3652. begin
  3653. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3654. { mov reg1, mem1 or mov mem1, reg1
  3655. mov mem2, reg1 mov reg2, mem1}
  3656. begin
  3657. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3658. { Removes the second statement from
  3659. mov reg1, mem1/reg2
  3660. mov mem1/reg2, reg1 }
  3661. begin
  3662. if taicpu(p).oper[0]^.typ=top_reg then
  3663. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3664. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3665. RemoveInstruction(hp1);
  3666. Result:=true;
  3667. exit;
  3668. end
  3669. else
  3670. begin
  3671. TransferUsedRegs(TmpUsedRegs);
  3672. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3673. if (taicpu(p).oper[1]^.typ = top_ref) and
  3674. { mov reg1, mem1
  3675. mov mem2, reg1 }
  3676. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3677. GetNextInstruction(hp1, hp2) and
  3678. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3679. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3680. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3681. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3682. { change to
  3683. mov reg1, mem1 mov reg1, mem1
  3684. mov mem2, reg1 cmp reg1, mem2
  3685. cmp mem1, reg1
  3686. }
  3687. begin
  3688. RemoveInstruction(hp2);
  3689. taicpu(hp1).opcode := A_CMP;
  3690. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3691. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3692. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3693. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3694. end;
  3695. end;
  3696. end
  3697. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3698. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3699. begin
  3700. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3701. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3702. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3703. end
  3704. else
  3705. begin
  3706. TransferUsedRegs(TmpUsedRegs);
  3707. if GetNextInstruction(hp1, hp2) and
  3708. MatchOpType(taicpu(p),top_ref,top_reg) and
  3709. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3710. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3711. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3712. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3713. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3714. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3715. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3716. { mov mem1, %reg1
  3717. mov %reg1, mem2
  3718. mov mem2, reg2
  3719. to:
  3720. mov mem1, reg2
  3721. mov reg2, mem2}
  3722. begin
  3723. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3724. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3725. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3726. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3727. RemoveInstruction(hp2);
  3728. Result := True;
  3729. end
  3730. {$ifdef i386}
  3731. { this is enabled for i386 only, as the rules to create the reg sets below
  3732. are too complicated for x86-64, so this makes this code too error prone
  3733. on x86-64
  3734. }
  3735. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3736. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3737. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3738. { mov mem1, reg1 mov mem1, reg1
  3739. mov reg1, mem2 mov reg1, mem2
  3740. mov mem2, reg2 mov mem2, reg1
  3741. to: to:
  3742. mov mem1, reg1 mov mem1, reg1
  3743. mov mem1, reg2 mov reg1, mem2
  3744. mov reg1, mem2
  3745. or (if mem1 depends on reg1
  3746. and/or if mem2 depends on reg2)
  3747. to:
  3748. mov mem1, reg1
  3749. mov reg1, mem2
  3750. mov reg1, reg2
  3751. }
  3752. begin
  3753. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3754. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3755. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3756. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3757. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3758. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3759. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3760. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3761. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3762. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3763. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3764. end
  3765. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3766. begin
  3767. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3768. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3769. end
  3770. else
  3771. begin
  3772. RemoveInstruction(hp2);
  3773. end
  3774. {$endif i386}
  3775. ;
  3776. end;
  3777. end
  3778. { movl [mem1],reg1
  3779. movl [mem1],reg2
  3780. to
  3781. movl [mem1],reg1
  3782. movl reg1,reg2
  3783. }
  3784. else if not CheckMovMov2MovMov2(p, hp1) and
  3785. { movl const1,[mem1]
  3786. movl [mem1],reg1
  3787. to
  3788. movl const1,reg1
  3789. movl reg1,[mem1]
  3790. }
  3791. MatchOpType(Taicpu(p),top_const,top_ref) and
  3792. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3793. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3794. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3795. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3796. begin
  3797. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3798. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3799. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3800. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3801. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3802. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3803. Result:=true;
  3804. exit;
  3805. end;
  3806. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3807. { Change:
  3808. movl %reg1,%reg2
  3809. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3810. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3811. To:
  3812. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3813. movl x(%reg1),%reg1
  3814. movl %reg1,%regX
  3815. }
  3816. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3817. begin
  3818. p_SourceReg := taicpu(p).oper[0]^.reg;
  3819. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3820. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3821. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3822. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3823. GetNextInstruction(hp1, hp2) and
  3824. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3825. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3826. begin
  3827. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3828. if RegInRef(p_TargetReg, SourceRef) and
  3829. { If %reg1 also appears in the second reference, then it will
  3830. not refer to the same memory block as the first reference }
  3831. not RegInRef(p_SourceReg, SourceRef) then
  3832. begin
  3833. { Check to see if the references match if %reg2 is changed to %reg1 }
  3834. if SourceRef.base = p_TargetReg then
  3835. SourceRef.base := p_SourceReg;
  3836. if SourceRef.index = p_TargetReg then
  3837. SourceRef.index := p_SourceReg;
  3838. { RefsEqual also checks to ensure both references are non-volatile }
  3839. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3840. begin
  3841. taicpu(hp2).loadreg(0, p_SourceReg);
  3842. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3843. Result := True;
  3844. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3845. begin
  3846. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3847. RemoveCurrentP(p, hp1);
  3848. Exit;
  3849. end
  3850. else
  3851. begin
  3852. { Check to see if %reg2 is no longer in use }
  3853. TransferUsedRegs(TmpUsedRegs);
  3854. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3855. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3856. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3857. begin
  3858. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3859. RemoveCurrentP(p, hp1);
  3860. Exit;
  3861. end;
  3862. end;
  3863. { If we reach this point, p and hp1 weren't actually modified,
  3864. so we can do a bit more work on this pass }
  3865. end;
  3866. end;
  3867. end;
  3868. end;
  3869. end;
  3870. {$ifdef x86_64}
  3871. { Change:
  3872. movl %reg1l,%reg2l
  3873. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3874. To:
  3875. movl %reg1l,%reg2l
  3876. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3877. If %reg1 = %reg3, convert to:
  3878. movl %reg1l,%reg2l
  3879. andl %reg1l,%reg1l
  3880. }
  3881. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3882. MatchOpType(taicpu(p), top_reg, top_reg) and
  3883. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3884. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3885. begin
  3886. TransferUsedRegs(TmpUsedRegs);
  3887. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3888. taicpu(hp1).opsize := S_L;
  3889. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3890. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3891. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3892. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3893. begin
  3894. { %reg1 = %reg3 }
  3895. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3896. taicpu(hp1).opcode := A_AND;
  3897. end
  3898. else
  3899. begin
  3900. { %reg1 <> %reg3 }
  3901. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3902. end;
  3903. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3904. begin
  3905. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3906. RemoveCurrentP(p, hp1);
  3907. Result := True;
  3908. Exit;
  3909. end
  3910. else
  3911. begin
  3912. { Initial instruction wasn't actually changed }
  3913. Include(OptsToCheck, aoc_ForceNewIteration);
  3914. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3915. appears below since %reg1 has technically changed }
  3916. if taicpu(hp1).opcode = A_AND then
  3917. Exit;
  3918. end;
  3919. end;
  3920. {$endif x86_64}
  3921. { search further than the next instruction for a mov (as long as it's not a jump) }
  3922. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3923. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3924. (taicpu(p).oper[1]^.typ = top_reg) and
  3925. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3926. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3927. begin
  3928. { we work with hp2 here, so hp1 can be still used later on when
  3929. checking for GetNextInstruction_p }
  3930. hp3 := hp1;
  3931. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3932. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3933. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3934. TransferUsedRegs(TmpUsedRegs);
  3935. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3936. if NotFirstIteration then
  3937. JumpTracking := TLinkedList.Create
  3938. else
  3939. JumpTracking := nil;
  3940. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3941. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3942. (hp2.typ=ait_instruction) do
  3943. begin
  3944. case taicpu(hp2).opcode of
  3945. A_POP:
  3946. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3947. begin
  3948. if not CrossJump and
  3949. not RegUsedBetween(p_TargetReg, p, hp2) then
  3950. begin
  3951. { We can remove the original MOV since the register
  3952. wasn't used between it and its popping from the stack }
  3953. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3954. RemoveCurrentp(p, hp1);
  3955. Result := True;
  3956. JumpTracking.Free;
  3957. Exit;
  3958. end;
  3959. { Can't go any further }
  3960. Break;
  3961. end;
  3962. A_MOV:
  3963. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3964. ((taicpu(p).oper[0]^.typ=top_const) or
  3965. ((taicpu(p).oper[0]^.typ=top_reg) and
  3966. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3967. )
  3968. ) then
  3969. begin
  3970. { we have
  3971. mov x, %treg
  3972. mov %treg, y
  3973. }
  3974. { We don't need to call UpdateUsedRegs for every instruction between
  3975. p and hp2 because the register we're concerned about will not
  3976. become deallocated (otherwise GetNextInstructionUsingReg would
  3977. have stopped at an earlier instruction). [Kit] }
  3978. TempRegUsed :=
  3979. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3980. RegReadByInstruction(p_TargetReg, hp3) or
  3981. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3982. case taicpu(p).oper[0]^.typ Of
  3983. top_reg:
  3984. begin
  3985. { change
  3986. mov %reg, %treg
  3987. mov %treg, y
  3988. to
  3989. mov %reg, y
  3990. }
  3991. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3992. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3993. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3994. begin
  3995. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3996. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3997. if TempRegUsed then
  3998. begin
  3999. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4000. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4001. { Set the start of the next GetNextInstructionUsingRegCond search
  4002. to start at the entry right before hp2 (which is about to be removed) }
  4003. hp3 := tai(hp2.Previous);
  4004. RemoveInstruction(hp2);
  4005. Include(OptsToCheck, aoc_ForceNewIteration);
  4006. { See if there's more we can optimise }
  4007. Continue;
  4008. end
  4009. else
  4010. begin
  4011. RemoveInstruction(hp2);
  4012. { We can remove the original MOV too }
  4013. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4014. RemoveCurrentP(p, hp1);
  4015. Result:=true;
  4016. JumpTracking.Free;
  4017. Exit;
  4018. end;
  4019. end
  4020. else
  4021. begin
  4022. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4023. taicpu(hp2).loadReg(0, p_SourceReg);
  4024. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4025. { Check to see if the register also appears in the reference }
  4026. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4027. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4028. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4029. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4030. begin
  4031. { Don't remove the first instruction if the temporary register is in use }
  4032. if not TempRegUsed then
  4033. begin
  4034. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4035. RemoveCurrentP(p, hp1);
  4036. Result:=true;
  4037. JumpTracking.Free;
  4038. Exit;
  4039. end;
  4040. { No need to set Result to True here. If there's another instruction later
  4041. on that can be optimised, it will be detected when the main Pass 1 loop
  4042. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4043. hp3 := hp2;
  4044. Continue;
  4045. end;
  4046. end;
  4047. end;
  4048. top_const:
  4049. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4050. begin
  4051. { change
  4052. mov const, %treg
  4053. mov %treg, y
  4054. to
  4055. mov const, y
  4056. }
  4057. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4058. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4059. begin
  4060. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4061. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4062. if TempRegUsed then
  4063. begin
  4064. { Don't remove the first instruction if the temporary register is in use }
  4065. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4066. { No need to set Result to True. If there's another instruction later on
  4067. that can be optimised, it will be detected when the main Pass 1 loop
  4068. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4069. end
  4070. else
  4071. begin
  4072. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4073. RemoveCurrentP(p, hp1);
  4074. Result:=true;
  4075. Exit;
  4076. end;
  4077. end;
  4078. end;
  4079. else
  4080. Internalerror(2019103001);
  4081. end;
  4082. end
  4083. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4084. begin
  4085. if not CrossJump and
  4086. not RegUsedBetween(p_TargetReg, p, hp2) and
  4087. not RegReadByInstruction(p_TargetReg, hp2) then
  4088. begin
  4089. { Register is not used before it is overwritten }
  4090. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4091. RemoveCurrentp(p, hp1);
  4092. Result := True;
  4093. Exit;
  4094. end;
  4095. if (taicpu(p).oper[0]^.typ = top_const) and
  4096. (taicpu(hp2).oper[0]^.typ = top_const) then
  4097. begin
  4098. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4099. begin
  4100. { Same value - register hasn't changed }
  4101. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4102. RemoveInstruction(hp2);
  4103. Include(OptsToCheck, aoc_ForceNewIteration);
  4104. { See if there's more we can optimise }
  4105. Continue;
  4106. end;
  4107. end;
  4108. {$ifdef x86_64}
  4109. end
  4110. { Change:
  4111. movl %reg1l,%reg2l
  4112. ...
  4113. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4114. To:
  4115. movl %reg1l,%reg2l
  4116. ...
  4117. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4118. If %reg1 = %reg3, convert to:
  4119. movl %reg1l,%reg2l
  4120. ...
  4121. andl %reg1l,%reg1l
  4122. }
  4123. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4124. (taicpu(p).oper[0]^.typ = top_reg) and
  4125. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4126. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4127. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4128. begin
  4129. TempRegUsed :=
  4130. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4131. RegReadByInstruction(p_TargetReg, hp3) or
  4132. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4133. taicpu(hp2).opsize := S_L;
  4134. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4135. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4136. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4137. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4138. begin
  4139. { %reg1 = %reg3 }
  4140. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4141. taicpu(hp2).opcode := A_AND;
  4142. end
  4143. else
  4144. begin
  4145. { %reg1 <> %reg3 }
  4146. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4147. end;
  4148. if not TempRegUsed then
  4149. begin
  4150. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4151. RemoveCurrentP(p, hp1);
  4152. Result := True;
  4153. Exit;
  4154. end
  4155. else
  4156. begin
  4157. { Initial instruction wasn't actually changed }
  4158. Include(OptsToCheck, aoc_ForceNewIteration);
  4159. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4160. appears below since %reg1 has technically changed }
  4161. if taicpu(hp2).opcode = A_AND then
  4162. Break;
  4163. end;
  4164. {$endif x86_64}
  4165. end
  4166. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4167. GetNextInstruction(hp2, hp4) and
  4168. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4169. { Optimise the following first:
  4170. movl [mem1],reg1
  4171. movl [mem1],reg2
  4172. to
  4173. movl [mem1],reg1
  4174. movl reg1,reg2
  4175. If [mem1] contains the target register and reg1 is the
  4176. the source register, this optimisation will get missed
  4177. and produce less efficient code later on.
  4178. }
  4179. if CheckMovMov2MovMov2(hp2, hp4) then
  4180. { Initial instruction wasn't actually changed }
  4181. Include(OptsToCheck, aoc_ForceNewIteration);
  4182. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4183. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4184. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4185. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4186. begin
  4187. {
  4188. Change from:
  4189. mov ###, %reg
  4190. ...
  4191. movs/z %reg,%reg (Same register, just different sizes)
  4192. To:
  4193. movs/z ###, %reg (Longer version)
  4194. ...
  4195. (remove)
  4196. }
  4197. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4198. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4199. { Keep the first instruction as mov if ### is a constant }
  4200. if taicpu(p).oper[0]^.typ = top_const then
  4201. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4202. else
  4203. begin
  4204. taicpu(p).opcode := taicpu(hp2).opcode;
  4205. taicpu(p).opsize := taicpu(hp2).opsize;
  4206. end;
  4207. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4208. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4209. RemoveInstruction(hp2);
  4210. Result := True;
  4211. JumpTracking.Free;
  4212. Exit;
  4213. end;
  4214. else
  4215. { Move down to the if-block below };
  4216. end;
  4217. { Also catches MOV/S/Z instructions that aren't modified }
  4218. if taicpu(p).oper[0]^.typ = top_reg then
  4219. begin
  4220. p_SourceReg := taicpu(p).oper[0]^.reg;
  4221. if
  4222. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4223. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4224. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4225. begin
  4226. Result := True;
  4227. { Just in case something didn't get modified (e.g. an
  4228. implicit register). Also, if it does read from this
  4229. register, then there's no longer an advantage to
  4230. changing the register on subsequent instructions.}
  4231. if not RegReadByInstruction(p_TargetReg, hp2) then
  4232. begin
  4233. { If a conditional jump was crossed, do not delete
  4234. the original MOV no matter what }
  4235. if not CrossJump and
  4236. { RegEndOfLife returns True if the register is
  4237. deallocated before the next instruction or has
  4238. been loaded with a new value }
  4239. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4240. begin
  4241. { We can remove the original MOV }
  4242. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4243. RemoveCurrentp(p, hp1);
  4244. JumpTracking.Free;
  4245. Result := True;
  4246. Exit;
  4247. end;
  4248. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4249. begin
  4250. { See if there's more we can optimise }
  4251. hp3 := hp2;
  4252. Continue;
  4253. end;
  4254. end;
  4255. end;
  4256. end;
  4257. { Break out of the while loop under normal circumstances }
  4258. Break;
  4259. end;
  4260. JumpTracking.Free;
  4261. end;
  4262. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4263. (taicpu(p).oper[1]^.typ = top_reg) and
  4264. (taicpu(p).opsize = S_L) and
  4265. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4266. (hp2.typ = ait_instruction) and
  4267. (taicpu(hp2).opcode = A_AND) and
  4268. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4269. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4270. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4271. ) then
  4272. begin
  4273. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4274. begin
  4275. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4276. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4277. begin
  4278. { Optimize out:
  4279. mov x, %reg
  4280. and ffffffffh, %reg
  4281. }
  4282. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4283. RemoveInstruction(hp2);
  4284. Result:=true;
  4285. exit;
  4286. end;
  4287. end;
  4288. end;
  4289. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4290. x >= RetOffset) as it doesn't do anything (it writes either to a
  4291. parameter or to the temporary storage room for the function
  4292. result)
  4293. }
  4294. if IsExitCode(hp1) and
  4295. (taicpu(p).oper[1]^.typ = top_ref) and
  4296. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4297. (
  4298. (
  4299. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4300. not (
  4301. assigned(current_procinfo.procdef.funcretsym) and
  4302. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4303. )
  4304. ) or
  4305. { Also discard writes to the stack that are below the base pointer,
  4306. as this is temporary storage rather than a function result on the
  4307. stack, say. }
  4308. (
  4309. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4310. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4311. )
  4312. ) then
  4313. begin
  4314. RemoveCurrentp(p, hp1);
  4315. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4316. RemoveLastDeallocForFuncRes(p);
  4317. Result:=true;
  4318. exit;
  4319. end;
  4320. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4321. begin
  4322. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4323. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4324. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4325. begin
  4326. { change
  4327. mov reg1, mem1
  4328. test/cmp x, mem1
  4329. to
  4330. mov reg1, mem1
  4331. test/cmp x, reg1
  4332. }
  4333. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4334. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4335. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4336. Result := True;
  4337. Exit;
  4338. end;
  4339. if DoMovCmpMemOpt(p, hp1) then
  4340. begin
  4341. Result := True;
  4342. Exit;
  4343. end;
  4344. end;
  4345. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4346. { If the flags register is in use, don't change the instruction to an
  4347. ADD otherwise this will scramble the flags. [Kit] }
  4348. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4349. begin
  4350. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4351. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4352. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4353. ) or
  4354. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4355. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4356. )
  4357. ) then
  4358. { mov reg1,ref
  4359. lea reg2,[reg1,reg2]
  4360. to
  4361. add reg2,ref}
  4362. begin
  4363. TransferUsedRegs(TmpUsedRegs);
  4364. { reg1 may not be used afterwards }
  4365. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4366. begin
  4367. Taicpu(hp1).opcode:=A_ADD;
  4368. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4369. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4370. RemoveCurrentp(p, hp1);
  4371. result:=true;
  4372. exit;
  4373. end;
  4374. end;
  4375. { If the LEA instruction can be converted into an arithmetic instruction,
  4376. it may be possible to then fold it in the next optimisation, otherwise
  4377. there's nothing more that can be optimised here. }
  4378. if not ConvertLEA(taicpu(hp1)) then
  4379. Exit;
  4380. end;
  4381. if (taicpu(p).oper[1]^.typ = top_reg) and
  4382. (hp1.typ = ait_instruction) and
  4383. GetNextInstruction(hp1, hp2) and
  4384. MatchInstruction(hp2,A_MOV,[]) and
  4385. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4386. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4387. (
  4388. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4389. {$ifdef x86_64}
  4390. or
  4391. (
  4392. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4393. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4394. )
  4395. {$endif x86_64}
  4396. ) then
  4397. begin
  4398. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4399. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4400. { change movsX/movzX reg/ref, reg2
  4401. add/sub/or/... reg3/$const, reg2
  4402. mov reg2 reg/ref
  4403. dealloc reg2
  4404. to
  4405. add/sub/or/... reg3/$const, reg/ref }
  4406. begin
  4407. TransferUsedRegs(TmpUsedRegs);
  4408. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4409. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4410. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4411. begin
  4412. { by example:
  4413. movswl %si,%eax movswl %si,%eax p
  4414. decl %eax addl %edx,%eax hp1
  4415. movw %ax,%si movw %ax,%si hp2
  4416. ->
  4417. movswl %si,%eax movswl %si,%eax p
  4418. decw %eax addw %edx,%eax hp1
  4419. movw %ax,%si movw %ax,%si hp2
  4420. }
  4421. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4422. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4423. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4424. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4425. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4426. {
  4427. ->
  4428. movswl %si,%eax movswl %si,%eax p
  4429. decw %si addw %dx,%si hp1
  4430. movw %ax,%si movw %ax,%si hp2
  4431. }
  4432. case taicpu(hp1).ops of
  4433. 1:
  4434. begin
  4435. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4436. if taicpu(hp1).oper[0]^.typ=top_reg then
  4437. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4438. end;
  4439. 2:
  4440. begin
  4441. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4442. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4443. (taicpu(hp1).opcode<>A_SHL) and
  4444. (taicpu(hp1).opcode<>A_SHR) and
  4445. (taicpu(hp1).opcode<>A_SAR) then
  4446. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4447. end;
  4448. else
  4449. internalerror(2008042701);
  4450. end;
  4451. {
  4452. ->
  4453. decw %si addw %dx,%si p
  4454. }
  4455. RemoveInstruction(hp2);
  4456. RemoveCurrentP(p, hp1);
  4457. Result:=True;
  4458. Exit;
  4459. end;
  4460. end;
  4461. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4462. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4463. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4464. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4465. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4466. )
  4467. {$ifdef i386}
  4468. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4469. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4470. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4471. {$endif i386}
  4472. then
  4473. { change movsX/movzX reg/ref, reg2
  4474. add/sub/or/... regX/$const, reg2
  4475. mov reg2, reg3
  4476. dealloc reg2
  4477. to
  4478. movsX/movzX reg/ref, reg3
  4479. add/sub/or/... reg3/$const, reg3
  4480. }
  4481. begin
  4482. TransferUsedRegs(TmpUsedRegs);
  4483. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4484. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4485. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4486. begin
  4487. { by example:
  4488. movswl %si,%eax movswl %si,%eax p
  4489. decl %eax addl %edx,%eax hp1
  4490. movw %ax,%si movw %ax,%si hp2
  4491. ->
  4492. movswl %si,%eax movswl %si,%eax p
  4493. decw %eax addw %edx,%eax hp1
  4494. movw %ax,%si movw %ax,%si hp2
  4495. }
  4496. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4497. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4498. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4499. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4500. { limit size of constants as well to avoid assembler errors, but
  4501. check opsize to avoid overflow when left shifting the 1 }
  4502. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4503. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4504. {$ifdef x86_64}
  4505. { Be careful of, for example:
  4506. movl %reg1,%reg2
  4507. addl %reg3,%reg2
  4508. movq %reg2,%reg4
  4509. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4510. }
  4511. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4512. begin
  4513. taicpu(hp2).changeopsize(S_L);
  4514. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4515. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4516. end;
  4517. {$endif x86_64}
  4518. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4519. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4520. if taicpu(p).oper[0]^.typ=top_reg then
  4521. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4522. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4523. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4524. {
  4525. ->
  4526. movswl %si,%eax movswl %si,%eax p
  4527. decw %si addw %dx,%si hp1
  4528. movw %ax,%si movw %ax,%si hp2
  4529. }
  4530. case taicpu(hp1).ops of
  4531. 1:
  4532. begin
  4533. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4534. if taicpu(hp1).oper[0]^.typ=top_reg then
  4535. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4536. end;
  4537. 2:
  4538. begin
  4539. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4540. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4541. (taicpu(hp1).opcode<>A_SHL) and
  4542. (taicpu(hp1).opcode<>A_SHR) and
  4543. (taicpu(hp1).opcode<>A_SAR) then
  4544. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4545. end;
  4546. else
  4547. internalerror(2018111801);
  4548. end;
  4549. {
  4550. ->
  4551. decw %si addw %dx,%si p
  4552. }
  4553. RemoveInstruction(hp2);
  4554. end;
  4555. end;
  4556. end;
  4557. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4558. GetNextInstruction(hp1, hp2) and
  4559. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4560. MatchOperand(Taicpu(p).oper[0]^,0) and
  4561. (Taicpu(p).oper[1]^.typ = top_reg) and
  4562. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4563. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4564. { mov reg1,0
  4565. bts reg1,operand1 --> mov reg1,operand2
  4566. or reg1,operand2 bts reg1,operand1}
  4567. begin
  4568. Taicpu(hp2).opcode:=A_MOV;
  4569. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4570. asml.remove(hp1);
  4571. insertllitem(hp2,hp2.next,hp1);
  4572. RemoveCurrentp(p, hp1);
  4573. Result:=true;
  4574. exit;
  4575. end;
  4576. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4577. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4578. GetNextInstruction(hp1, hp2) and
  4579. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4580. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4581. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4582. { change
  4583. mov reg1,reg2
  4584. sub reg3,reg2
  4585. cmp reg3,reg1
  4586. into
  4587. mov reg1,reg2
  4588. sub reg3,reg2
  4589. }
  4590. begin
  4591. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4592. RemoveInstruction(hp2);
  4593. Result:=true;
  4594. exit;
  4595. end;
  4596. {
  4597. mov ref,reg0
  4598. <op> reg0,reg1
  4599. dealloc reg0
  4600. to
  4601. <op> ref,reg1
  4602. }
  4603. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4604. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4605. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4606. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4607. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4608. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4609. begin
  4610. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4611. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4612. RemoveCurrentp(p, hp1);
  4613. Result:=true;
  4614. exit;
  4615. end;
  4616. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4617. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4618. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4619. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4620. begin
  4621. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4622. {$ifdef x86_64}
  4623. { Convert:
  4624. movq x(ref),%reg64
  4625. shrq y,%reg64
  4626. To:
  4627. movl x+4(ref),%reg32
  4628. shrl y-32,%reg32 (Remove if y = 32)
  4629. }
  4630. if (taicpu(p).opsize = S_Q) and
  4631. (taicpu(hp1).opcode = A_SHR) and
  4632. (taicpu(hp1).oper[0]^.val >= 32) then
  4633. begin
  4634. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4635. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4636. { Convert to 32-bit }
  4637. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4638. taicpu(p).opsize := S_L;
  4639. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4640. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4641. if (taicpu(hp1).oper[0]^.val = 32) then
  4642. begin
  4643. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4644. RemoveInstruction(hp1);
  4645. end
  4646. else
  4647. begin
  4648. { This will potentially open up more arithmetic operations since
  4649. the peephole optimizer now has a big hint that only the lower
  4650. 32 bits are currently in use (and opcodes are smaller in size) }
  4651. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4652. taicpu(hp1).opsize := S_L;
  4653. Dec(taicpu(hp1).oper[0]^.val, 32);
  4654. DebugMsg(SPeepholeOptimization + PreMessage +
  4655. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4656. end;
  4657. Result := True;
  4658. Exit;
  4659. end;
  4660. {$endif x86_64}
  4661. { Convert:
  4662. movl x(ref),%reg
  4663. shrl $24,%reg
  4664. To:
  4665. movzbl x+3(ref),%reg
  4666. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4667. Also accept sar instead of shr, but convert to movsx instead of movzx
  4668. }
  4669. if taicpu(hp1).opcode = A_SHR then
  4670. MovUnaligned := A_MOVZX
  4671. else
  4672. MovUnaligned := A_MOVSX;
  4673. NewSize := S_NO;
  4674. NewOffset := 0;
  4675. case taicpu(p).opsize of
  4676. S_B:
  4677. { No valid combinations };
  4678. S_W:
  4679. if (taicpu(hp1).oper[0]^.val = 8) then
  4680. begin
  4681. NewSize := S_BW;
  4682. NewOffset := 1;
  4683. end;
  4684. S_L:
  4685. case taicpu(hp1).oper[0]^.val of
  4686. 16:
  4687. begin
  4688. NewSize := S_WL;
  4689. NewOffset := 2;
  4690. end;
  4691. 24:
  4692. begin
  4693. NewSize := S_BL;
  4694. NewOffset := 3;
  4695. end;
  4696. else
  4697. ;
  4698. end;
  4699. {$ifdef x86_64}
  4700. S_Q:
  4701. case taicpu(hp1).oper[0]^.val of
  4702. 32:
  4703. begin
  4704. if taicpu(hp1).opcode = A_SAR then
  4705. begin
  4706. { 32-bit to 64-bit is a distinct instruction }
  4707. MovUnaligned := A_MOVSXD;
  4708. NewSize := S_LQ;
  4709. NewOffset := 4;
  4710. end
  4711. else
  4712. { Should have been handled by MovShr2Mov above }
  4713. InternalError(2022081811);
  4714. end;
  4715. 48:
  4716. begin
  4717. NewSize := S_WQ;
  4718. NewOffset := 6;
  4719. end;
  4720. 56:
  4721. begin
  4722. NewSize := S_BQ;
  4723. NewOffset := 7;
  4724. end;
  4725. else
  4726. ;
  4727. end;
  4728. {$endif x86_64}
  4729. else
  4730. InternalError(2022081810);
  4731. end;
  4732. if (NewSize <> S_NO) and
  4733. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4734. begin
  4735. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4736. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4737. debug_op2str(MovUnaligned);
  4738. {$ifdef x86_64}
  4739. if MovUnaligned <> A_MOVSXD then
  4740. { Don't add size suffix for MOVSXD }
  4741. {$endif x86_64}
  4742. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4743. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4744. taicpu(p).opcode := MovUnaligned;
  4745. taicpu(p).opsize := NewSize;
  4746. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4747. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4748. RemoveInstruction(hp1);
  4749. Result := True;
  4750. Exit;
  4751. end;
  4752. end;
  4753. { Backward optimisation shared with OptPass2MOV }
  4754. if FuncMov2Func(p, hp1) then
  4755. begin
  4756. Result := True;
  4757. Exit;
  4758. end;
  4759. end;
  4760. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4761. var
  4762. hp1 : tai;
  4763. begin
  4764. Result:=false;
  4765. if taicpu(p).ops <> 2 then
  4766. exit;
  4767. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4768. GetNextInstruction(p,hp1) then
  4769. begin
  4770. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4771. (taicpu(hp1).ops = 2) then
  4772. begin
  4773. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4774. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4775. { movXX reg1, mem1 or movXX mem1, reg1
  4776. movXX mem2, reg2 movXX reg2, mem2}
  4777. begin
  4778. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4779. { movXX reg1, mem1 or movXX mem1, reg1
  4780. movXX mem2, reg1 movXX reg2, mem1}
  4781. begin
  4782. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4783. begin
  4784. { Removes the second statement from
  4785. movXX reg1, mem1/reg2
  4786. movXX mem1/reg2, reg1
  4787. }
  4788. if taicpu(p).oper[0]^.typ=top_reg then
  4789. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4790. { Removes the second statement from
  4791. movXX mem1/reg1, reg2
  4792. movXX reg2, mem1/reg1
  4793. }
  4794. if (taicpu(p).oper[1]^.typ=top_reg) and
  4795. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4796. begin
  4797. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4798. RemoveInstruction(hp1);
  4799. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4800. Result:=true;
  4801. exit;
  4802. end
  4803. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4804. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4805. begin
  4806. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4807. RemoveInstruction(hp1);
  4808. Result:=true;
  4809. exit;
  4810. end;
  4811. end
  4812. end;
  4813. end;
  4814. end;
  4815. end;
  4816. end;
  4817. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4818. var
  4819. hp1 : tai;
  4820. begin
  4821. result:=false;
  4822. { replace
  4823. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4824. MovX %mreg2,%mreg1
  4825. dealloc %mreg2
  4826. by
  4827. <Op>X %mreg2,%mreg1
  4828. ?
  4829. }
  4830. if GetNextInstruction(p,hp1) and
  4831. { we mix single and double opperations here because we assume that the compiler
  4832. generates vmovapd only after double operations and vmovaps only after single operations }
  4833. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4834. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4835. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4836. (taicpu(p).oper[0]^.typ=top_reg) then
  4837. begin
  4838. TransferUsedRegs(TmpUsedRegs);
  4839. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4840. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4841. begin
  4842. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4843. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4844. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4845. RemoveInstruction(hp1);
  4846. result:=true;
  4847. end;
  4848. end;
  4849. end;
  4850. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4851. var
  4852. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4853. JumpLabel, JumpLabel_dist: TAsmLabel;
  4854. FirstValue, SecondValue: TCGInt;
  4855. function OptimizeJump(var InputP: tai): Boolean;
  4856. var
  4857. TempBool: Boolean;
  4858. begin
  4859. Result := False;
  4860. TempBool := True;
  4861. if DoJumpOptimizations(InputP, TempBool) or
  4862. not TempBool then
  4863. begin
  4864. Result := True;
  4865. if Assigned(InputP) then
  4866. begin
  4867. { CollapseZeroDistJump will be set to the label or an align
  4868. before it after the jump if it optimises, whether or not
  4869. the label is live or dead }
  4870. if (InputP.typ = ait_align) or
  4871. (
  4872. (InputP.typ = ait_label) and
  4873. not (tai_label(InputP).labsym.is_used)
  4874. ) then
  4875. GetNextInstruction(InputP, InputP);
  4876. end;
  4877. Exit;
  4878. end;
  4879. end;
  4880. begin
  4881. Result := False;
  4882. if (taicpu(p).oper[0]^.typ = top_const) and
  4883. (taicpu(p).oper[0]^.val <> -1) then
  4884. begin
  4885. { Convert unsigned maximum constants to -1 to aid optimisation }
  4886. case taicpu(p).opsize of
  4887. S_B:
  4888. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4889. begin
  4890. taicpu(p).oper[0]^.val := -1;
  4891. Result := True;
  4892. Exit;
  4893. end;
  4894. S_W:
  4895. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4896. begin
  4897. taicpu(p).oper[0]^.val := -1;
  4898. Result := True;
  4899. Exit;
  4900. end;
  4901. S_L:
  4902. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4903. begin
  4904. taicpu(p).oper[0]^.val := -1;
  4905. Result := True;
  4906. Exit;
  4907. end;
  4908. {$ifdef x86_64}
  4909. S_Q:
  4910. { Storing anything greater than $7FFFFFFF is not possible so do
  4911. nothing };
  4912. {$endif x86_64}
  4913. else
  4914. InternalError(2021121001);
  4915. end;
  4916. end;
  4917. if GetNextInstruction(p, hp1) and
  4918. TrySwapMovCmp(p, hp1) then
  4919. begin
  4920. Result := True;
  4921. Exit;
  4922. end;
  4923. p_label := nil;
  4924. JumpLabel := nil;
  4925. if MatchInstruction(hp1, A_Jcc, []) then
  4926. begin
  4927. if OptimizeJump(hp1) then
  4928. begin
  4929. Result := True;
  4930. if Assigned(hp1) then
  4931. begin
  4932. { CollapseZeroDistJump will be set to the label or an align
  4933. before it after the jump if it optimises, whether or not
  4934. the label is live or dead }
  4935. if (hp1.typ = ait_align) or
  4936. (
  4937. (hp1.typ = ait_label) and
  4938. not (tai_label(hp1).labsym.is_used)
  4939. ) then
  4940. GetNextInstruction(hp1, hp1);
  4941. end;
  4942. TransferUsedRegs(TmpUsedRegs);
  4943. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4944. if not Assigned(hp1) or
  4945. (
  4946. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4947. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4948. ) then
  4949. begin
  4950. { No more conditional jumps; conditional statement is no longer required }
  4951. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4952. RemoveCurrentP(p);
  4953. end;
  4954. Exit;
  4955. end;
  4956. if IsJumpToLabel(taicpu(hp1)) then
  4957. begin
  4958. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4959. if Assigned(JumpLabel) then
  4960. p_label := getlabelwithsym(JumpLabel);
  4961. end;
  4962. end;
  4963. { Search for:
  4964. test $x,(reg/ref)
  4965. jne @lbl1
  4966. test $y,(reg/ref) (same register or reference)
  4967. jne @lbl1
  4968. Change to:
  4969. test $(x or y),(reg/ref)
  4970. jne @lbl1
  4971. (Note, this doesn't work with je instead of jne)
  4972. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4973. Also search for:
  4974. test $x,(reg/ref)
  4975. je @lbl1
  4976. ...
  4977. test $y,(reg/ref)
  4978. je/jne @lbl2
  4979. If (x or y) = x, then the second jump is deterministic
  4980. }
  4981. if (
  4982. (
  4983. (taicpu(p).oper[0]^.typ = top_const) or
  4984. (
  4985. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4986. (taicpu(p).oper[0]^.typ = top_reg) and
  4987. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4988. )
  4989. ) and
  4990. MatchInstruction(hp1, A_JCC, [])
  4991. ) then
  4992. begin
  4993. if (taicpu(p).oper[0]^.typ = top_reg) and
  4994. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4995. FirstValue := -1
  4996. else
  4997. FirstValue := taicpu(p).oper[0]^.val;
  4998. { If we have several test/jne's in a row, it might be the case that
  4999. the second label doesn't go to the same location, but the one
  5000. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5001. so accommodate for this with a while loop.
  5002. }
  5003. hp1_last := hp1;
  5004. while (
  5005. (
  5006. (taicpu(p).oper[1]^.typ = top_reg) and
  5007. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5008. ) or GetNextInstruction(hp1_last, p_dist)
  5009. ) and (p_dist.typ = ait_instruction) do
  5010. begin
  5011. if (
  5012. (
  5013. (taicpu(p_dist).opcode = A_TEST) and
  5014. (
  5015. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5016. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5017. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5018. )
  5019. ) or
  5020. (
  5021. { cmp 0,%reg = test %reg,%reg }
  5022. (taicpu(p_dist).opcode = A_CMP) and
  5023. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5024. )
  5025. ) and
  5026. { Make sure the destination operands are actually the same }
  5027. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5028. GetNextInstruction(p_dist, hp1_dist) and
  5029. MatchInstruction(hp1_dist, A_JCC, []) then
  5030. begin
  5031. if OptimizeJump(hp1_dist) then
  5032. begin
  5033. Result := True;
  5034. Exit;
  5035. end;
  5036. if
  5037. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5038. (
  5039. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5040. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5041. ) then
  5042. SecondValue := -1
  5043. else
  5044. SecondValue := taicpu(p_dist).oper[0]^.val;
  5045. { If both of the TEST constants are identical, delete the
  5046. second TEST that is unnecessary (be careful though, just
  5047. in case the flags are modified in between) }
  5048. if (FirstValue = SecondValue) then
  5049. begin
  5050. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5051. begin
  5052. { Since the second jump's condition is a subset of the first, we
  5053. know it will never branch because the first jump dominates it.
  5054. Get it out of the way now rather than wait for the jump
  5055. optimisations for a speed boost. }
  5056. if IsJumpToLabel(taicpu(hp1_dist)) then
  5057. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5058. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5059. RemoveInstruction(hp1_dist);
  5060. Result := True;
  5061. end
  5062. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5063. begin
  5064. { If the inverse of the first condition is a subset of the second,
  5065. the second one will definitely branch if the first one doesn't }
  5066. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5067. { We can remove the TEST instruction too }
  5068. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5069. RemoveInstruction(p_dist);
  5070. MakeUnconditional(taicpu(hp1_dist));
  5071. RemoveDeadCodeAfterJump(hp1_dist);
  5072. { Since the jump is now unconditional, we can't
  5073. continue any further with this particular
  5074. optimisation. The original TEST is still intact
  5075. though, so there might be something else we can
  5076. do }
  5077. Include(OptsToCheck, aoc_ForceNewIteration);
  5078. Break;
  5079. end;
  5080. if Result or
  5081. { If a jump wasn't removed or made unconditional, only
  5082. remove the identical TEST instruction if the flags
  5083. weren't modified }
  5084. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5085. begin
  5086. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5087. RemoveInstruction(p_dist);
  5088. { If the jump was removed or made unconditional, we
  5089. don't need to allocate NR_DEFAULTFLAGS over the
  5090. entire range }
  5091. if not Result then
  5092. begin
  5093. { Mark the flags as 'in use' over the entire range }
  5094. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5095. { Speed gain - continue search from the Jcc instruction }
  5096. hp1_last := hp1_dist;
  5097. { Only the TEST instruction was removed, and the
  5098. original was unchanged, so we can safely do
  5099. another iteration of the while loop }
  5100. Include(OptsToCheck, aoc_ForceNewIteration);
  5101. Continue;
  5102. end;
  5103. Exit;
  5104. end;
  5105. end;
  5106. hp1_last := nil;
  5107. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5108. (
  5109. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5110. { Always adjacent under -O2 and under }
  5111. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5112. (
  5113. GetNextInstruction(hp1, hp1_last) and
  5114. (hp1_last = p_dist)
  5115. )
  5116. ) and
  5117. (
  5118. (
  5119. { Test the following variant:
  5120. test $x,(reg/ref)
  5121. jne @lbl1
  5122. test $y,(reg/ref)
  5123. je @lbl2
  5124. @lbl1:
  5125. Becomes:
  5126. test $(x or y),(reg/ref)
  5127. je @lbl2
  5128. @lbl1: (may become a dead label)
  5129. }
  5130. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5131. GetNextInstruction(hp1_dist, hp1_last) and
  5132. (hp1_last = p_label)
  5133. ) or
  5134. (
  5135. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5136. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5137. then the second jump will never branch, so it can also be
  5138. removed regardless of where it goes }
  5139. (
  5140. (FirstValue = -1) or
  5141. (SecondValue = -1) or
  5142. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5143. )
  5144. )
  5145. ) then
  5146. begin
  5147. { Same jump location... can be a register since nothing's changed }
  5148. { If any of the entries are equivalent to test %reg,%reg, then the
  5149. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5150. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5151. if (hp1_last = p_label) then
  5152. begin
  5153. { Variant }
  5154. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5155. RemoveInstruction(p_dist);
  5156. if Assigned(JumpLabel) then
  5157. JumpLabel.decrefs;
  5158. RemoveInstruction(hp1);
  5159. end
  5160. else
  5161. begin
  5162. { Only remove the second test if no jumps or other conditional instructions follow }
  5163. TransferUsedRegs(TmpUsedRegs);
  5164. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5165. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5166. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5167. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5168. begin
  5169. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5170. RemoveInstruction(p_dist);
  5171. { Remove the first jump, not the second, to keep
  5172. any register deallocations between the second
  5173. TEST/JNE pair in the same place. Aids future
  5174. optimisation. }
  5175. if Assigned(JumpLabel) then
  5176. JumpLabel.decrefs;
  5177. RemoveInstruction(hp1);
  5178. end
  5179. else
  5180. begin
  5181. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5182. if IsJumpToLabel(taicpu(hp1_dist)) then
  5183. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5184. { Remove second jump in this instance }
  5185. RemoveInstruction(hp1_dist);
  5186. end;
  5187. end;
  5188. Result := True;
  5189. Exit;
  5190. end;
  5191. end;
  5192. if { If -O2 and under, it may stop on any old instruction }
  5193. (cs_opt_level3 in current_settings.optimizerswitches) and
  5194. (taicpu(p).oper[1]^.typ = top_reg) and
  5195. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5196. begin
  5197. hp1_last := p_dist;
  5198. Continue;
  5199. end;
  5200. Break;
  5201. end;
  5202. end;
  5203. { Search for:
  5204. test %reg,%reg
  5205. j(c1) @lbl1
  5206. ...
  5207. @lbl:
  5208. test %reg,%reg (same register)
  5209. j(c2) @lbl2
  5210. If c2 is a subset of c1, change to:
  5211. test %reg,%reg
  5212. j(c1) @lbl2
  5213. (@lbl1 may become a dead label as a result)
  5214. }
  5215. if (taicpu(p).oper[1]^.typ = top_reg) and
  5216. (taicpu(p).oper[0]^.typ = top_reg) and
  5217. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5218. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5219. Assigned(p_label) and
  5220. GetNextInstruction(p_label, p_dist) and
  5221. MatchInstruction(p_dist, A_TEST, []) and
  5222. { It's fine if the second test uses smaller sub-registers }
  5223. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5224. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5225. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5226. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5227. GetNextInstruction(p_dist, hp1_dist) and
  5228. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5229. begin
  5230. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5231. if JumpLabel = JumpLabel_dist then
  5232. { This is an infinite loop }
  5233. Exit;
  5234. { Best optimisation when the first condition is a subset (or equal) of the second }
  5235. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5236. begin
  5237. { Any registers used here will already be allocated }
  5238. if Assigned(JumpLabel) then
  5239. JumpLabel.DecRefs;
  5240. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5241. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5242. Result := True;
  5243. Exit;
  5244. end;
  5245. end;
  5246. end;
  5247. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5248. var
  5249. hp1, hp2: tai;
  5250. ActiveReg: TRegister;
  5251. OldOffset: asizeint;
  5252. ThisConst: TCGInt;
  5253. function RegDeallocated: Boolean;
  5254. begin
  5255. TransferUsedRegs(TmpUsedRegs);
  5256. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5257. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5258. end;
  5259. begin
  5260. result:=false;
  5261. hp1 := nil;
  5262. { replace
  5263. addX const,%reg1
  5264. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5265. dealloc %reg1
  5266. by
  5267. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5268. }
  5269. if MatchOpType(taicpu(p),top_const,top_reg) then
  5270. begin
  5271. ActiveReg := taicpu(p).oper[1]^.reg;
  5272. { Ensures the entire register was updated }
  5273. if (taicpu(p).opsize >= S_L) and
  5274. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5275. MatchInstruction(hp1,A_LEA,[]) and
  5276. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5277. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5278. (
  5279. { Cover the case where the register in the reference is also the destination register }
  5280. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5281. (
  5282. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5283. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5284. RegDeallocated
  5285. )
  5286. ) then
  5287. begin
  5288. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5289. {$push}
  5290. {$R-}{$Q-}
  5291. { Explicitly disable overflow checking for these offset calculation
  5292. as those do not matter for the final result }
  5293. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5294. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5295. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5296. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5297. {$pop}
  5298. {$ifdef x86_64}
  5299. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5300. begin
  5301. { Overflow; abort }
  5302. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5303. end
  5304. else
  5305. {$endif x86_64}
  5306. begin
  5307. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5308. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5309. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5310. RemoveCurrentP(p, hp1)
  5311. else
  5312. RemoveCurrentP(p);
  5313. result:=true;
  5314. Exit;
  5315. end;
  5316. end;
  5317. if (
  5318. { Save calling GetNextInstructionUsingReg again }
  5319. Assigned(hp1) or
  5320. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5321. ) and
  5322. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5323. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5324. begin
  5325. if taicpu(hp1).oper[0]^.typ = top_const then
  5326. begin
  5327. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5328. if taicpu(hp1).opcode = A_ADD then
  5329. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5330. else
  5331. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5332. Result := True;
  5333. { Handle any overflows }
  5334. case taicpu(p).opsize of
  5335. S_B:
  5336. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5337. S_W:
  5338. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5339. S_L:
  5340. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5341. {$ifdef x86_64}
  5342. S_Q:
  5343. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5344. { Overflow; abort }
  5345. Result := False
  5346. else
  5347. taicpu(p).oper[0]^.val := ThisConst;
  5348. {$endif x86_64}
  5349. else
  5350. InternalError(2021102610);
  5351. end;
  5352. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5353. if Result then
  5354. begin
  5355. if (taicpu(p).oper[0]^.val < 0) and
  5356. (
  5357. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5358. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5359. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5360. ) then
  5361. begin
  5362. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5363. taicpu(p).opcode := A_SUB;
  5364. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5365. end
  5366. else
  5367. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5368. RemoveInstruction(hp1);
  5369. end;
  5370. end
  5371. else
  5372. begin
  5373. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5374. TransferUsedRegs(TmpUsedRegs);
  5375. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5376. hp2 := p;
  5377. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5378. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5379. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5380. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5381. begin
  5382. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5383. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5384. Asml.Remove(p);
  5385. Asml.InsertAfter(p, hp1);
  5386. p := hp1;
  5387. Result := True;
  5388. Exit;
  5389. end;
  5390. end;
  5391. end;
  5392. if DoArithCombineOpt(p) then
  5393. Result:=true;
  5394. end;
  5395. end;
  5396. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5397. var
  5398. hp1, hp2: tai;
  5399. ref: Integer;
  5400. saveref: treference;
  5401. offsetcalc: Int64;
  5402. TempReg: TRegister;
  5403. Multiple: TCGInt;
  5404. Adjacent, IntermediateRegDiscarded: Boolean;
  5405. begin
  5406. Result:=false;
  5407. { play save and throw an error if LEA uses a seg register prefix,
  5408. this is most likely an error somewhere else }
  5409. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5410. internalerror(2022022001);
  5411. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5412. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5413. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5414. (
  5415. { do not mess with leas accessing the stack pointer
  5416. unless it's a null operation }
  5417. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5418. (
  5419. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5420. (taicpu(p).oper[0]^.ref^.offset = 0)
  5421. )
  5422. ) and
  5423. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5424. begin
  5425. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5426. begin
  5427. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5428. begin
  5429. taicpu(p).opcode := A_MOV;
  5430. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5431. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5432. end
  5433. else
  5434. begin
  5435. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5436. RemoveCurrentP(p);
  5437. end;
  5438. Result:=true;
  5439. exit;
  5440. end
  5441. else if (
  5442. { continue to use lea to adjust the stack pointer,
  5443. it is the recommended way, but only if not optimizing for size }
  5444. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5445. (cs_opt_size in current_settings.optimizerswitches)
  5446. ) and
  5447. { If the flags register is in use, don't change the instruction
  5448. to an ADD otherwise this will scramble the flags. [Kit] }
  5449. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5450. ConvertLEA(taicpu(p)) then
  5451. begin
  5452. Result:=true;
  5453. exit;
  5454. end;
  5455. end;
  5456. { Don't optimise if the stack or frame pointer is the destination register }
  5457. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5458. Exit;
  5459. if GetNextInstruction(p,hp1) and
  5460. (hp1.typ=ait_instruction) then
  5461. begin
  5462. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5463. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5464. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5465. begin
  5466. TransferUsedRegs(TmpUsedRegs);
  5467. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5468. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5469. begin
  5470. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5471. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5472. RemoveInstruction(hp1);
  5473. result:=true;
  5474. exit;
  5475. end;
  5476. end;
  5477. { changes
  5478. lea <ref1>, reg1
  5479. <op> ...,<ref. with reg1>,...
  5480. to
  5481. <op> ...,<ref1>,... }
  5482. { find a reference which uses reg1 }
  5483. 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
  5484. ref:=0
  5485. 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
  5486. ref:=1
  5487. else
  5488. ref:=-1;
  5489. if (ref<>-1) and
  5490. { reg1 must be either the base or the index }
  5491. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5492. begin
  5493. { reg1 can be removed from the reference }
  5494. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5495. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5496. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5497. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5498. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5499. else
  5500. Internalerror(2019111201);
  5501. { check if the can insert all data of the lea into the second instruction }
  5502. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5503. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5504. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5505. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5506. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5507. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5508. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5509. {$ifdef x86_64}
  5510. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5511. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5512. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5513. )
  5514. {$endif x86_64}
  5515. then
  5516. begin
  5517. { reg1 might not used by the second instruction after it is remove from the reference }
  5518. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5519. begin
  5520. TransferUsedRegs(TmpUsedRegs);
  5521. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5522. { reg1 is not updated so it might not be used afterwards }
  5523. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5524. begin
  5525. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5526. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5527. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5528. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5529. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5530. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5531. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5532. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5533. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5534. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5535. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5536. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5537. RemoveCurrentP(p, hp1);
  5538. result:=true;
  5539. exit;
  5540. end
  5541. end;
  5542. end;
  5543. { recover }
  5544. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5545. end;
  5546. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5547. if Adjacent or
  5548. { Check further ahead (up to 2 instructions ahead for -O2) }
  5549. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5550. begin
  5551. { Check common LEA/LEA conditions }
  5552. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5553. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5554. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5555. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5556. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5557. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5558. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5559. (
  5560. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5561. calling it (since it calls GetNextInstruction) }
  5562. Adjacent or
  5563. (
  5564. (
  5565. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5566. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5567. ) and (
  5568. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5569. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5570. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5571. )
  5572. )
  5573. ) then
  5574. begin
  5575. TransferUsedRegs(TmpUsedRegs);
  5576. hp2 := p;
  5577. repeat
  5578. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5579. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5580. IntermediateRegDiscarded :=
  5581. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5582. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5583. { changes
  5584. lea offset1(regX,scale), reg1
  5585. lea offset2(reg1,reg1), reg2
  5586. to
  5587. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5588. and
  5589. lea offset1(regX,scale1), reg1
  5590. lea offset2(reg1,scale2), reg2
  5591. to
  5592. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5593. and
  5594. lea offset1(regX,scale1), reg1
  5595. lea offset2(reg3,reg1,scale2), reg2
  5596. to
  5597. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5598. ... so long as the final scale does not exceed 8
  5599. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5600. }
  5601. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5602. (
  5603. { Don't optimise if size is a concern and the intermediate register remains in use }
  5604. IntermediateRegDiscarded or
  5605. not (cs_opt_size in current_settings.optimizerswitches)
  5606. ) and
  5607. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5608. (
  5609. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5610. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5611. ) and (
  5612. (
  5613. { lea (reg1,scale2), reg2 variant }
  5614. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5615. (
  5616. Adjacent or
  5617. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5618. ) and
  5619. (
  5620. (
  5621. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5622. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5623. ) or (
  5624. { lea (regX,regX), reg1 variant }
  5625. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5626. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5627. )
  5628. )
  5629. ) or (
  5630. { lea (reg1,reg1), reg1 variant }
  5631. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5632. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5633. )
  5634. ) then
  5635. begin
  5636. { Make everything homogeneous to make calculations easier }
  5637. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5638. begin
  5639. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5640. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5641. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5642. else
  5643. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5644. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5645. end;
  5646. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5647. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5648. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5649. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5650. begin
  5651. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5652. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5653. begin
  5654. { Put the register to change in the index register }
  5655. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5656. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5657. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5658. end;
  5659. { Change lea (reg,reg) to lea(,reg,2) }
  5660. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5661. begin
  5662. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5663. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5664. end;
  5665. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5666. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5667. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5668. { Just to prevent miscalculations }
  5669. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5670. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5671. else
  5672. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5673. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5674. if IntermediateRegDiscarded then
  5675. begin
  5676. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5677. RemoveCurrentP(p);
  5678. end
  5679. else
  5680. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5681. result:=true;
  5682. exit;
  5683. end;
  5684. end;
  5685. { changes
  5686. lea offset1(regX), reg1
  5687. lea offset2(reg1), reg2
  5688. to
  5689. lea offset1+offset2(regX), reg2 }
  5690. if (
  5691. { Don't optimise if size is a concern and the intermediate register remains in use }
  5692. IntermediateRegDiscarded or
  5693. not (cs_opt_size in current_settings.optimizerswitches)
  5694. ) and
  5695. (
  5696. (
  5697. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5698. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5699. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5700. ) or (
  5701. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5702. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5703. (
  5704. (
  5705. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5706. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5707. ) or (
  5708. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5709. (
  5710. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5711. (
  5712. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5713. (
  5714. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5715. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5716. )
  5717. )
  5718. )
  5719. )
  5720. )
  5721. )
  5722. ) then
  5723. begin
  5724. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5725. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5726. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5727. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5728. begin
  5729. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5730. begin
  5731. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5732. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5733. { if the register is used as index and base, we have to increase for base as well
  5734. and adapt base }
  5735. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5736. begin
  5737. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5738. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5739. end;
  5740. end
  5741. else
  5742. begin
  5743. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5744. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5745. end;
  5746. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5747. begin
  5748. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5749. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5750. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5751. end;
  5752. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5753. if IntermediateRegDiscarded then
  5754. begin
  5755. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5756. RemoveCurrentP(p);
  5757. end
  5758. else
  5759. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5760. result:=true;
  5761. exit;
  5762. end;
  5763. end;
  5764. end;
  5765. { Change:
  5766. leal/q $x(%reg1),%reg2
  5767. ...
  5768. shll/q $y,%reg2
  5769. To:
  5770. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5771. }
  5772. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5773. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5774. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5775. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5776. (taicpu(hp1).oper[0]^.val <= 3) then
  5777. begin
  5778. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5779. TransferUsedRegs(TmpUsedRegs);
  5780. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5781. if
  5782. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5783. (this works even if scalefactor is zero) }
  5784. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5785. { Ensure offset doesn't go out of bounds }
  5786. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5787. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5788. (
  5789. (
  5790. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5791. (
  5792. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5793. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5794. (
  5795. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5796. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5797. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5798. )
  5799. )
  5800. ) or (
  5801. (
  5802. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5803. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5804. ) and
  5805. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5806. )
  5807. ) then
  5808. begin
  5809. repeat
  5810. with taicpu(p).oper[0]^.ref^ do
  5811. begin
  5812. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5813. if index = base then
  5814. begin
  5815. if Multiple > 4 then
  5816. { Optimisation will no longer work because resultant
  5817. scale factor will exceed 8 }
  5818. Break;
  5819. base := NR_NO;
  5820. scalefactor := 2;
  5821. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5822. end
  5823. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5824. begin
  5825. { Scale factor only works on the index register }
  5826. index := base;
  5827. base := NR_NO;
  5828. end;
  5829. { For safety }
  5830. if scalefactor <= 1 then
  5831. begin
  5832. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5833. scalefactor := Multiple;
  5834. end
  5835. else
  5836. begin
  5837. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5838. scalefactor := scalefactor * Multiple;
  5839. end;
  5840. offset := offset * Multiple;
  5841. end;
  5842. RemoveInstruction(hp1);
  5843. Result := True;
  5844. Exit;
  5845. { This repeat..until loop exists for the benefit of Break }
  5846. until True;
  5847. end;
  5848. end;
  5849. end;
  5850. end;
  5851. end;
  5852. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5853. var
  5854. hp1 : tai;
  5855. SubInstr: Boolean;
  5856. ThisConst: TCGInt;
  5857. const
  5858. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5859. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5860. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5861. begin
  5862. Result := False;
  5863. if taicpu(p).oper[0]^.typ <> top_const then
  5864. { Should have been confirmed before calling }
  5865. InternalError(2021102601);
  5866. SubInstr := (taicpu(p).opcode = A_SUB);
  5867. if GetLastInstruction(p, hp1) and
  5868. (hp1.typ = ait_instruction) and
  5869. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5870. begin
  5871. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5872. { Bad size }
  5873. InternalError(2022042001);
  5874. case taicpu(hp1).opcode Of
  5875. A_INC:
  5876. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5877. begin
  5878. if SubInstr then
  5879. ThisConst := taicpu(p).oper[0]^.val - 1
  5880. else
  5881. ThisConst := taicpu(p).oper[0]^.val + 1;
  5882. end
  5883. else
  5884. Exit;
  5885. A_DEC:
  5886. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5887. begin
  5888. if SubInstr then
  5889. ThisConst := taicpu(p).oper[0]^.val + 1
  5890. else
  5891. ThisConst := taicpu(p).oper[0]^.val - 1;
  5892. end
  5893. else
  5894. Exit;
  5895. A_SUB:
  5896. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5897. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5898. begin
  5899. if SubInstr then
  5900. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5901. else
  5902. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5903. end
  5904. else
  5905. Exit;
  5906. A_ADD:
  5907. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5908. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5909. begin
  5910. if SubInstr then
  5911. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5912. else
  5913. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5914. end
  5915. else
  5916. Exit;
  5917. else
  5918. Exit;
  5919. end;
  5920. { Check that the values are in range }
  5921. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5922. { Overflow; abort }
  5923. Exit;
  5924. if (ThisConst = 0) then
  5925. begin
  5926. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5927. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5928. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5929. RemoveInstruction(hp1);
  5930. hp1 := tai(p.next);
  5931. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5932. if not GetLastInstruction(hp1, p) then
  5933. p := hp1;
  5934. end
  5935. else
  5936. begin
  5937. if taicpu(hp1).opercnt=1 then
  5938. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5939. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5940. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5941. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5942. else
  5943. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5944. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5945. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5946. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5947. RemoveInstruction(hp1);
  5948. taicpu(p).loadconst(0, ThisConst);
  5949. end;
  5950. Result := True;
  5951. end;
  5952. end;
  5953. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5954. begin
  5955. Result := False;
  5956. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5957. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5958. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5959. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5960. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5961. (
  5962. (
  5963. (taicpu(hp1).opcode = A_TEST)
  5964. ) or (
  5965. (taicpu(hp1).opcode = A_CMP) and
  5966. { A sanity check more than anything }
  5967. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5968. )
  5969. ) then
  5970. begin
  5971. { change
  5972. mov mem, %reg
  5973. ...
  5974. cmp/test x, %reg / test %reg,%reg
  5975. (reg deallocated)
  5976. to
  5977. cmp/test x, mem / cmp 0, mem
  5978. }
  5979. TransferUsedRegs(TmpUsedRegs);
  5980. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5981. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5982. begin
  5983. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5984. if (taicpu(hp1).opcode = A_TEST) and
  5985. (
  5986. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5987. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5988. ) then
  5989. begin
  5990. taicpu(hp1).opcode := A_CMP;
  5991. taicpu(hp1).loadconst(0, 0);
  5992. end;
  5993. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5994. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5995. RemoveCurrentP(p);
  5996. if (p <> hp1) then
  5997. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5998. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  5999. { Make sure the flags are allocated across the CMP instruction }
  6000. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6001. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6002. Result := True;
  6003. Exit;
  6004. end;
  6005. end;
  6006. end;
  6007. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6008. var
  6009. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6010. ThisReg, SecondReg: TRegister;
  6011. JumpLoc: TAsmLabel;
  6012. NewSize: TOpSize;
  6013. begin
  6014. Result := False;
  6015. {
  6016. Convert:
  6017. j<c> .L1
  6018. .L2:
  6019. mov 1,reg
  6020. jmp .L3 (or ret, although it might not be a RET yet)
  6021. .L1:
  6022. mov 0,reg
  6023. jmp .L3 (or ret)
  6024. ( As long as .L3 <> .L1 or .L2)
  6025. To:
  6026. mov 0,reg
  6027. set<not(c)> reg
  6028. jmp .L3 (or ret)
  6029. .L2:
  6030. mov 1,reg
  6031. jmp .L3 (or ret)
  6032. .L1:
  6033. mov 0,reg
  6034. jmp .L3 (or ret)
  6035. }
  6036. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6037. Exit;
  6038. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6039. if GetNextInstruction(hp_label, hp2) and
  6040. MatchInstruction(hp2,A_MOV,[]) and
  6041. (taicpu(hp2).oper[0]^.typ = top_const) and
  6042. (
  6043. (
  6044. (taicpu(hp2).oper[1]^.typ = top_reg)
  6045. {$ifdef i386}
  6046. { Under i386, ESI, EDI, EBP and ESP
  6047. don't have an 8-bit representation }
  6048. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6049. {$endif i386}
  6050. ) or (
  6051. {$ifdef i386}
  6052. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6053. {$endif i386}
  6054. (taicpu(hp2).opsize = S_B)
  6055. )
  6056. ) and
  6057. GetNextInstruction(hp2, hp3) and
  6058. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6059. (
  6060. (taicpu(hp3).opcode=A_RET) or
  6061. (
  6062. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6063. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6064. )
  6065. ) and
  6066. GetNextInstruction(hp3, hp4) and
  6067. (hp4.typ=ait_label) and
  6068. (tai_label(hp4).labsym=JumpLoc) and
  6069. (
  6070. not (cs_opt_size in current_settings.optimizerswitches) or
  6071. { If the initial jump is the label's only reference, then it will
  6072. become a dead label if the other conditions are met and hence
  6073. remove at least 2 instructions, including a jump }
  6074. (JumpLoc.getrefs = 1)
  6075. ) and
  6076. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6077. that will be optimised out }
  6078. GetNextInstruction(hp4, hp5) and
  6079. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6080. (taicpu(hp5).oper[0]^.typ = top_const) and
  6081. (
  6082. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6083. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6084. ) and
  6085. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6086. GetNextInstruction(hp5,hp6) and
  6087. (
  6088. (hp6.typ<>ait_label) or
  6089. SkipLabels(hp6, hp6)
  6090. ) and
  6091. (hp6.typ=ait_instruction) then
  6092. begin
  6093. { First, let's look at the two jumps that are hp3 and hp6 }
  6094. if not
  6095. (
  6096. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6097. (
  6098. (taicpu(hp6).opcode=A_RET) or
  6099. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6100. )
  6101. ) then
  6102. { If condition is False, then the JMP/RET instructions matched conventionally }
  6103. begin
  6104. { See if one of the jumps can be instantly converted into a RET }
  6105. if (taicpu(hp3).opcode=A_JMP) then
  6106. begin
  6107. { Reuse hp5 }
  6108. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6109. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6110. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6111. Exit;
  6112. if MatchInstruction(hp5, A_RET, []) then
  6113. begin
  6114. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6115. ConvertJumpToRET(hp3, hp5);
  6116. Result := True;
  6117. end
  6118. else
  6119. Exit;
  6120. end;
  6121. if (taicpu(hp6).opcode=A_JMP) then
  6122. begin
  6123. { Reuse hp5 }
  6124. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6125. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6126. Exit;
  6127. if MatchInstruction(hp5, A_RET, []) then
  6128. begin
  6129. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6130. ConvertJumpToRET(hp6, hp5);
  6131. Result := True;
  6132. end
  6133. else
  6134. Exit;
  6135. end;
  6136. if not
  6137. (
  6138. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6139. (
  6140. (taicpu(hp6).opcode=A_RET) or
  6141. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6142. )
  6143. ) then
  6144. { Still doesn't match }
  6145. Exit;
  6146. end;
  6147. if (taicpu(hp2).oper[0]^.val = 1) then
  6148. begin
  6149. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6150. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6151. end
  6152. else
  6153. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6154. if taicpu(hp2).opsize=S_B then
  6155. begin
  6156. if taicpu(hp2).oper[1]^.typ = top_reg then
  6157. begin
  6158. SecondReg := taicpu(hp2).oper[1]^.reg;
  6159. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6160. end
  6161. else
  6162. begin
  6163. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6164. SecondReg := NR_NO;
  6165. end;
  6166. hp_pos := p;
  6167. hp_allocstart := hp4;
  6168. end
  6169. else
  6170. begin
  6171. { Will be a register because the size can't be S_B otherwise }
  6172. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6173. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6174. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6175. if (cs_opt_size in current_settings.optimizerswitches) then
  6176. begin
  6177. { Favour using MOVZX when optimising for size }
  6178. case taicpu(hp2).opsize of
  6179. S_W:
  6180. NewSize := S_BW;
  6181. S_L:
  6182. NewSize := S_BL;
  6183. {$ifdef x86_64}
  6184. S_Q:
  6185. begin
  6186. NewSize := S_BL;
  6187. { Will implicitly zero-extend to 64-bit }
  6188. setsubreg(SecondReg, R_SUBD);
  6189. end;
  6190. {$endif x86_64}
  6191. else
  6192. InternalError(2022101301);
  6193. end;
  6194. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6195. { Inserting it right before p will guarantee that the flags are also tracked }
  6196. Asml.InsertBefore(hp5, p);
  6197. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6198. hp_pos := hp5;
  6199. hp_allocstart := hp4;
  6200. end
  6201. else
  6202. begin
  6203. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6204. { Inserting it right before p will guarantee that the flags are also tracked }
  6205. Asml.InsertBefore(hp5, p);
  6206. hp_pos := p;
  6207. hp_allocstart := hp5;
  6208. end;
  6209. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6210. end;
  6211. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6212. taicpu(hp4).condition := taicpu(p).condition;
  6213. asml.InsertBefore(hp4, hp_pos);
  6214. if taicpu(hp3).is_jmp then
  6215. begin
  6216. JumpLoc.decrefs;
  6217. MakeUnconditional(taicpu(p));
  6218. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6219. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6220. end
  6221. else
  6222. ConvertJumpToRET(p, hp3);
  6223. if SecondReg <> NR_NO then
  6224. { Ensure the destination register is allocated over this region }
  6225. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6226. if (JumpLoc.getrefs = 0) then
  6227. RemoveDeadCodeAfterJump(hp3);
  6228. Result:=true;
  6229. exit;
  6230. end;
  6231. end;
  6232. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6233. var
  6234. hp1, hp2: tai;
  6235. ActiveReg: TRegister;
  6236. OldOffset: asizeint;
  6237. ThisConst: TCGInt;
  6238. function RegDeallocated: Boolean;
  6239. begin
  6240. TransferUsedRegs(TmpUsedRegs);
  6241. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6242. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6243. end;
  6244. begin
  6245. Result:=false;
  6246. hp1 := nil;
  6247. { replace
  6248. subX const,%reg1
  6249. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6250. dealloc %reg1
  6251. by
  6252. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6253. }
  6254. if MatchOpType(taicpu(p),top_const,top_reg) then
  6255. begin
  6256. ActiveReg := taicpu(p).oper[1]^.reg;
  6257. { Ensures the entire register was updated }
  6258. if (taicpu(p).opsize >= S_L) and
  6259. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6260. MatchInstruction(hp1,A_LEA,[]) and
  6261. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6262. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6263. (
  6264. { Cover the case where the register in the reference is also the destination register }
  6265. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6266. (
  6267. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6268. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6269. RegDeallocated
  6270. )
  6271. ) then
  6272. begin
  6273. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6274. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6275. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6276. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6277. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6278. {$ifdef x86_64}
  6279. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6280. begin
  6281. { Overflow; abort }
  6282. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6283. end
  6284. else
  6285. {$endif x86_64}
  6286. begin
  6287. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6288. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6289. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6290. RemoveCurrentP(p, hp1)
  6291. else
  6292. RemoveCurrentP(p);
  6293. result:=true;
  6294. Exit;
  6295. end;
  6296. end;
  6297. if (
  6298. { Save calling GetNextInstructionUsingReg again }
  6299. Assigned(hp1) or
  6300. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6301. ) and
  6302. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6303. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6304. begin
  6305. if taicpu(hp1).oper[0]^.typ = top_const then
  6306. begin
  6307. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6308. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6309. Result := True;
  6310. { Handle any overflows }
  6311. case taicpu(p).opsize of
  6312. S_B:
  6313. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6314. S_W:
  6315. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6316. S_L:
  6317. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6318. {$ifdef x86_64}
  6319. S_Q:
  6320. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6321. { Overflow; abort }
  6322. Result := False
  6323. else
  6324. taicpu(p).oper[0]^.val := ThisConst;
  6325. {$endif x86_64}
  6326. else
  6327. InternalError(2021102611);
  6328. end;
  6329. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6330. if Result then
  6331. begin
  6332. if (taicpu(p).oper[0]^.val < 0) and
  6333. (
  6334. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6335. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6336. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6337. ) then
  6338. begin
  6339. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6340. taicpu(p).opcode := A_SUB;
  6341. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6342. end
  6343. else
  6344. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6345. RemoveInstruction(hp1);
  6346. end;
  6347. end
  6348. else
  6349. begin
  6350. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6351. TransferUsedRegs(TmpUsedRegs);
  6352. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6353. hp2 := p;
  6354. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6355. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6356. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6357. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6358. begin
  6359. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6360. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6361. Asml.Remove(p);
  6362. Asml.InsertAfter(p, hp1);
  6363. p := hp1;
  6364. Result := True;
  6365. Exit;
  6366. end;
  6367. end;
  6368. end;
  6369. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6370. { * change "sub/add const1, reg" or "dec reg" followed by
  6371. "sub const2, reg" to one "sub ..., reg" }
  6372. {$ifdef i386}
  6373. if (taicpu(p).oper[0]^.val = 2) and
  6374. (ActiveReg = NR_ESP) and
  6375. { Don't do the sub/push optimization if the sub }
  6376. { comes from setting up the stack frame (JM) }
  6377. (not(GetLastInstruction(p,hp1)) or
  6378. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6379. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6380. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6381. begin
  6382. hp1 := tai(p.next);
  6383. while Assigned(hp1) and
  6384. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6385. not RegReadByInstruction(NR_ESP,hp1) and
  6386. not RegModifiedByInstruction(NR_ESP,hp1) do
  6387. hp1 := tai(hp1.next);
  6388. if Assigned(hp1) and
  6389. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6390. begin
  6391. taicpu(hp1).changeopsize(S_L);
  6392. if taicpu(hp1).oper[0]^.typ=top_reg then
  6393. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6394. hp1 := tai(p.next);
  6395. RemoveCurrentp(p, hp1);
  6396. Result:=true;
  6397. exit;
  6398. end;
  6399. end;
  6400. {$endif i386}
  6401. if DoArithCombineOpt(p) then
  6402. Result:=true;
  6403. end;
  6404. end;
  6405. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6406. var
  6407. TmpBool1,TmpBool2 : Boolean;
  6408. tmpref : treference;
  6409. hp1,hp2: tai;
  6410. mask, shiftval: tcgint;
  6411. begin
  6412. Result:=false;
  6413. { All these optimisations work on "shl/sal const,%reg" }
  6414. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6415. Exit;
  6416. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6417. (taicpu(p).oper[0]^.val <= 3) then
  6418. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6419. begin
  6420. { should we check the next instruction? }
  6421. TmpBool1 := True;
  6422. { have we found an add/sub which could be
  6423. integrated in the lea? }
  6424. TmpBool2 := False;
  6425. reference_reset(tmpref,2,[]);
  6426. TmpRef.index := taicpu(p).oper[1]^.reg;
  6427. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6428. while TmpBool1 and
  6429. GetNextInstruction(p, hp1) and
  6430. (tai(hp1).typ = ait_instruction) and
  6431. ((((taicpu(hp1).opcode = A_ADD) or
  6432. (taicpu(hp1).opcode = A_SUB)) and
  6433. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6434. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6435. (((taicpu(hp1).opcode = A_INC) or
  6436. (taicpu(hp1).opcode = A_DEC)) and
  6437. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6438. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6439. ((taicpu(hp1).opcode = A_LEA) and
  6440. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6441. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6442. (not GetNextInstruction(hp1,hp2) or
  6443. not instrReadsFlags(hp2)) Do
  6444. begin
  6445. TmpBool1 := False;
  6446. if taicpu(hp1).opcode=A_LEA then
  6447. begin
  6448. if (TmpRef.base = NR_NO) and
  6449. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6450. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6451. { Segment register isn't a concern here }
  6452. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6453. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6454. begin
  6455. TmpBool1 := True;
  6456. TmpBool2 := True;
  6457. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6458. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6459. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6460. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6461. RemoveInstruction(hp1);
  6462. end
  6463. end
  6464. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6465. begin
  6466. TmpBool1 := True;
  6467. TmpBool2 := True;
  6468. case taicpu(hp1).opcode of
  6469. A_ADD:
  6470. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6471. A_SUB:
  6472. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6473. else
  6474. internalerror(2019050536);
  6475. end;
  6476. RemoveInstruction(hp1);
  6477. end
  6478. else
  6479. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6480. (((taicpu(hp1).opcode = A_ADD) and
  6481. (TmpRef.base = NR_NO)) or
  6482. (taicpu(hp1).opcode = A_INC) or
  6483. (taicpu(hp1).opcode = A_DEC)) then
  6484. begin
  6485. TmpBool1 := True;
  6486. TmpBool2 := True;
  6487. case taicpu(hp1).opcode of
  6488. A_ADD:
  6489. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6490. A_INC:
  6491. inc(TmpRef.offset);
  6492. A_DEC:
  6493. dec(TmpRef.offset);
  6494. else
  6495. internalerror(2019050535);
  6496. end;
  6497. RemoveInstruction(hp1);
  6498. end;
  6499. end;
  6500. if TmpBool2
  6501. {$ifndef x86_64}
  6502. or
  6503. ((current_settings.optimizecputype < cpu_Pentium2) and
  6504. (taicpu(p).oper[0]^.val <= 3) and
  6505. not(cs_opt_size in current_settings.optimizerswitches))
  6506. {$endif x86_64}
  6507. then
  6508. begin
  6509. if not(TmpBool2) and
  6510. (taicpu(p).oper[0]^.val=1) then
  6511. begin
  6512. taicpu(p).opcode := A_ADD;
  6513. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6514. end
  6515. else
  6516. begin
  6517. taicpu(p).opcode := A_LEA;
  6518. taicpu(p).loadref(0, TmpRef);
  6519. end;
  6520. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6521. Result := True;
  6522. end;
  6523. end
  6524. {$ifndef x86_64}
  6525. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6526. begin
  6527. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6528. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6529. (unlike shl, which is only Tairable in the U pipe) }
  6530. if taicpu(p).oper[0]^.val=1 then
  6531. begin
  6532. taicpu(p).opcode := A_ADD;
  6533. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6534. Result := True;
  6535. end
  6536. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6537. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6538. else if (taicpu(p).opsize = S_L) and
  6539. (taicpu(p).oper[0]^.val<= 3) then
  6540. begin
  6541. reference_reset(tmpref,2,[]);
  6542. TmpRef.index := taicpu(p).oper[1]^.reg;
  6543. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6544. taicpu(p).opcode := A_LEA;
  6545. taicpu(p).loadref(0, TmpRef);
  6546. Result := True;
  6547. end;
  6548. end
  6549. {$endif x86_64}
  6550. else if
  6551. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6552. (
  6553. (
  6554. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6555. SetAndTest(hp1, hp2)
  6556. {$ifdef x86_64}
  6557. ) or
  6558. (
  6559. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6560. GetNextInstruction(hp1, hp2) and
  6561. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6562. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6563. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6564. {$endif x86_64}
  6565. )
  6566. ) and
  6567. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6568. begin
  6569. { Change:
  6570. shl x, %reg1
  6571. mov -(1<<x), %reg2
  6572. and %reg2, %reg1
  6573. Or:
  6574. shl x, %reg1
  6575. and -(1<<x), %reg1
  6576. To just:
  6577. shl x, %reg1
  6578. Since the and operation only zeroes bits that are already zero from the shl operation
  6579. }
  6580. case taicpu(p).oper[0]^.val of
  6581. 8:
  6582. mask:=$FFFFFFFFFFFFFF00;
  6583. 16:
  6584. mask:=$FFFFFFFFFFFF0000;
  6585. 32:
  6586. mask:=$FFFFFFFF00000000;
  6587. 63:
  6588. { Constant pre-calculated to prevent overflow errors with Int64 }
  6589. mask:=$8000000000000000;
  6590. else
  6591. begin
  6592. if taicpu(p).oper[0]^.val >= 64 then
  6593. { Shouldn't happen realistically, since the register
  6594. is guaranteed to be set to zero at this point }
  6595. mask := 0
  6596. else
  6597. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6598. end;
  6599. end;
  6600. if taicpu(hp1).oper[0]^.val = mask then
  6601. begin
  6602. { Everything checks out, perform the optimisation, as long as
  6603. the FLAGS register isn't being used}
  6604. TransferUsedRegs(TmpUsedRegs);
  6605. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6606. {$ifdef x86_64}
  6607. if (hp1 <> hp2) then
  6608. begin
  6609. { "shl/mov/and" version }
  6610. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6611. { Don't do the optimisation if the FLAGS register is in use }
  6612. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6613. begin
  6614. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6615. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6616. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6617. begin
  6618. RemoveInstruction(hp1);
  6619. Result := True;
  6620. end;
  6621. { Only set Result to True if the 'mov' instruction was removed }
  6622. RemoveInstruction(hp2);
  6623. end;
  6624. end
  6625. else
  6626. {$endif x86_64}
  6627. begin
  6628. { "shl/and" version }
  6629. { Don't do the optimisation if the FLAGS register is in use }
  6630. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6631. begin
  6632. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6633. RemoveInstruction(hp1);
  6634. Result := True;
  6635. end;
  6636. end;
  6637. Exit;
  6638. end
  6639. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6640. begin
  6641. { Even if the mask doesn't allow for its removal, we might be
  6642. able to optimise the mask for the "shl/and" version, which
  6643. may permit other peephole optimisations }
  6644. {$ifdef DEBUG_AOPTCPU}
  6645. mask := taicpu(hp1).oper[0]^.val and mask;
  6646. if taicpu(hp1).oper[0]^.val <> mask then
  6647. begin
  6648. DebugMsg(
  6649. SPeepholeOptimization +
  6650. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6651. ' to $' + debug_tostr(mask) +
  6652. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6653. taicpu(hp1).oper[0]^.val := mask;
  6654. end;
  6655. {$else DEBUG_AOPTCPU}
  6656. { If debugging is off, just set the operand even if it's the same }
  6657. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6658. {$endif DEBUG_AOPTCPU}
  6659. end;
  6660. end;
  6661. {
  6662. change
  6663. shl/sal const,reg
  6664. <op> ...(...,reg,1),...
  6665. into
  6666. <op> ...(...,reg,1 shl const),...
  6667. if const in 1..3
  6668. }
  6669. if MatchOpType(taicpu(p), top_const, top_reg) and
  6670. (taicpu(p).oper[0]^.val in [1..3]) and
  6671. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6672. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6673. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6674. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6675. MatchOpType(taicpu(hp1),top_ref))
  6676. ) and
  6677. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6678. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6679. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6680. begin
  6681. TransferUsedRegs(TmpUsedRegs);
  6682. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6683. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6684. begin
  6685. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6686. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6687. RemoveCurrentP(p);
  6688. Result:=true;
  6689. exit;
  6690. end;
  6691. end;
  6692. if MatchOpType(taicpu(p), top_const, top_reg) and
  6693. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6694. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6695. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6696. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6697. begin
  6698. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6699. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6700. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6701. {$ifdef x86_64}
  6702. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6703. {$endif x86_64}
  6704. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6705. begin
  6706. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6707. taicpu(hp1).opcode:=A_MOV;
  6708. taicpu(hp1).oper[0]^.val:=0;
  6709. end
  6710. else
  6711. begin
  6712. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6713. taicpu(hp1).oper[0]^.val:=shiftval;
  6714. end;
  6715. RemoveCurrentP(p);
  6716. Result:=true;
  6717. exit;
  6718. end;
  6719. end;
  6720. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6721. begin
  6722. case shr_size of
  6723. S_B:
  6724. { No valid combinations }
  6725. Result := False;
  6726. S_W:
  6727. Result := (Shift >= 8) and (movz_size = S_BW);
  6728. S_L:
  6729. Result :=
  6730. (Shift >= 24) { Any opsize is valid for this shift } or
  6731. ((Shift >= 16) and (movz_size = S_WL));
  6732. {$ifdef x86_64}
  6733. S_Q:
  6734. Result :=
  6735. (Shift >= 56) { Any opsize is valid for this shift } or
  6736. ((Shift >= 48) and (movz_size = S_WL));
  6737. {$endif x86_64}
  6738. else
  6739. InternalError(2022081510);
  6740. end;
  6741. end;
  6742. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6743. var
  6744. hp1, hp2: tai;
  6745. Shift: TCGInt;
  6746. LimitSize: Topsize;
  6747. DoNotMerge: Boolean;
  6748. begin
  6749. Result := False;
  6750. { All these optimisations work on "shr const,%reg" }
  6751. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6752. Exit;
  6753. DoNotMerge := False;
  6754. Shift := taicpu(p).oper[0]^.val;
  6755. LimitSize := taicpu(p).opsize;
  6756. hp1 := p;
  6757. repeat
  6758. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6759. Exit;
  6760. case taicpu(hp1).opcode of
  6761. A_TEST, A_CMP, A_Jcc:
  6762. { Skip over conditional jumps and relevant comparisons }
  6763. Continue;
  6764. A_MOVZX:
  6765. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6766. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6767. begin
  6768. { Since the original register is being read as is, subsequent
  6769. SHRs must not be merged at this point }
  6770. DoNotMerge := True;
  6771. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6772. begin
  6773. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6774. begin
  6775. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6776. taicpu(hp1).opcode := A_MOV;
  6777. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6778. case taicpu(hp1).opsize of
  6779. S_BW:
  6780. taicpu(hp1).opsize := S_W;
  6781. S_BL, S_WL:
  6782. taicpu(hp1).opsize := S_L;
  6783. else
  6784. InternalError(2022081503);
  6785. end;
  6786. { p itself hasn't changed, so no need to set Result to True }
  6787. Include(OptsToCheck, aoc_ForceNewIteration);
  6788. { See if there's anything afterwards that can be
  6789. optimised, since the input register hasn't changed }
  6790. Continue;
  6791. end;
  6792. { NOTE: If the MOVZX instruction reads and writes the same
  6793. register, defer this to the post-peephole optimisation stage }
  6794. Exit;
  6795. end;
  6796. end;
  6797. A_SHL, A_SAL, A_SHR:
  6798. if (taicpu(hp1).opsize <= LimitSize) and
  6799. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6800. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6801. begin
  6802. { Make sure the sizes don't exceed the register size limit
  6803. (measured by the shift value falling below the limit) }
  6804. if taicpu(hp1).opsize < LimitSize then
  6805. LimitSize := taicpu(hp1).opsize;
  6806. if taicpu(hp1).opcode = A_SHR then
  6807. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6808. else
  6809. begin
  6810. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6811. DoNotMerge := True;
  6812. end;
  6813. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6814. Exit;
  6815. { Since we've established that the combined shift is within
  6816. limits, we can actually combine the adjacent SHR
  6817. instructions even if they're different sizes }
  6818. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6819. begin
  6820. hp2 := tai(hp1.Previous);
  6821. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6822. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6823. RemoveInstruction(hp1);
  6824. hp1 := hp2;
  6825. { Though p has changed, only the constant has, and its
  6826. effects can still be detected on the next iteration of
  6827. the repeat..until loop }
  6828. Include(OptsToCheck, aoc_ForceNewIteration);
  6829. end;
  6830. { Move onto the next instruction }
  6831. Continue;
  6832. end;
  6833. else
  6834. ;
  6835. end;
  6836. Break;
  6837. until False;
  6838. end;
  6839. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6840. var
  6841. CurrentRef: TReference;
  6842. FullReg: TRegister;
  6843. hp1, hp2: tai;
  6844. begin
  6845. Result := False;
  6846. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6847. Exit;
  6848. { We assume you've checked if the operand is actually a reference by
  6849. this point. If it isn't, you'll most likely get an access violation }
  6850. CurrentRef := first_mov.oper[1]^.ref^;
  6851. { Memory must be aligned }
  6852. if (CurrentRef.offset mod 4) <> 0 then
  6853. Exit;
  6854. Inc(CurrentRef.offset);
  6855. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6856. if MatchOperand(second_mov.oper[0]^, 0) and
  6857. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6858. GetNextInstruction(second_mov, hp1) and
  6859. (hp1.typ = ait_instruction) and
  6860. (taicpu(hp1).opcode = A_MOV) and
  6861. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6862. (taicpu(hp1).oper[0]^.val = 0) then
  6863. begin
  6864. Inc(CurrentRef.offset);
  6865. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6866. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6867. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6868. begin
  6869. case taicpu(hp1).opsize of
  6870. S_B:
  6871. if GetNextInstruction(hp1, hp2) and
  6872. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6873. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6874. (taicpu(hp2).oper[0]^.val = 0) then
  6875. begin
  6876. Inc(CurrentRef.offset);
  6877. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6878. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6879. (taicpu(hp2).opsize = S_B) then
  6880. begin
  6881. RemoveInstruction(hp1);
  6882. RemoveInstruction(hp2);
  6883. first_mov.opsize := S_L;
  6884. if first_mov.oper[0]^.typ = top_reg then
  6885. begin
  6886. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6887. { Reuse second_mov as a MOVZX instruction }
  6888. second_mov.opcode := A_MOVZX;
  6889. second_mov.opsize := S_BL;
  6890. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6891. second_mov.loadreg(1, FullReg);
  6892. first_mov.oper[0]^.reg := FullReg;
  6893. asml.Remove(second_mov);
  6894. asml.InsertBefore(second_mov, first_mov);
  6895. end
  6896. else
  6897. { It's a value }
  6898. begin
  6899. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6900. RemoveInstruction(second_mov);
  6901. end;
  6902. Result := True;
  6903. Exit;
  6904. end;
  6905. end;
  6906. S_W:
  6907. begin
  6908. RemoveInstruction(hp1);
  6909. first_mov.opsize := S_L;
  6910. if first_mov.oper[0]^.typ = top_reg then
  6911. begin
  6912. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6913. { Reuse second_mov as a MOVZX instruction }
  6914. second_mov.opcode := A_MOVZX;
  6915. second_mov.opsize := S_BL;
  6916. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6917. second_mov.loadreg(1, FullReg);
  6918. first_mov.oper[0]^.reg := FullReg;
  6919. asml.Remove(second_mov);
  6920. asml.InsertBefore(second_mov, first_mov);
  6921. end
  6922. else
  6923. { It's a value }
  6924. begin
  6925. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6926. RemoveInstruction(second_mov);
  6927. end;
  6928. Result := True;
  6929. Exit;
  6930. end;
  6931. else
  6932. ;
  6933. end;
  6934. end;
  6935. end;
  6936. end;
  6937. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6938. { returns true if a "continue" should be done after this optimization }
  6939. var
  6940. hp1, hp2, hp3: tai;
  6941. begin
  6942. Result := false;
  6943. hp3 := nil;
  6944. if MatchOpType(taicpu(p),top_ref) and
  6945. GetNextInstruction(p, hp1) and
  6946. (hp1.typ = ait_instruction) and
  6947. (((taicpu(hp1).opcode = A_FLD) and
  6948. (taicpu(p).opcode = A_FSTP)) or
  6949. ((taicpu(p).opcode = A_FISTP) and
  6950. (taicpu(hp1).opcode = A_FILD))) and
  6951. MatchOpType(taicpu(hp1),top_ref) and
  6952. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6953. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6954. begin
  6955. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6956. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6957. GetNextInstruction(hp1, hp2) and
  6958. (((hp2.typ = ait_instruction) and
  6959. IsExitCode(hp2) and
  6960. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6961. not(assigned(current_procinfo.procdef.funcretsym) and
  6962. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6963. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6964. { fstp <temp>
  6965. fld <temp>
  6966. <dealloc> <temp>
  6967. }
  6968. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6969. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6970. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6971. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6972. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6973. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6974. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6975. )
  6976. )
  6977. ) then
  6978. begin
  6979. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6980. RemoveInstruction(hp1);
  6981. RemoveCurrentP(p, hp2);
  6982. { first case: exit code }
  6983. if hp2.typ = ait_instruction then
  6984. RemoveLastDeallocForFuncRes(p);
  6985. Result := true;
  6986. end
  6987. else
  6988. { we can do this only in fast math mode as fstp is rounding ...
  6989. ... still disabled as it breaks the compiler and/or rtl }
  6990. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6991. { ... or if another fstp equal to the first one follows }
  6992. GetNextInstruction(hp1,hp2) and
  6993. (hp2.typ = ait_instruction) and
  6994. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6995. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6996. begin
  6997. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6998. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6999. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7000. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7001. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7002. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7003. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7004. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7005. ) then
  7006. begin
  7007. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7008. RemoveCurrentP(p,hp2);
  7009. RemoveInstruction(hp1);
  7010. Result := true;
  7011. end
  7012. else if { fst can't store an extended/comp value }
  7013. (taicpu(p).opsize <> S_FX) and
  7014. (taicpu(p).opsize <> S_IQ) then
  7015. begin
  7016. if (taicpu(p).opcode = A_FSTP) then
  7017. taicpu(p).opcode := A_FST
  7018. else
  7019. taicpu(p).opcode := A_FIST;
  7020. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7021. RemoveInstruction(hp1);
  7022. Result := true;
  7023. end;
  7024. end;
  7025. end;
  7026. end;
  7027. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7028. var
  7029. hp1, hp2, hp3: tai;
  7030. begin
  7031. result:=false;
  7032. if MatchOpType(taicpu(p),top_reg) and
  7033. GetNextInstruction(p, hp1) and
  7034. (hp1.typ = Ait_Instruction) and
  7035. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7036. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7037. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7038. { change to
  7039. fld reg fxxx reg,st
  7040. fxxxp st, st1 (hp1)
  7041. Remark: non commutative operations must be reversed!
  7042. }
  7043. begin
  7044. case taicpu(hp1).opcode Of
  7045. A_FMULP,A_FADDP,
  7046. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7047. begin
  7048. case taicpu(hp1).opcode Of
  7049. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7050. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7051. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7052. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7053. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7054. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7055. else
  7056. internalerror(2019050534);
  7057. end;
  7058. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7059. taicpu(hp1).oper[1]^.reg := NR_ST;
  7060. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7061. RemoveCurrentP(p, hp1);
  7062. Result:=true;
  7063. exit;
  7064. end;
  7065. else
  7066. ;
  7067. end;
  7068. end
  7069. else
  7070. if MatchOpType(taicpu(p),top_ref) and
  7071. GetNextInstruction(p, hp2) and
  7072. (hp2.typ = Ait_Instruction) and
  7073. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7074. (taicpu(p).opsize in [S_FS, S_FL]) and
  7075. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7076. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7077. if GetLastInstruction(p, hp1) and
  7078. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7079. MatchOpType(taicpu(hp1),top_ref) and
  7080. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7081. if ((taicpu(hp2).opcode = A_FMULP) or
  7082. (taicpu(hp2).opcode = A_FADDP)) then
  7083. { change to
  7084. fld/fst mem1 (hp1) fld/fst mem1
  7085. fld mem1 (p) fadd/
  7086. faddp/ fmul st, st
  7087. fmulp st, st1 (hp2) }
  7088. begin
  7089. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7090. RemoveCurrentP(p, hp1);
  7091. if (taicpu(hp2).opcode = A_FADDP) then
  7092. taicpu(hp2).opcode := A_FADD
  7093. else
  7094. taicpu(hp2).opcode := A_FMUL;
  7095. taicpu(hp2).oper[1]^.reg := NR_ST;
  7096. end
  7097. else
  7098. { change to
  7099. fld/fst mem1 (hp1) fld/fst mem1
  7100. fld mem1 (p) fld st
  7101. }
  7102. begin
  7103. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7104. taicpu(p).changeopsize(S_FL);
  7105. taicpu(p).loadreg(0,NR_ST);
  7106. end
  7107. else
  7108. begin
  7109. case taicpu(hp2).opcode Of
  7110. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7111. { change to
  7112. fld/fst mem1 (hp1) fld/fst mem1
  7113. fld mem2 (p) fxxx mem2
  7114. fxxxp st, st1 (hp2) }
  7115. begin
  7116. case taicpu(hp2).opcode Of
  7117. A_FADDP: taicpu(p).opcode := A_FADD;
  7118. A_FMULP: taicpu(p).opcode := A_FMUL;
  7119. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7120. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7121. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7122. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7123. else
  7124. internalerror(2019050533);
  7125. end;
  7126. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7127. RemoveInstruction(hp2);
  7128. end
  7129. else
  7130. ;
  7131. end
  7132. end
  7133. end;
  7134. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7135. begin
  7136. Result := condition_in(cond1, cond2) or
  7137. { Not strictly subsets due to the actual flags checked, but because we're
  7138. comparing integers, E is a subset of AE and GE and their aliases }
  7139. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7140. end;
  7141. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7142. var
  7143. v: TCGInt;
  7144. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7145. FirstMatch, TempBool: Boolean;
  7146. NewReg: TRegister;
  7147. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7148. begin
  7149. Result:=false;
  7150. { All these optimisations need a next instruction }
  7151. if not GetNextInstruction(p, hp1) then
  7152. Exit;
  7153. { Search for:
  7154. cmp ###,###
  7155. j(c1) @lbl1
  7156. ...
  7157. @lbl:
  7158. cmp ###,### (same comparison as above)
  7159. j(c2) @lbl2
  7160. If c1 is a subset of c2, change to:
  7161. cmp ###,###
  7162. j(c1) @lbl2
  7163. (@lbl1 may become a dead label as a result)
  7164. }
  7165. { Also handle cases where there are multiple jumps in a row }
  7166. p_jump := hp1;
  7167. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7168. begin
  7169. if IsJumpToLabel(taicpu(p_jump)) then
  7170. begin
  7171. { Do jump optimisations first in case the condition becomes
  7172. unnecessary }
  7173. TempBool := True;
  7174. if DoJumpOptimizations(p_jump, TempBool) or
  7175. not TempBool then
  7176. begin
  7177. if Assigned(p_jump) then
  7178. begin
  7179. { CollapseZeroDistJump will be set to the label or an align
  7180. before it after the jump if it optimises, whether or not
  7181. the label is live or dead }
  7182. if (p_jump.typ = ait_align) or
  7183. (
  7184. (p_jump.typ = ait_label) and
  7185. not (tai_label(p_jump).labsym.is_used)
  7186. ) then
  7187. GetNextInstruction(p_jump, p_jump);
  7188. end;
  7189. TransferUsedRegs(TmpUsedRegs);
  7190. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7191. if not Assigned(p_jump) or
  7192. (
  7193. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7194. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7195. ) then
  7196. begin
  7197. { No more conditional jumps; conditional statement is no longer required }
  7198. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7199. RemoveCurrentP(p);
  7200. Result := True;
  7201. Exit;
  7202. end;
  7203. hp1 := p_jump;
  7204. Include(OptsToCheck, aoc_ForceNewIteration);
  7205. Continue;
  7206. end;
  7207. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7208. if GetNextInstruction(p_jump, hp2) and
  7209. (
  7210. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7211. not TempBool
  7212. ) then
  7213. begin
  7214. hp1 := p_jump;
  7215. Include(OptsToCheck, aoc_ForceNewIteration);
  7216. Continue;
  7217. end;
  7218. p_label := nil;
  7219. if Assigned(JumpLabel) then
  7220. p_label := getlabelwithsym(JumpLabel);
  7221. if Assigned(p_label) and
  7222. GetNextInstruction(p_label, p_dist) and
  7223. MatchInstruction(p_dist, A_CMP, []) and
  7224. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7225. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7226. GetNextInstruction(p_dist, hp1_dist) and
  7227. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7228. begin
  7229. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7230. if JumpLabel = JumpLabel_dist then
  7231. { This is an infinite loop }
  7232. Exit;
  7233. { Best optimisation when the first condition is a subset (or equal) of the second }
  7234. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7235. begin
  7236. { Any registers used here will already be allocated }
  7237. if Assigned(JumpLabel) then
  7238. JumpLabel.DecRefs;
  7239. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7240. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7241. Result := True;
  7242. { Don't exit yet. Since p and p_jump haven't actually been
  7243. removed, we can check for more on this iteration }
  7244. end
  7245. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7246. GetNextInstruction(hp1_dist, hp1_label) and
  7247. (hp1_label.typ = ait_label) then
  7248. begin
  7249. JumpLabel_far := tai_label(hp1_label).labsym;
  7250. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7251. { This is an infinite loop }
  7252. Exit;
  7253. if Assigned(JumpLabel_far) then
  7254. begin
  7255. { In this situation, if the first jump branches, the second one will never,
  7256. branch so change the destination label to after the second jump }
  7257. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7258. if Assigned(JumpLabel) then
  7259. JumpLabel.DecRefs;
  7260. JumpLabel_far.IncRefs;
  7261. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7262. Result := True;
  7263. { Don't exit yet. Since p and p_jump haven't actually been
  7264. removed, we can check for more on this iteration }
  7265. Continue;
  7266. end;
  7267. end;
  7268. end;
  7269. end;
  7270. { Search for:
  7271. cmp ###,###
  7272. j(c1) @lbl1
  7273. cmp ###,### (same as first)
  7274. Remove second cmp
  7275. }
  7276. if GetNextInstruction(p_jump, hp2) and
  7277. (
  7278. (
  7279. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7280. (
  7281. (
  7282. MatchOpType(taicpu(p), top_const, top_reg) and
  7283. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7284. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7285. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7286. ) or (
  7287. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7288. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7289. )
  7290. )
  7291. ) or (
  7292. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7293. MatchOperand(taicpu(p).oper[0]^, 0) and
  7294. (taicpu(p).oper[1]^.typ = top_reg) and
  7295. MatchInstruction(hp2, A_TEST, []) and
  7296. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7297. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7298. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7299. )
  7300. ) then
  7301. begin
  7302. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7303. RemoveInstruction(hp2);
  7304. Result := True;
  7305. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7306. end;
  7307. GetNextInstruction(p_jump, p_jump);
  7308. end;
  7309. if (
  7310. { Don't call GetNextInstruction again if we already have it }
  7311. (hp1 = p_jump) or
  7312. GetNextInstruction(p, hp1)
  7313. ) and
  7314. MatchInstruction(hp1, A_Jcc, []) and
  7315. IsJumpToLabel(taicpu(hp1)) and
  7316. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7317. GetNextInstruction(hp1, hp2) then
  7318. begin
  7319. {
  7320. cmp x, y (or "cmp y, x")
  7321. je @lbl
  7322. mov x, y
  7323. @lbl:
  7324. (x and y can be constants, registers or references)
  7325. Change to:
  7326. mov x, y (x and y will always be equal in the end)
  7327. @lbl: (may beceome a dead label)
  7328. Also:
  7329. cmp x, y (or "cmp y, x")
  7330. jne @lbl
  7331. mov x, y
  7332. @lbl:
  7333. (x and y can be constants, registers or references)
  7334. Change to:
  7335. Absolutely nothing! (Except @lbl if it's still live)
  7336. }
  7337. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7338. (
  7339. (
  7340. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7341. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7342. ) or (
  7343. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7344. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7345. )
  7346. ) and
  7347. GetNextInstruction(hp2, hp1_label) and
  7348. (hp1_label.typ = ait_label) and
  7349. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7350. begin
  7351. tai_label(hp1_label).labsym.DecRefs;
  7352. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7353. begin
  7354. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7355. RemoveInstruction(hp2);
  7356. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7357. end
  7358. else
  7359. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7360. RemoveInstruction(hp1);
  7361. RemoveCurrentp(p, hp2);
  7362. Result := True;
  7363. Exit;
  7364. end;
  7365. {
  7366. Try to optimise the following:
  7367. cmp $x,### ($x and $y can be registers or constants)
  7368. je @lbl1 (only reference)
  7369. cmp $y,### (### are identical)
  7370. @Lbl:
  7371. sete %reg1
  7372. Change to:
  7373. cmp $x,###
  7374. sete %reg2 (allocate new %reg2)
  7375. cmp $y,###
  7376. sete %reg1
  7377. orb %reg2,%reg1
  7378. (dealloc %reg2)
  7379. This adds an instruction (so don't perform under -Os), but it removes
  7380. a conditional branch.
  7381. }
  7382. if not (cs_opt_size in current_settings.optimizerswitches) and
  7383. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7384. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7385. { The first operand of CMP instructions can only be a register or
  7386. immediate anyway, so no need to check }
  7387. GetNextInstruction(hp2, p_label) and
  7388. (p_label.typ = ait_label) and
  7389. (tai_label(p_label).labsym.getrefs = 1) and
  7390. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7391. GetNextInstruction(p_label, p_dist) and
  7392. MatchInstruction(p_dist, A_SETcc, []) and
  7393. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7394. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7395. begin
  7396. TransferUsedRegs(TmpUsedRegs);
  7397. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7398. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7399. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7400. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7401. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7402. { Get the instruction after the SETcc instruction so we can
  7403. allocate a new register over the entire range }
  7404. GetNextInstruction(p_dist, hp1_dist) then
  7405. begin
  7406. { Register can appear in p if it's not used afterwards, so only
  7407. allocate between hp1 and hp1_dist }
  7408. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7409. if NewReg <> NR_NO then
  7410. begin
  7411. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7412. { Change the jump instruction into a SETcc instruction }
  7413. taicpu(hp1).opcode := A_SETcc;
  7414. taicpu(hp1).opsize := S_B;
  7415. taicpu(hp1).loadreg(0, NewReg);
  7416. { This is now a dead label }
  7417. tai_label(p_label).labsym.decrefs;
  7418. { Prefer adding before the next instruction so the FLAGS
  7419. register is deallicated first }
  7420. AsmL.InsertBefore(
  7421. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7422. hp1_dist
  7423. );
  7424. Result := True;
  7425. { Don't exit yet, as p wasn't changed and hp1, while
  7426. modified, is still intact and might be optimised by the
  7427. SETcc optimisation below }
  7428. end;
  7429. end;
  7430. end;
  7431. end;
  7432. if taicpu(p).oper[0]^.typ = top_const then
  7433. begin
  7434. if (taicpu(p).oper[0]^.val = 0) and
  7435. (taicpu(p).oper[1]^.typ = top_reg) and
  7436. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7437. begin
  7438. hp2 := p;
  7439. FirstMatch := True;
  7440. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7441. anything meaningful once it's converted to "test %reg,%reg";
  7442. additionally, some jumps will always (or never) branch, so
  7443. evaluate every jump immediately following the
  7444. comparison, optimising the conditions if possible.
  7445. Similarly with SETcc... those that are always set to 0 or 1
  7446. are changed to MOV instructions }
  7447. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7448. (
  7449. GetNextInstruction(hp2, hp1) and
  7450. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7451. ) do
  7452. begin
  7453. FirstMatch := False;
  7454. case taicpu(hp1).condition of
  7455. C_B, C_C, C_NAE, C_O:
  7456. { For B/NAE:
  7457. Will never branch since an unsigned integer can never be below zero
  7458. For C/O:
  7459. Result cannot overflow because 0 is being subtracted
  7460. }
  7461. begin
  7462. if taicpu(hp1).opcode = A_Jcc then
  7463. begin
  7464. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7465. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7466. RemoveInstruction(hp1);
  7467. { Since hp1 was deleted, hp2 must not be updated }
  7468. Continue;
  7469. end
  7470. else
  7471. begin
  7472. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7473. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7474. taicpu(hp1).opcode := A_MOV;
  7475. taicpu(hp1).ops := 2;
  7476. taicpu(hp1).condition := C_None;
  7477. taicpu(hp1).opsize := S_B;
  7478. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7479. taicpu(hp1).loadconst(0, 0);
  7480. end;
  7481. end;
  7482. C_BE, C_NA:
  7483. begin
  7484. { Will only branch if equal to zero }
  7485. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7486. taicpu(hp1).condition := C_E;
  7487. end;
  7488. C_A, C_NBE:
  7489. begin
  7490. { Will only branch if not equal to zero }
  7491. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7492. taicpu(hp1).condition := C_NE;
  7493. end;
  7494. C_AE, C_NB, C_NC, C_NO:
  7495. begin
  7496. { Will always branch }
  7497. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7498. if taicpu(hp1).opcode = A_Jcc then
  7499. begin
  7500. MakeUnconditional(taicpu(hp1));
  7501. { Any jumps/set that follow will now be dead code }
  7502. RemoveDeadCodeAfterJump(taicpu(hp1));
  7503. Break;
  7504. end
  7505. else
  7506. begin
  7507. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7508. taicpu(hp1).opcode := A_MOV;
  7509. taicpu(hp1).ops := 2;
  7510. taicpu(hp1).condition := C_None;
  7511. taicpu(hp1).opsize := S_B;
  7512. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7513. taicpu(hp1).loadconst(0, 1);
  7514. end;
  7515. end;
  7516. C_None:
  7517. InternalError(2020012201);
  7518. C_P, C_PE, C_NP, C_PO:
  7519. { We can't handle parity checks and they should never be generated
  7520. after a general-purpose CMP (it's used in some floating-point
  7521. comparisons that don't use CMP) }
  7522. InternalError(2020012202);
  7523. else
  7524. { Zero/Equality, Sign, their complements and all of the
  7525. signed comparisons do not need to be converted };
  7526. end;
  7527. hp2 := hp1;
  7528. end;
  7529. { Convert the instruction to a TEST }
  7530. taicpu(p).opcode := A_TEST;
  7531. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7532. Result := True;
  7533. Exit;
  7534. end
  7535. else if (taicpu(p).oper[0]^.val = 1) and
  7536. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7537. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7538. begin
  7539. { Convert; To:
  7540. cmp $1,r/m cmp $0,r/m
  7541. jl @lbl jle @lbl
  7542. (Also do inverted conditions)
  7543. }
  7544. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7545. taicpu(p).oper[0]^.val := 0;
  7546. if taicpu(hp1).condition in [C_L, C_NGE] then
  7547. taicpu(hp1).condition := C_LE
  7548. else
  7549. taicpu(hp1).condition := C_NLE;
  7550. { If the instruction is now "cmp $0,%reg", convert it to a
  7551. TEST (and effectively do the work of the "cmp $0,%reg" in
  7552. the block above)
  7553. }
  7554. if (taicpu(p).oper[1]^.typ = top_reg) then
  7555. begin
  7556. taicpu(p).opcode := A_TEST;
  7557. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7558. end;
  7559. Result := True;
  7560. Exit;
  7561. end
  7562. else if (taicpu(p).oper[1]^.typ = top_reg)
  7563. {$ifdef x86_64}
  7564. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7565. {$endif x86_64}
  7566. then
  7567. begin
  7568. { cmp register,$8000 neg register
  7569. je target --> jo target
  7570. .... only if register is deallocated before jump.}
  7571. case Taicpu(p).opsize of
  7572. S_B: v:=$80;
  7573. S_W: v:=$8000;
  7574. S_L: v:=qword($80000000);
  7575. else
  7576. internalerror(2013112905);
  7577. end;
  7578. if (taicpu(p).oper[0]^.val=v) and
  7579. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7580. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7581. begin
  7582. TransferUsedRegs(TmpUsedRegs);
  7583. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7584. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7585. begin
  7586. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7587. Taicpu(p).opcode:=A_NEG;
  7588. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7589. Taicpu(p).clearop(1);
  7590. Taicpu(p).ops:=1;
  7591. if Taicpu(hp1).condition=C_E then
  7592. Taicpu(hp1).condition:=C_O
  7593. else
  7594. Taicpu(hp1).condition:=C_NO;
  7595. Result:=true;
  7596. exit;
  7597. end;
  7598. end;
  7599. end;
  7600. end;
  7601. if TrySwapMovCmp(p, hp1) then
  7602. begin
  7603. Result := True;
  7604. Exit;
  7605. end;
  7606. end;
  7607. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7608. var
  7609. hp1: tai;
  7610. begin
  7611. {
  7612. remove the second (v)pxor from
  7613. pxor reg,reg
  7614. ...
  7615. pxor reg,reg
  7616. }
  7617. Result:=false;
  7618. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7619. MatchOpType(taicpu(p),top_reg,top_reg) and
  7620. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7621. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7622. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7623. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7624. begin
  7625. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7626. RemoveInstruction(hp1);
  7627. Result:=true;
  7628. Exit;
  7629. end
  7630. {
  7631. replace
  7632. pxor reg1,reg1
  7633. movapd/s reg1,reg2
  7634. dealloc reg1
  7635. by
  7636. pxor reg2,reg2
  7637. }
  7638. else if GetNextInstruction(p,hp1) and
  7639. { we mix single and double opperations here because we assume that the compiler
  7640. generates vmovapd only after double operations and vmovaps only after single operations }
  7641. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7642. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7643. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7644. (taicpu(p).oper[0]^.typ=top_reg) then
  7645. begin
  7646. TransferUsedRegs(TmpUsedRegs);
  7647. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7648. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7649. begin
  7650. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7651. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7652. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7653. RemoveInstruction(hp1);
  7654. result:=true;
  7655. end;
  7656. end;
  7657. end;
  7658. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7659. var
  7660. hp1: tai;
  7661. begin
  7662. {
  7663. remove the second (v)pxor from
  7664. (v)pxor reg,reg
  7665. ...
  7666. (v)pxor reg,reg
  7667. }
  7668. Result:=false;
  7669. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7670. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7671. begin
  7672. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7673. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7674. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7675. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7676. begin
  7677. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7678. RemoveInstruction(hp1);
  7679. Result:=true;
  7680. Exit;
  7681. end;
  7682. {$ifdef x86_64}
  7683. {
  7684. replace
  7685. vpxor reg1,reg1,reg1
  7686. vmov reg,mem
  7687. by
  7688. movq $0,mem
  7689. }
  7690. if GetNextInstruction(p,hp1) and
  7691. MatchInstruction(hp1,A_VMOVSD,[]) and
  7692. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7693. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7694. begin
  7695. TransferUsedRegs(TmpUsedRegs);
  7696. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7697. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7698. begin
  7699. taicpu(hp1).loadconst(0,0);
  7700. taicpu(hp1).opcode:=A_MOV;
  7701. taicpu(hp1).opsize:=S_Q;
  7702. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7703. RemoveCurrentP(p);
  7704. result:=true;
  7705. Exit;
  7706. end;
  7707. end;
  7708. {$endif x86_64}
  7709. end
  7710. {
  7711. replace
  7712. vpxor reg1,reg1,reg2
  7713. by
  7714. vpxor reg2,reg2,reg2
  7715. to avoid unncessary data dependencies
  7716. }
  7717. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7718. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7719. begin
  7720. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7721. { avoid unncessary data dependency }
  7722. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7723. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7724. result:=true;
  7725. exit;
  7726. end;
  7727. Result:=OptPass1VOP(p);
  7728. end;
  7729. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7730. var
  7731. hp1 : tai;
  7732. begin
  7733. result:=false;
  7734. { replace
  7735. IMul const,%mreg1,%mreg2
  7736. Mov %reg2,%mreg3
  7737. dealloc %mreg3
  7738. by
  7739. Imul const,%mreg1,%mreg23
  7740. }
  7741. if (taicpu(p).ops=3) and
  7742. GetNextInstruction(p,hp1) and
  7743. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7744. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7745. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7746. begin
  7747. TransferUsedRegs(TmpUsedRegs);
  7748. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7749. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7750. begin
  7751. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7752. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7753. RemoveInstruction(hp1);
  7754. result:=true;
  7755. end;
  7756. end;
  7757. end;
  7758. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7759. var
  7760. hp1 : tai;
  7761. begin
  7762. result:=false;
  7763. { replace
  7764. IMul %reg0,%reg1,%reg2
  7765. Mov %reg2,%reg3
  7766. dealloc %reg2
  7767. by
  7768. Imul %reg0,%reg1,%reg3
  7769. }
  7770. if GetNextInstruction(p,hp1) and
  7771. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7772. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7773. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7774. begin
  7775. TransferUsedRegs(TmpUsedRegs);
  7776. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7777. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7778. begin
  7779. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7780. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7781. RemoveInstruction(hp1);
  7782. result:=true;
  7783. end;
  7784. end;
  7785. end;
  7786. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7787. var
  7788. hp1: tai;
  7789. begin
  7790. Result:=false;
  7791. { get rid of
  7792. (v)cvtss2sd reg0,<reg1,>reg2
  7793. (v)cvtss2sd reg2,<reg2,>reg0
  7794. }
  7795. if GetNextInstruction(p,hp1) and
  7796. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7797. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7798. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7799. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7800. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7801. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7802. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7803. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7804. )
  7805. ) then
  7806. begin
  7807. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7808. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7809. begin
  7810. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7811. RemoveCurrentP(p);
  7812. RemoveInstruction(hp1);
  7813. end
  7814. else
  7815. begin
  7816. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7817. if taicpu(hp1).opcode=A_CVTSD2SS then
  7818. begin
  7819. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7820. taicpu(p).opcode:=A_MOVAPS;
  7821. end
  7822. else
  7823. begin
  7824. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7825. taicpu(p).opcode:=A_VMOVAPS;
  7826. end;
  7827. taicpu(p).ops:=2;
  7828. RemoveInstruction(hp1);
  7829. end;
  7830. Result:=true;
  7831. Exit;
  7832. end;
  7833. end;
  7834. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7835. var
  7836. hp1, hp2, hp3, hp4, hp5: tai;
  7837. ThisReg: TRegister;
  7838. begin
  7839. Result := False;
  7840. if not GetNextInstruction(p,hp1) then
  7841. Exit;
  7842. {
  7843. convert
  7844. j<c> .L1
  7845. mov 1,reg
  7846. jmp .L2
  7847. .L1
  7848. mov 0,reg
  7849. .L2
  7850. into
  7851. mov 0,reg
  7852. set<not(c)> reg
  7853. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7854. would destroy the flag contents
  7855. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7856. executed at the same time as a previous comparison.
  7857. set<not(c)> reg
  7858. movzx reg, reg
  7859. }
  7860. if MatchInstruction(hp1,A_MOV,[]) and
  7861. (taicpu(hp1).oper[0]^.typ = top_const) and
  7862. (
  7863. (
  7864. (taicpu(hp1).oper[1]^.typ = top_reg)
  7865. {$ifdef i386}
  7866. { Under i386, ESI, EDI, EBP and ESP
  7867. don't have an 8-bit representation }
  7868. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7869. {$endif i386}
  7870. ) or (
  7871. {$ifdef i386}
  7872. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7873. {$endif i386}
  7874. (taicpu(hp1).opsize = S_B)
  7875. )
  7876. ) and
  7877. GetNextInstruction(hp1,hp2) and
  7878. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7879. GetNextInstruction(hp2,hp3) and
  7880. (hp3.typ=ait_label) and
  7881. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7882. GetNextInstruction(hp3,hp4) and
  7883. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7884. (taicpu(hp4).oper[0]^.typ = top_const) and
  7885. (
  7886. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7887. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7888. ) and
  7889. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7890. GetNextInstruction(hp4,hp5) and
  7891. (hp5.typ=ait_label) and
  7892. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7893. begin
  7894. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7895. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7896. tai_label(hp3).labsym.DecRefs;
  7897. { If this isn't the only reference to the middle label, we can
  7898. still make a saving - only that the first jump and everything
  7899. that follows will remain. }
  7900. if (tai_label(hp3).labsym.getrefs = 0) then
  7901. begin
  7902. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7903. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7904. else
  7905. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7906. { remove jump, first label and second MOV (also catching any aligns) }
  7907. repeat
  7908. if not GetNextInstruction(hp2, hp3) then
  7909. InternalError(2021040810);
  7910. RemoveInstruction(hp2);
  7911. hp2 := hp3;
  7912. until hp2 = hp5;
  7913. { Don't decrement reference count before the removal loop
  7914. above, otherwise GetNextInstruction won't stop on the
  7915. the label }
  7916. tai_label(hp5).labsym.DecRefs;
  7917. end
  7918. else
  7919. begin
  7920. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7921. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7922. else
  7923. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7924. end;
  7925. taicpu(p).opcode:=A_SETcc;
  7926. taicpu(p).opsize:=S_B;
  7927. taicpu(p).is_jmp:=False;
  7928. if taicpu(hp1).opsize=S_B then
  7929. begin
  7930. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7931. if taicpu(hp1).oper[1]^.typ = top_reg then
  7932. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7933. RemoveInstruction(hp1);
  7934. end
  7935. else
  7936. begin
  7937. { Will be a register because the size can't be S_B otherwise }
  7938. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7939. taicpu(p).loadreg(0, ThisReg);
  7940. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7941. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7942. begin
  7943. case taicpu(hp1).opsize of
  7944. S_W:
  7945. taicpu(hp1).opsize := S_BW;
  7946. S_L:
  7947. taicpu(hp1).opsize := S_BL;
  7948. {$ifdef x86_64}
  7949. S_Q:
  7950. begin
  7951. taicpu(hp1).opsize := S_BL;
  7952. { Change the destination register to 32-bit }
  7953. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7954. end;
  7955. {$endif x86_64}
  7956. else
  7957. InternalError(2021040820);
  7958. end;
  7959. taicpu(hp1).opcode := A_MOVZX;
  7960. taicpu(hp1).loadreg(0, ThisReg);
  7961. end
  7962. else
  7963. begin
  7964. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7965. { hp1 is already a MOV instruction with the correct register }
  7966. taicpu(hp1).loadconst(0, 0);
  7967. { Inserting it right before p will guarantee that the flags are also tracked }
  7968. asml.Remove(hp1);
  7969. asml.InsertBefore(hp1, p);
  7970. end;
  7971. end;
  7972. Result:=true;
  7973. exit;
  7974. end
  7975. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  7976. Result := TryJccStcClcOpt(p, hp1)
  7977. else if (hp1.typ = ait_label) then
  7978. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7979. end;
  7980. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7981. var
  7982. hp1, hp2, hp3: tai;
  7983. SourceRef, TargetRef: TReference;
  7984. CurrentReg: TRegister;
  7985. begin
  7986. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7987. if not UseAVX then
  7988. InternalError(2021100501);
  7989. Result := False;
  7990. { Look for the following to simplify:
  7991. vmovdqa/u x(mem1), %xmmreg
  7992. vmovdqa/u %xmmreg, y(mem2)
  7993. vmovdqa/u x+16(mem1), %xmmreg
  7994. vmovdqa/u %xmmreg, y+16(mem2)
  7995. Change to:
  7996. vmovdqa/u x(mem1), %ymmreg
  7997. vmovdqa/u %ymmreg, y(mem2)
  7998. vpxor %ymmreg, %ymmreg, %ymmreg
  7999. ( The VPXOR instruction is to zero the upper half, thus removing the
  8000. need to call the potentially expensive VZEROUPPER instruction. Other
  8001. peephole optimisations can remove VPXOR if it's unnecessary )
  8002. }
  8003. TransferUsedRegs(TmpUsedRegs);
  8004. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8005. { NOTE: In the optimisations below, if the references dictate that an
  8006. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8007. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8008. if (taicpu(p).opsize = S_XMM) and
  8009. MatchOpType(taicpu(p), top_ref, top_reg) and
  8010. GetNextInstruction(p, hp1) and
  8011. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8012. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8013. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8014. begin
  8015. SourceRef := taicpu(p).oper[0]^.ref^;
  8016. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8017. if GetNextInstruction(hp1, hp2) and
  8018. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8019. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8020. begin
  8021. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8022. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8023. Inc(SourceRef.offset, 16);
  8024. { Reuse the register in the first block move }
  8025. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8026. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8027. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8028. begin
  8029. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8030. Inc(TargetRef.offset, 16);
  8031. if GetNextInstruction(hp2, hp3) and
  8032. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8033. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8034. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8035. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8036. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8037. begin
  8038. { Update the register tracking to the new size }
  8039. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8040. { Remember that the offsets are 16 ahead }
  8041. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8042. if not (
  8043. ((SourceRef.offset mod 32) = 16) and
  8044. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8045. ) then
  8046. taicpu(p).opcode := A_VMOVDQU;
  8047. taicpu(p).opsize := S_YMM;
  8048. taicpu(p).oper[1]^.reg := CurrentReg;
  8049. if not (
  8050. ((TargetRef.offset mod 32) = 16) and
  8051. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8052. ) then
  8053. taicpu(hp1).opcode := A_VMOVDQU;
  8054. taicpu(hp1).opsize := S_YMM;
  8055. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8056. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8057. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8058. if (pi_uses_ymm in current_procinfo.flags) then
  8059. RemoveInstruction(hp2)
  8060. else
  8061. begin
  8062. taicpu(hp2).opcode := A_VPXOR;
  8063. taicpu(hp2).opsize := S_YMM;
  8064. taicpu(hp2).loadreg(0, CurrentReg);
  8065. taicpu(hp2).loadreg(1, CurrentReg);
  8066. taicpu(hp2).loadreg(2, CurrentReg);
  8067. taicpu(hp2).ops := 3;
  8068. end;
  8069. RemoveInstruction(hp3);
  8070. Result := True;
  8071. Exit;
  8072. end;
  8073. end
  8074. else
  8075. begin
  8076. { See if the next references are 16 less rather than 16 greater }
  8077. Dec(SourceRef.offset, 32); { -16 the other way }
  8078. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8079. begin
  8080. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8081. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8082. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8083. GetNextInstruction(hp2, hp3) and
  8084. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8085. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8086. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8087. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8088. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8089. begin
  8090. { Update the register tracking to the new size }
  8091. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8092. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8093. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8094. if not(
  8095. ((SourceRef.offset mod 32) = 0) and
  8096. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8097. ) then
  8098. taicpu(hp2).opcode := A_VMOVDQU;
  8099. taicpu(hp2).opsize := S_YMM;
  8100. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8101. if not (
  8102. ((TargetRef.offset mod 32) = 0) and
  8103. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8104. ) then
  8105. taicpu(hp3).opcode := A_VMOVDQU;
  8106. taicpu(hp3).opsize := S_YMM;
  8107. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8108. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8109. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8110. if (pi_uses_ymm in current_procinfo.flags) then
  8111. RemoveInstruction(hp1)
  8112. else
  8113. begin
  8114. taicpu(hp1).opcode := A_VPXOR;
  8115. taicpu(hp1).opsize := S_YMM;
  8116. taicpu(hp1).loadreg(0, CurrentReg);
  8117. taicpu(hp1).loadreg(1, CurrentReg);
  8118. taicpu(hp1).loadreg(2, CurrentReg);
  8119. taicpu(hp1).ops := 3;
  8120. Asml.Remove(hp1);
  8121. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8122. end;
  8123. RemoveCurrentP(p, hp2);
  8124. Result := True;
  8125. Exit;
  8126. end;
  8127. end;
  8128. end;
  8129. end;
  8130. end;
  8131. end;
  8132. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8133. var
  8134. hp2, hp3, first_assignment: tai;
  8135. IncCount, OperIdx: Integer;
  8136. OrigLabel: TAsmLabel;
  8137. begin
  8138. Count := 0;
  8139. Result := False;
  8140. first_assignment := nil;
  8141. if (LoopCount >= 20) then
  8142. begin
  8143. { Guard against infinite loops }
  8144. Exit;
  8145. end;
  8146. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8147. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8148. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8149. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8150. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8151. Exit;
  8152. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8153. {
  8154. change
  8155. jmp .L1
  8156. ...
  8157. .L1:
  8158. mov ##, ## ( multiple movs possible )
  8159. jmp/ret
  8160. into
  8161. mov ##, ##
  8162. jmp/ret
  8163. }
  8164. if not Assigned(hp1) then
  8165. begin
  8166. hp1 := GetLabelWithSym(OrigLabel);
  8167. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8168. Exit;
  8169. end;
  8170. hp2 := hp1;
  8171. while Assigned(hp2) do
  8172. begin
  8173. if Assigned(hp2) and (hp2.typ = ait_label) then
  8174. SkipLabels(hp2,hp2);
  8175. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8176. Break;
  8177. case taicpu(hp2).opcode of
  8178. A_MOVSD:
  8179. begin
  8180. if taicpu(hp2).ops = 0 then
  8181. { Wrong MOVSD }
  8182. Break;
  8183. Inc(Count);
  8184. if Count >= 5 then
  8185. { Too many to be worthwhile }
  8186. Break;
  8187. GetNextInstruction(hp2, hp2);
  8188. Continue;
  8189. end;
  8190. A_MOV,
  8191. A_MOVD,
  8192. A_MOVQ,
  8193. A_MOVSX,
  8194. {$ifdef x86_64}
  8195. A_MOVSXD,
  8196. {$endif x86_64}
  8197. A_MOVZX,
  8198. A_MOVAPS,
  8199. A_MOVUPS,
  8200. A_MOVSS,
  8201. A_MOVAPD,
  8202. A_MOVUPD,
  8203. A_MOVDQA,
  8204. A_MOVDQU,
  8205. A_VMOVSS,
  8206. A_VMOVAPS,
  8207. A_VMOVUPS,
  8208. A_VMOVSD,
  8209. A_VMOVAPD,
  8210. A_VMOVUPD,
  8211. A_VMOVDQA,
  8212. A_VMOVDQU:
  8213. begin
  8214. Inc(Count);
  8215. if Count >= 5 then
  8216. { Too many to be worthwhile }
  8217. Break;
  8218. GetNextInstruction(hp2, hp2);
  8219. Continue;
  8220. end;
  8221. A_JMP:
  8222. begin
  8223. { Guard against infinite loops }
  8224. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8225. Exit;
  8226. { Analyse this jump first in case it also duplicates assignments }
  8227. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8228. begin
  8229. { Something did change! }
  8230. Result := True;
  8231. Inc(Count, IncCount);
  8232. if Count >= 5 then
  8233. begin
  8234. { Too many to be worthwhile }
  8235. Exit;
  8236. end;
  8237. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8238. Break;
  8239. end;
  8240. Result := True;
  8241. Break;
  8242. end;
  8243. A_RET:
  8244. begin
  8245. Result := True;
  8246. Break;
  8247. end;
  8248. else
  8249. Break;
  8250. end;
  8251. end;
  8252. if Result then
  8253. begin
  8254. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8255. if Count = 0 then
  8256. begin
  8257. Result := False;
  8258. Exit;
  8259. end;
  8260. hp3 := p;
  8261. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8262. while True do
  8263. begin
  8264. if Assigned(hp1) and (hp1.typ = ait_label) then
  8265. SkipLabels(hp1,hp1);
  8266. if (hp1.typ <> ait_instruction) then
  8267. InternalError(2021040720);
  8268. case taicpu(hp1).opcode of
  8269. A_JMP:
  8270. begin
  8271. { Change the original jump to the new destination }
  8272. OrigLabel.decrefs;
  8273. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8274. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8275. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8276. if not Assigned(first_assignment) then
  8277. InternalError(2021040810)
  8278. else
  8279. p := first_assignment;
  8280. Exit;
  8281. end;
  8282. A_RET:
  8283. begin
  8284. { Now change the jump into a RET instruction }
  8285. ConvertJumpToRET(p, hp1);
  8286. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8287. if not Assigned(first_assignment) then
  8288. InternalError(2021040811)
  8289. else
  8290. p := first_assignment;
  8291. Exit;
  8292. end;
  8293. else
  8294. begin
  8295. { Duplicate the MOV instruction }
  8296. hp3:=tai(hp1.getcopy);
  8297. if first_assignment = nil then
  8298. first_assignment := hp3;
  8299. asml.InsertBefore(hp3, p);
  8300. { Make sure the compiler knows about any final registers written here }
  8301. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8302. with taicpu(hp3).oper[OperIdx]^ do
  8303. begin
  8304. case typ of
  8305. top_ref:
  8306. begin
  8307. if (ref^.base <> NR_NO) and
  8308. (getsupreg(ref^.base) <> RS_ESP) and
  8309. (getsupreg(ref^.base) <> RS_EBP)
  8310. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8311. then
  8312. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8313. if (ref^.index <> NR_NO) and
  8314. (getsupreg(ref^.index) <> RS_ESP) and
  8315. (getsupreg(ref^.index) <> RS_EBP)
  8316. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8317. (ref^.index <> ref^.base) then
  8318. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8319. end;
  8320. top_reg:
  8321. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8322. else
  8323. ;
  8324. end;
  8325. end;
  8326. end;
  8327. end;
  8328. if not GetNextInstruction(hp1, hp1) then
  8329. { Should have dropped out earlier }
  8330. InternalError(2021040710);
  8331. end;
  8332. end;
  8333. end;
  8334. const
  8335. WriteOp: array[0..3] of set of TInsChange = (
  8336. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8337. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8338. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8339. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8340. RegWriteFlags: array[0..7] of set of TInsChange = (
  8341. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8342. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8343. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8344. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8345. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8346. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8347. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8348. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8349. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8350. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8351. var
  8352. hp2: tai;
  8353. X: Integer;
  8354. begin
  8355. { If we have something like:
  8356. op ###,###
  8357. mov ###,###
  8358. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8359. interfere in regards to what they write to.
  8360. NOTE: p must be a 2-operand instruction
  8361. }
  8362. Result := False;
  8363. if (hp1.typ <> ait_instruction) or
  8364. taicpu(hp1).is_jmp or
  8365. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8366. Exit;
  8367. { NOP is a pipeline fence, likely marking the beginning of the function
  8368. epilogue, so drop out. Similarly, drop out if POP or RET are
  8369. encountered }
  8370. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8371. Exit;
  8372. if (taicpu(hp1).opcode = A_MOVSD) and
  8373. (taicpu(hp1).ops = 0) then
  8374. { Wrong MOVSD }
  8375. Exit;
  8376. { Check for writes to specific registers first }
  8377. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8378. for X := 0 to 7 do
  8379. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8380. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8381. Exit;
  8382. for X := 0 to taicpu(hp1).ops - 1 do
  8383. begin
  8384. { Check to see if this operand writes to something }
  8385. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8386. { And matches something in the CMP/TEST instruction }
  8387. (
  8388. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8389. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8390. (
  8391. { If it's a register, make sure the register written to doesn't
  8392. appear in the cmp instruction as part of a reference }
  8393. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8394. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8395. )
  8396. ) then
  8397. Exit;
  8398. end;
  8399. { Check p to make sure it doesn't write to something that affects hp1 }
  8400. { Check for writes to specific registers first }
  8401. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8402. for X := 0 to 7 do
  8403. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8404. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8405. Exit;
  8406. for X := 0 to taicpu(p).ops - 1 do
  8407. begin
  8408. { Check to see if this operand writes to something }
  8409. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8410. { And matches something in hp1 }
  8411. (taicpu(p).oper[X]^.typ = top_reg) and
  8412. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8413. Exit;
  8414. end;
  8415. { The instruction can be safely moved }
  8416. asml.Remove(hp1);
  8417. { Try to insert after the last instructions where the FLAGS register is not
  8418. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8419. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8420. asml.InsertBefore(hp1, hp2)
  8421. { Failing that, try to insert after the last instructions where the
  8422. FLAGS register is not yet in use }
  8423. else if GetLastInstruction(p, hp2) and
  8424. (
  8425. (hp2.typ <> ait_instruction) or
  8426. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8427. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8428. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8429. ) then
  8430. asml.InsertAfter(hp1, hp2)
  8431. else
  8432. { Note, if p.Previous is nil (even if it should logically never be the
  8433. case), FindRegAllocBackward immediately exits with False and so we
  8434. safely land here (we can't just pass p because FindRegAllocBackward
  8435. immediately exits on an instruction). [Kit] }
  8436. asml.InsertBefore(hp1, p);
  8437. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8438. { We can't trust UsedRegs because we're looking backwards, although we
  8439. know the registers are allocated after p at the very least, so manually
  8440. create tai_regalloc objects if needed }
  8441. for X := 0 to taicpu(hp1).ops - 1 do
  8442. case taicpu(hp1).oper[X]^.typ of
  8443. top_reg:
  8444. begin
  8445. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8446. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8447. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8448. end;
  8449. top_ref:
  8450. begin
  8451. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8452. begin
  8453. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8454. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8455. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8456. end;
  8457. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8458. begin
  8459. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8460. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8461. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8462. end;
  8463. end;
  8464. else
  8465. ;
  8466. end;
  8467. Result := True;
  8468. end;
  8469. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8470. var
  8471. hp2: tai;
  8472. X: Integer;
  8473. begin
  8474. { If we have something like:
  8475. cmp ###,%reg1
  8476. mov 0,%reg2
  8477. And no modified registers are shared, move the instruction to before
  8478. the comparison as this means it can be optimised without worrying
  8479. about the FLAGS register. (CMP/MOV is generated by
  8480. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8481. As long as the second instruction doesn't use the flags or one of the
  8482. registers used by CMP or TEST (also check any references that use the
  8483. registers), then it can be moved prior to the comparison.
  8484. }
  8485. Result := False;
  8486. if not TrySwapMovOp(p, hp1) then
  8487. Exit;
  8488. if taicpu(hp1).opcode = A_LEA then
  8489. { The flags will be overwritten by the CMP/TEST instruction }
  8490. ConvertLEA(taicpu(hp1));
  8491. Result := True;
  8492. { Can we move it one further back? }
  8493. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8494. { Check to see if CMP/TEST is a comparison against zero }
  8495. (
  8496. (
  8497. (taicpu(p).opcode = A_CMP) and
  8498. MatchOperand(taicpu(p).oper[0]^, 0)
  8499. ) or
  8500. (
  8501. (taicpu(p).opcode = A_TEST) and
  8502. (
  8503. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8504. MatchOperand(taicpu(p).oper[0]^, -1)
  8505. )
  8506. )
  8507. ) and
  8508. { These instructions set the zero flag if the result is zero }
  8509. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8510. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8511. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8512. TrySwapMovOp(hp2, hp1);
  8513. end;
  8514. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8515. var
  8516. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8517. JumpLabel: TAsmLabel;
  8518. TmpBool: Boolean;
  8519. begin
  8520. Result := False;
  8521. { Look for:
  8522. stc/clc
  8523. j(c) .L1
  8524. ...
  8525. .L1:
  8526. set(n)cb %reg
  8527. (flags deallocated)
  8528. j(c) .L2
  8529. Change to:
  8530. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8531. j(c) .L2
  8532. }
  8533. p_last := p;
  8534. while GetNextInstruction(p_last, hp1) and
  8535. (hp1.typ = ait_instruction) and
  8536. IsJumpToLabel(taicpu(hp1)) do
  8537. begin
  8538. if DoJumpOptimizations(hp1, TmpBool) then
  8539. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8540. Continue;
  8541. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8542. if not Assigned(JumpLabel) then
  8543. InternalError(2024012801);
  8544. { Optimise the J(c); stc/clc optimisation first since this will
  8545. get missed if the main optimisation takes place }
  8546. if (taicpu(hp1).opcode = A_JCC) then
  8547. begin
  8548. if GetNextInstruction(hp1, hp2) and
  8549. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8550. TryJccStcClcOpt(hp1, hp2) then
  8551. begin
  8552. Result := True;
  8553. Exit;
  8554. end;
  8555. hp2 := nil; { Suppress compiler warning }
  8556. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8557. { Make sure the flags aren't used again }
  8558. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8559. begin
  8560. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8561. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8562. begin
  8563. if (taicpu(p).opcode = A_STC) then
  8564. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8565. else
  8566. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8567. MakeUnconditional(taicpu(hp1));
  8568. { Move the jump to after the flag deallocations }
  8569. Asml.Remove(hp1);
  8570. Asml.InsertAfter(hp1, hp2);
  8571. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8572. Result := True;
  8573. Exit;
  8574. end
  8575. else
  8576. begin
  8577. if (taicpu(p).opcode = A_STC) then
  8578. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8579. else
  8580. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8581. { In this case, the jump is deterministic in that it will never be taken }
  8582. JumpLabel.DecRefs;
  8583. RemoveInstruction(hp1);
  8584. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8585. Result := True;
  8586. Exit;
  8587. end;
  8588. end;
  8589. end;
  8590. hp2 := nil; { Suppress compiler warning }
  8591. if
  8592. { Make sure the carry flag doesn't appear in the jump conditions }
  8593. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8594. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8595. GetNextInstruction(hp2, p_dist) and
  8596. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8597. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8598. begin
  8599. case taicpu(p_dist).opcode of
  8600. A_Jcc:
  8601. begin
  8602. if DoJumpOptimizations(p_dist, TmpBool) then
  8603. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8604. Continue;
  8605. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8606. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8607. begin
  8608. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8609. JumpLabel.decrefs;
  8610. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8611. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8612. Result := True;
  8613. Exit;
  8614. end
  8615. else if GetNextInstruction(p_dist, hp1_dist) and
  8616. (hp1_dist.typ = ait_label) then
  8617. begin
  8618. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8619. JumpLabel.decrefs;
  8620. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8621. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8622. Result := True;
  8623. Exit;
  8624. end;
  8625. end;
  8626. A_SETcc:
  8627. if { Make sure the flags aren't used again }
  8628. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8629. GetNextInstruction(hp2, hp1_dist) and
  8630. (hp1_dist.typ = ait_instruction) and
  8631. IsJumpToLabel(taicpu(hp1_dist)) and
  8632. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8633. { This works if hp1_dist or both are regular JMP instructions }
  8634. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  8635. begin
  8636. taicpu(p).allocate_oper(2);
  8637. taicpu(p).ops := 2;
  8638. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8639. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8640. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8641. taicpu(p).opcode := A_MOV;
  8642. taicpu(p).opsize := S_B;
  8643. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8644. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8645. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8646. JumpLabel.decrefs;
  8647. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8648. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8649. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8650. (tai_regalloc(hp2).ratype = ra_alloc) then
  8651. begin
  8652. Asml.Remove(hp2);
  8653. Asml.InsertAfter(hp2, p);
  8654. end;
  8655. Result := True;
  8656. Exit;
  8657. end;
  8658. else
  8659. ;
  8660. end;
  8661. end;
  8662. p_last := hp1;
  8663. end;
  8664. end;
  8665. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8666. var
  8667. hp2, hp3: tai;
  8668. TempBool: Boolean;
  8669. begin
  8670. Result := False;
  8671. {
  8672. j(c) .L1
  8673. stc/clc
  8674. .L1:
  8675. jc/jnc .L2
  8676. (Flags deallocated)
  8677. Change to:
  8678. j)c) .L1
  8679. jmp .L2
  8680. .L1:
  8681. jc/jnc .L2
  8682. Then call DoJumpOptimizations to convert to:
  8683. j(nc) .L2
  8684. .L1: (may become a dead label)
  8685. jc/jnc .L2
  8686. }
  8687. if GetNextInstruction(hp1, hp2) and
  8688. (hp2.typ = ait_label) and
  8689. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8690. GetNextInstruction(hp2, hp3) and
  8691. MatchInstruction(hp3, A_Jcc, []) and
  8692. (
  8693. (
  8694. (taicpu(hp3).condition = C_C) and
  8695. (taicpu(hp1).opcode = A_STC)
  8696. ) or (
  8697. (taicpu(hp3).condition = C_NC) and
  8698. (taicpu(hp1).opcode = A_CLC)
  8699. )
  8700. ) and
  8701. { Make sure the flags aren't used again }
  8702. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8703. begin
  8704. taicpu(hp1).allocate_oper(1);
  8705. taicpu(hp1).ops := 1;
  8706. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8707. taicpu(hp1).opcode := A_JMP;
  8708. taicpu(hp1).is_jmp := True;
  8709. TempBool := True; { Prevent compiler warnings }
  8710. if DoJumpOptimizations(p, TempBool) then
  8711. Result := True
  8712. else
  8713. Include(OptsToCheck, aoc_ForceNewIteration);
  8714. end;
  8715. end;
  8716. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  8717. begin
  8718. { This generally only executes under -O3 and above }
  8719. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  8720. end;
  8721. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8722. function IsXCHGAcceptable: Boolean; inline;
  8723. begin
  8724. { Always accept if optimising for size }
  8725. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8726. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8727. than 3, so it becomes a saving compared to three MOVs with two of
  8728. them able to execute simultaneously. [Kit] }
  8729. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8730. end;
  8731. var
  8732. NewRef: TReference;
  8733. hp1, hp2, hp3, hp4: Tai;
  8734. {$ifndef x86_64}
  8735. OperIdx: Integer;
  8736. {$endif x86_64}
  8737. NewInstr : Taicpu;
  8738. NewAligh : Tai_align;
  8739. DestLabel: TAsmLabel;
  8740. TempTracking: TAllUsedRegs;
  8741. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8742. var
  8743. NextInstr: tai;
  8744. begin
  8745. Result := False;
  8746. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8747. if not GetNextInstruction(InputInstr, NextInstr) or
  8748. (
  8749. { The FLAGS register isn't always tracked properly, so do not
  8750. perform this optimisation if a conditional statement follows }
  8751. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8752. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8753. ) then
  8754. begin
  8755. reference_reset(NewRef, 1, []);
  8756. NewRef.base := taicpu(p).oper[0]^.reg;
  8757. NewRef.scalefactor := 1;
  8758. if taicpu(InputInstr).opcode = A_ADD then
  8759. begin
  8760. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8761. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8762. end
  8763. else
  8764. begin
  8765. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8766. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8767. end;
  8768. taicpu(p).opcode := A_LEA;
  8769. taicpu(p).loadref(0, NewRef);
  8770. RemoveInstruction(InputInstr);
  8771. Result := True;
  8772. end;
  8773. end;
  8774. begin
  8775. Result:=false;
  8776. { This optimisation adds an instruction, so only do it for speed }
  8777. if not (cs_opt_size in current_settings.optimizerswitches) and
  8778. MatchOpType(taicpu(p), top_const, top_reg) and
  8779. (taicpu(p).oper[0]^.val = 0) then
  8780. begin
  8781. { To avoid compiler warning }
  8782. DestLabel := nil;
  8783. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8784. InternalError(2021040750);
  8785. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8786. Exit;
  8787. case hp1.typ of
  8788. ait_label:
  8789. begin
  8790. { Change:
  8791. mov $0,%reg mov $0,%reg
  8792. @Lbl1: @Lbl1:
  8793. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8794. je @Lbl2 jne @Lbl2
  8795. To: To:
  8796. mov $0,%reg mov $0,%reg
  8797. jmp @Lbl2 jmp @Lbl3
  8798. (align) (align)
  8799. @Lbl1: @Lbl1:
  8800. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8801. je @Lbl2 je @Lbl2
  8802. @Lbl3: <-- Only if label exists
  8803. (Not if it's optimised for size)
  8804. }
  8805. if not GetNextInstruction(hp1, hp2) then
  8806. Exit;
  8807. if (hp2.typ = ait_instruction) and
  8808. (
  8809. { Register sizes must exactly match }
  8810. (
  8811. (taicpu(hp2).opcode = A_CMP) and
  8812. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8813. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8814. ) or (
  8815. (taicpu(hp2).opcode = A_TEST) and
  8816. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8817. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8818. )
  8819. ) and GetNextInstruction(hp2, hp3) and
  8820. (hp3.typ = ait_instruction) and
  8821. (taicpu(hp3).opcode = A_JCC) and
  8822. (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
  8823. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8824. begin
  8825. { Check condition of jump }
  8826. { Always true? }
  8827. if condition_in(C_E, taicpu(hp3).condition) then
  8828. begin
  8829. { Copy label symbol and obtain matching label entry for the
  8830. conditional jump, as this will be our destination}
  8831. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8832. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8833. Result := True;
  8834. end
  8835. { Always false? }
  8836. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8837. begin
  8838. { This is only worth it if there's a jump to take }
  8839. case hp2.typ of
  8840. ait_instruction:
  8841. begin
  8842. if taicpu(hp2).opcode = A_JMP then
  8843. begin
  8844. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8845. { An unconditional jump follows the conditional jump which will always be false,
  8846. so use this jump's destination for the new jump }
  8847. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8848. Result := True;
  8849. end
  8850. else if taicpu(hp2).opcode = A_JCC then
  8851. begin
  8852. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8853. if condition_in(C_E, taicpu(hp2).condition) then
  8854. begin
  8855. { A second conditional jump follows the conditional jump which will always be false,
  8856. while the second jump is always True, so use this jump's destination for the new jump }
  8857. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8858. Result := True;
  8859. end;
  8860. { Don't risk it if the jump isn't always true (Result remains False) }
  8861. end;
  8862. end;
  8863. else
  8864. { If anything else don't optimise };
  8865. end;
  8866. end;
  8867. if Result then
  8868. begin
  8869. { Just so we have something to insert as a paremeter}
  8870. reference_reset(NewRef, 1, []);
  8871. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8872. { Now actually load the correct parameter (this also
  8873. increases the reference count) }
  8874. NewInstr.loadsymbol(0, DestLabel, 0);
  8875. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8876. begin
  8877. { Get instruction before original label (may not be p under -O3) }
  8878. if not GetLastInstruction(hp1, hp2) then
  8879. { Shouldn't fail here }
  8880. InternalError(2021040701);
  8881. end
  8882. else
  8883. hp2 := p;
  8884. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8885. AsmL.InsertAfter(NewInstr, hp2);
  8886. { Add new alignment field }
  8887. (* AsmL.InsertAfter(
  8888. cai_align.create_max(
  8889. current_settings.alignment.jumpalign,
  8890. current_settings.alignment.jumpalignskipmax
  8891. ),
  8892. NewInstr
  8893. ); *)
  8894. end;
  8895. Exit;
  8896. end;
  8897. end;
  8898. else
  8899. ;
  8900. end;
  8901. end;
  8902. if not GetNextInstruction(p, hp1) then
  8903. Exit;
  8904. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8905. and DoMovCmpMemOpt(p, hp1) then
  8906. begin
  8907. Result := True;
  8908. Exit;
  8909. end
  8910. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8911. begin
  8912. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8913. further, but we can't just put this jump optimisation in pass 1
  8914. because it tends to perform worse when conditional jumps are
  8915. nearby (e.g. when converting CMOV instructions). [Kit] }
  8916. CopyUsedRegs(TempTracking);
  8917. UpdateUsedRegs(tai(p.Next));
  8918. if OptPass2JMP(hp1) then
  8919. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8920. Result := OptPass1MOV(p);
  8921. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8922. returned True and the instruction is still a MOV, thus checking
  8923. the optimisations below }
  8924. { If OptPass2JMP returned False, no optimisations were done to
  8925. the jump and there are no further optimisations that can be done
  8926. to the MOV instruction on this pass }
  8927. { Restore register state }
  8928. RestoreUsedRegs(TempTracking);
  8929. ReleaseUsedRegs(TempTracking);
  8930. end
  8931. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8932. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8933. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8934. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8935. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8936. begin
  8937. { Change:
  8938. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8939. addl/q $x,%reg2 subl/q $x,%reg2
  8940. To:
  8941. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8942. }
  8943. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8944. { be lazy, checking separately for sub would be slightly better }
  8945. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8946. begin
  8947. TransferUsedRegs(TmpUsedRegs);
  8948. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8949. if TryMovArith2Lea(hp1) then
  8950. begin
  8951. Result := True;
  8952. Exit;
  8953. end
  8954. end
  8955. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8956. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8957. { Same as above, but also adds or subtracts to %reg2 in between.
  8958. It's still valid as long as the flags aren't in use }
  8959. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8960. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8961. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8962. { be lazy, checking separately for sub would be slightly better }
  8963. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8964. begin
  8965. TransferUsedRegs(TmpUsedRegs);
  8966. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8967. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8968. if TryMovArith2Lea(hp2) then
  8969. begin
  8970. Result := True;
  8971. Exit;
  8972. end;
  8973. end;
  8974. end
  8975. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8976. {$ifdef x86_64}
  8977. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8978. {$else x86_64}
  8979. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8980. {$endif x86_64}
  8981. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8982. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8983. { mov reg1, reg2 mov reg1, reg2
  8984. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8985. begin
  8986. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8987. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8988. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8989. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8990. TransferUsedRegs(TmpUsedRegs);
  8991. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8992. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8993. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8994. then
  8995. begin
  8996. RemoveCurrentP(p, hp1);
  8997. Result:=true;
  8998. end;
  8999. exit;
  9000. end
  9001. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  9002. IsXCHGAcceptable and
  9003. { XCHG doesn't support 8-byte registers }
  9004. (taicpu(p).opsize <> S_B) and
  9005. MatchInstruction(hp1, A_MOV, []) and
  9006. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9007. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9008. GetNextInstruction(hp1, hp2) and
  9009. MatchInstruction(hp2, A_MOV, []) and
  9010. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9011. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9012. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9013. begin
  9014. { mov %reg1,%reg2
  9015. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9016. mov %reg2,%reg3
  9017. (%reg2 not used afterwards)
  9018. Note that xchg takes 3 cycles to execute, and generally mov's take
  9019. only one cycle apiece, but the first two mov's can be executed in
  9020. parallel, only taking 2 cycles overall. Older processors should
  9021. therefore only optimise for size. [Kit]
  9022. }
  9023. TransferUsedRegs(TmpUsedRegs);
  9024. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9025. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9026. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9027. begin
  9028. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9029. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9030. taicpu(hp1).opcode := A_XCHG;
  9031. RemoveCurrentP(p, hp1);
  9032. RemoveInstruction(hp2);
  9033. Result := True;
  9034. Exit;
  9035. end;
  9036. end
  9037. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  9038. MatchInstruction(hp1, A_SAR, []) then
  9039. begin
  9040. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9041. begin
  9042. { the use of %edx also covers the opsize being S_L }
  9043. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9044. begin
  9045. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9046. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9047. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9048. begin
  9049. { Change:
  9050. movl %eax,%edx
  9051. sarl $31,%edx
  9052. To:
  9053. cltd
  9054. }
  9055. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9056. RemoveInstruction(hp1);
  9057. taicpu(p).opcode := A_CDQ;
  9058. taicpu(p).opsize := S_NO;
  9059. taicpu(p).clearop(1);
  9060. taicpu(p).clearop(0);
  9061. taicpu(p).ops:=0;
  9062. Result := True;
  9063. end
  9064. else if (cs_opt_size in current_settings.optimizerswitches) and
  9065. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9066. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9067. begin
  9068. { Change:
  9069. movl %edx,%eax
  9070. sarl $31,%edx
  9071. To:
  9072. movl %edx,%eax
  9073. cltd
  9074. Note that this creates a dependency between the two instructions,
  9075. so only perform if optimising for size.
  9076. }
  9077. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9078. taicpu(hp1).opcode := A_CDQ;
  9079. taicpu(hp1).opsize := S_NO;
  9080. taicpu(hp1).clearop(1);
  9081. taicpu(hp1).clearop(0);
  9082. taicpu(hp1).ops:=0;
  9083. end;
  9084. {$ifndef x86_64}
  9085. end
  9086. { Don't bother if CMOV is supported, because a more optimal
  9087. sequence would have been generated for the Abs() intrinsic }
  9088. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9089. { the use of %eax also covers the opsize being S_L }
  9090. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9091. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9092. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9093. GetNextInstruction(hp1, hp2) and
  9094. MatchInstruction(hp2, A_XOR, [S_L]) and
  9095. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9096. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9097. GetNextInstruction(hp2, hp3) and
  9098. MatchInstruction(hp3, A_SUB, [S_L]) and
  9099. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9100. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9101. begin
  9102. { Change:
  9103. movl %eax,%edx
  9104. sarl $31,%eax
  9105. xorl %eax,%edx
  9106. subl %eax,%edx
  9107. (Instruction that uses %edx)
  9108. (%eax deallocated)
  9109. (%edx deallocated)
  9110. To:
  9111. cltd
  9112. xorl %edx,%eax <-- Note the registers have swapped
  9113. subl %edx,%eax
  9114. (Instruction that uses %eax) <-- %eax rather than %edx
  9115. }
  9116. TransferUsedRegs(TmpUsedRegs);
  9117. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9118. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9119. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9120. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9121. begin
  9122. if GetNextInstruction(hp3, hp4) and
  9123. not RegModifiedByInstruction(NR_EDX, hp4) and
  9124. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9125. begin
  9126. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9127. taicpu(p).opcode := A_CDQ;
  9128. taicpu(p).clearop(1);
  9129. taicpu(p).clearop(0);
  9130. taicpu(p).ops:=0;
  9131. RemoveInstruction(hp1);
  9132. taicpu(hp2).loadreg(0, NR_EDX);
  9133. taicpu(hp2).loadreg(1, NR_EAX);
  9134. taicpu(hp3).loadreg(0, NR_EDX);
  9135. taicpu(hp3).loadreg(1, NR_EAX);
  9136. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9137. { Convert references in the following instruction (hp4) from %edx to %eax }
  9138. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9139. with taicpu(hp4).oper[OperIdx]^ do
  9140. case typ of
  9141. top_reg:
  9142. if getsupreg(reg) = RS_EDX then
  9143. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9144. top_ref:
  9145. begin
  9146. if getsupreg(reg) = RS_EDX then
  9147. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9148. if getsupreg(reg) = RS_EDX then
  9149. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9150. end;
  9151. else
  9152. ;
  9153. end;
  9154. end;
  9155. end;
  9156. {$else x86_64}
  9157. end;
  9158. end
  9159. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9160. { the use of %rdx also covers the opsize being S_Q }
  9161. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9162. begin
  9163. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9164. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9165. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9166. begin
  9167. { Change:
  9168. movq %rax,%rdx
  9169. sarq $63,%rdx
  9170. To:
  9171. cqto
  9172. }
  9173. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9174. RemoveInstruction(hp1);
  9175. taicpu(p).opcode := A_CQO;
  9176. taicpu(p).opsize := S_NO;
  9177. taicpu(p).clearop(1);
  9178. taicpu(p).clearop(0);
  9179. taicpu(p).ops:=0;
  9180. Result := True;
  9181. end
  9182. else if (cs_opt_size in current_settings.optimizerswitches) and
  9183. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9184. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9185. begin
  9186. { Change:
  9187. movq %rdx,%rax
  9188. sarq $63,%rdx
  9189. To:
  9190. movq %rdx,%rax
  9191. cqto
  9192. Note that this creates a dependency between the two instructions,
  9193. so only perform if optimising for size.
  9194. }
  9195. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9196. taicpu(hp1).opcode := A_CQO;
  9197. taicpu(hp1).opsize := S_NO;
  9198. taicpu(hp1).clearop(1);
  9199. taicpu(hp1).clearop(0);
  9200. taicpu(hp1).ops:=0;
  9201. {$endif x86_64}
  9202. end;
  9203. end;
  9204. end
  9205. else if MatchInstruction(hp1, A_MOV, []) and
  9206. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9207. { Though "GetNextInstruction" could be factored out, along with
  9208. the instructions that depend on hp2, it is an expensive call that
  9209. should be delayed for as long as possible, hence we do cheaper
  9210. checks first that are likely to be False. [Kit] }
  9211. begin
  9212. if (
  9213. (
  9214. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9215. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9216. (
  9217. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9218. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9219. )
  9220. ) or
  9221. (
  9222. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9223. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9224. (
  9225. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9226. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9227. )
  9228. )
  9229. ) and
  9230. GetNextInstruction(hp1, hp2) and
  9231. MatchInstruction(hp2, A_SAR, []) and
  9232. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9233. begin
  9234. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9235. begin
  9236. { Change:
  9237. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9238. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9239. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9240. To:
  9241. movl r/m,%eax <- Note the change in register
  9242. cltd
  9243. }
  9244. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9245. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9246. taicpu(p).loadreg(1, NR_EAX);
  9247. taicpu(hp1).opcode := A_CDQ;
  9248. taicpu(hp1).clearop(1);
  9249. taicpu(hp1).clearop(0);
  9250. taicpu(hp1).ops:=0;
  9251. RemoveInstruction(hp2);
  9252. (*
  9253. {$ifdef x86_64}
  9254. end
  9255. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9256. { This code sequence does not get generated - however it might become useful
  9257. if and when 128-bit signed integer types make an appearance, so the code
  9258. is kept here for when it is eventually needed. [Kit] }
  9259. (
  9260. (
  9261. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9262. (
  9263. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9264. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9265. )
  9266. ) or
  9267. (
  9268. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9269. (
  9270. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9271. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9272. )
  9273. )
  9274. ) and
  9275. GetNextInstruction(hp1, hp2) and
  9276. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9277. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9278. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9279. begin
  9280. { Change:
  9281. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9282. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9283. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9284. To:
  9285. movq r/m,%rax <- Note the change in register
  9286. cqto
  9287. }
  9288. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9289. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9290. taicpu(p).loadreg(1, NR_RAX);
  9291. taicpu(hp1).opcode := A_CQO;
  9292. taicpu(hp1).clearop(1);
  9293. taicpu(hp1).clearop(0);
  9294. taicpu(hp1).ops:=0;
  9295. RemoveInstruction(hp2);
  9296. {$endif x86_64}
  9297. *)
  9298. end;
  9299. end;
  9300. {$ifdef x86_64}
  9301. end
  9302. else if (taicpu(p).opsize = S_L) and
  9303. (taicpu(p).oper[1]^.typ = top_reg) and
  9304. (
  9305. MatchInstruction(hp1, A_MOV,[]) and
  9306. (taicpu(hp1).opsize = S_L) and
  9307. (taicpu(hp1).oper[1]^.typ = top_reg)
  9308. ) and (
  9309. GetNextInstruction(hp1, hp2) and
  9310. (tai(hp2).typ=ait_instruction) and
  9311. (taicpu(hp2).opsize = S_Q) and
  9312. (
  9313. (
  9314. MatchInstruction(hp2, A_ADD,[]) and
  9315. (taicpu(hp2).opsize = S_Q) and
  9316. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9317. (
  9318. (
  9319. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9320. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9321. ) or (
  9322. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9323. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9324. )
  9325. )
  9326. ) or (
  9327. MatchInstruction(hp2, A_LEA,[]) and
  9328. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9329. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9330. (
  9331. (
  9332. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9333. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9334. ) or (
  9335. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9336. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9337. )
  9338. ) and (
  9339. (
  9340. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9341. ) or (
  9342. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9343. )
  9344. )
  9345. )
  9346. )
  9347. ) and (
  9348. GetNextInstruction(hp2, hp3) and
  9349. MatchInstruction(hp3, A_SHR,[]) and
  9350. (taicpu(hp3).opsize = S_Q) and
  9351. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9352. (taicpu(hp3).oper[0]^.val = 1) and
  9353. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9354. ) then
  9355. begin
  9356. { Change movl x, reg1d movl x, reg1d
  9357. movl y, reg2d movl y, reg2d
  9358. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9359. shrq $1, reg1q shrq $1, reg1q
  9360. ( reg1d and reg2d can be switched around in the first two instructions )
  9361. To movl x, reg1d
  9362. addl y, reg1d
  9363. rcrl $1, reg1d
  9364. This corresponds to the common expression (x + y) shr 1, where
  9365. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9366. smaller code, but won't account for x + y causing an overflow). [Kit]
  9367. }
  9368. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9369. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9370. { Change first MOV command to have the same register as the final output }
  9371. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9372. else
  9373. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9374. { Change second MOV command to an ADD command. This is easier than
  9375. converting the existing command because it means we don't have to
  9376. touch 'y', which might be a complicated reference, and also the
  9377. fact that the third command might either be ADD or LEA. [Kit] }
  9378. taicpu(hp1).opcode := A_ADD;
  9379. { Delete old ADD/LEA instruction }
  9380. RemoveInstruction(hp2);
  9381. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9382. taicpu(hp3).opcode := A_RCR;
  9383. taicpu(hp3).changeopsize(S_L);
  9384. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9385. {$endif x86_64}
  9386. end;
  9387. if FuncMov2Func(p, hp1) then
  9388. begin
  9389. Result := True;
  9390. Exit;
  9391. end;
  9392. end;
  9393. {$push}
  9394. {$q-}{$r-}
  9395. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9396. var
  9397. ThisReg: TRegister;
  9398. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9399. TargetSubReg: TSubRegister;
  9400. hp1, hp2: tai;
  9401. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9402. { Store list of found instructions so we don't have to call
  9403. GetNextInstructionUsingReg multiple times }
  9404. InstrList: array of taicpu;
  9405. InstrMax, Index: Integer;
  9406. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9407. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9408. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9409. WorkingValue: TCgInt;
  9410. PreMessage: string;
  9411. { Data flow analysis }
  9412. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9413. BitwiseOnly, OrXorUsed,
  9414. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9415. function CheckOverflowConditions: Boolean;
  9416. begin
  9417. Result := True;
  9418. if (TestValSignedMax > SignedUpperLimit) then
  9419. UpperSignedOverflow := True;
  9420. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9421. LowerSignedOverflow := True;
  9422. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9423. LowerUnsignedOverflow := True;
  9424. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9425. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9426. begin
  9427. { Absolute overflow }
  9428. Result := False;
  9429. Exit;
  9430. end;
  9431. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9432. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9433. ShiftDownOverflow := True;
  9434. if (TestValMin < 0) or (TestValMax < 0) then
  9435. begin
  9436. LowerUnsignedOverflow := True;
  9437. UpperUnsignedOverflow := True;
  9438. end;
  9439. end;
  9440. function AdjustInitialLoadAndSize: Boolean;
  9441. begin
  9442. Result := False;
  9443. if not p_removed then
  9444. begin
  9445. if TargetSize = MinSize then
  9446. begin
  9447. { Convert the input MOVZX to a MOV }
  9448. if (taicpu(p).oper[0]^.typ = top_reg) and
  9449. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9450. begin
  9451. { Or remove it completely! }
  9452. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9453. RemoveCurrentP(p);
  9454. p_removed := True;
  9455. end
  9456. else
  9457. begin
  9458. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9459. taicpu(p).opcode := A_MOV;
  9460. taicpu(p).oper[1]^.reg := ThisReg;
  9461. taicpu(p).opsize := TargetSize;
  9462. end;
  9463. Result := True;
  9464. end
  9465. else if TargetSize <> MaxSize then
  9466. begin
  9467. case MaxSize of
  9468. S_L:
  9469. if TargetSize = S_W then
  9470. begin
  9471. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9472. taicpu(p).opsize := S_BW;
  9473. taicpu(p).oper[1]^.reg := ThisReg;
  9474. Result := True;
  9475. end
  9476. else
  9477. InternalError(2020112341);
  9478. S_W:
  9479. if TargetSize = S_L then
  9480. begin
  9481. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9482. taicpu(p).opsize := S_BL;
  9483. taicpu(p).oper[1]^.reg := ThisReg;
  9484. Result := True;
  9485. end
  9486. else
  9487. InternalError(2020112342);
  9488. else
  9489. ;
  9490. end;
  9491. end
  9492. else if not hp1_removed and not RegInUse then
  9493. begin
  9494. { If we have something like:
  9495. movzbl (oper),%regd
  9496. add x, %regd
  9497. movzbl %regb, %regd
  9498. We can reduce the register size to the input of the final
  9499. movzbl instruction. Overflows won't have any effect.
  9500. }
  9501. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9502. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9503. begin
  9504. TargetSize := S_B;
  9505. setsubreg(ThisReg, R_SUBL);
  9506. Result := True;
  9507. end
  9508. else if (taicpu(p).opsize = S_WL) and
  9509. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9510. begin
  9511. TargetSize := S_W;
  9512. setsubreg(ThisReg, R_SUBW);
  9513. Result := True;
  9514. end;
  9515. if Result then
  9516. begin
  9517. { Convert the input MOVZX to a MOV }
  9518. if (taicpu(p).oper[0]^.typ = top_reg) and
  9519. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9520. begin
  9521. { Or remove it completely! }
  9522. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9523. RemoveCurrentP(p);
  9524. p_removed := True;
  9525. end
  9526. else
  9527. begin
  9528. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9529. taicpu(p).opcode := A_MOV;
  9530. taicpu(p).oper[1]^.reg := ThisReg;
  9531. taicpu(p).opsize := TargetSize;
  9532. end;
  9533. end;
  9534. end;
  9535. end;
  9536. end;
  9537. procedure AdjustFinalLoad;
  9538. begin
  9539. if not LowerUnsignedOverflow then
  9540. begin
  9541. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9542. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9543. begin
  9544. { Convert the output MOVZX to a MOV }
  9545. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9546. begin
  9547. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9548. if (MinSize = S_B) or
  9549. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9550. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9551. begin
  9552. { Remove it completely! }
  9553. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9554. { Be careful; if p = hp1 and p was also removed, p
  9555. will become a dangling pointer }
  9556. if p = hp1 then
  9557. begin
  9558. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9559. p_removed := True;
  9560. end
  9561. else
  9562. RemoveInstruction(hp1);
  9563. hp1_removed := True;
  9564. end;
  9565. end
  9566. else
  9567. begin
  9568. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9569. taicpu(hp1).opcode := A_MOV;
  9570. taicpu(hp1).oper[0]^.reg := ThisReg;
  9571. taicpu(hp1).opsize := TargetSize;
  9572. end;
  9573. end
  9574. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9575. begin
  9576. { Need to change the size of the output }
  9577. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9578. taicpu(hp1).oper[0]^.reg := ThisReg;
  9579. taicpu(hp1).opsize := S_BL;
  9580. end;
  9581. end;
  9582. end;
  9583. function CompressInstructions: Boolean;
  9584. var
  9585. LocalIndex: Integer;
  9586. begin
  9587. Result := False;
  9588. { The objective here is to try to find a combination that
  9589. removes one of the MOV/Z instructions. }
  9590. if (
  9591. (taicpu(p).oper[0]^.typ <> top_reg) or
  9592. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9593. ) and
  9594. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9595. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9596. begin
  9597. { Make a preference to remove the second MOVZX instruction }
  9598. case taicpu(hp1).opsize of
  9599. S_BL, S_WL:
  9600. begin
  9601. TargetSize := S_L;
  9602. TargetSubReg := R_SUBD;
  9603. end;
  9604. S_BW:
  9605. begin
  9606. TargetSize := S_W;
  9607. TargetSubReg := R_SUBW;
  9608. end;
  9609. else
  9610. InternalError(2020112302);
  9611. end;
  9612. end
  9613. else
  9614. begin
  9615. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9616. begin
  9617. { Exceeded lower bound but not upper bound }
  9618. TargetSize := MaxSize;
  9619. end
  9620. else if not LowerUnsignedOverflow then
  9621. begin
  9622. { Size didn't exceed lower bound }
  9623. TargetSize := MinSize;
  9624. end
  9625. else
  9626. Exit;
  9627. end;
  9628. case TargetSize of
  9629. S_B:
  9630. TargetSubReg := R_SUBL;
  9631. S_W:
  9632. TargetSubReg := R_SUBW;
  9633. S_L:
  9634. TargetSubReg := R_SUBD;
  9635. else
  9636. InternalError(2020112350);
  9637. end;
  9638. { Update the register to its new size }
  9639. setsubreg(ThisReg, TargetSubReg);
  9640. RegInUse := False;
  9641. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9642. begin
  9643. { Check to see if the active register is used afterwards;
  9644. if not, we can change it and make a saving. }
  9645. TransferUsedRegs(TmpUsedRegs);
  9646. { The target register may be marked as in use to cross
  9647. a jump to a distant label, so exclude it }
  9648. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9649. hp2 := p;
  9650. repeat
  9651. { Explicitly check for the excluded register (don't include the first
  9652. instruction as it may be reading from here }
  9653. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9654. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9655. begin
  9656. RegInUse := True;
  9657. Break;
  9658. end;
  9659. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9660. if not GetNextInstruction(hp2, hp2) then
  9661. InternalError(2020112340);
  9662. until (hp2 = hp1);
  9663. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9664. { We might still be able to get away with this }
  9665. RegInUse := not
  9666. (
  9667. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9668. (hp2.typ = ait_instruction) and
  9669. (
  9670. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9671. instruction that doesn't actually contain ThisReg }
  9672. (cs_opt_level3 in current_settings.optimizerswitches) or
  9673. RegInInstruction(ThisReg, hp2)
  9674. ) and
  9675. RegLoadedWithNewValue(ThisReg, hp2)
  9676. );
  9677. if not RegInUse then
  9678. begin
  9679. { Force the register size to the same as this instruction so it can be removed}
  9680. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9681. begin
  9682. TargetSize := S_L;
  9683. TargetSubReg := R_SUBD;
  9684. end
  9685. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9686. begin
  9687. TargetSize := S_W;
  9688. TargetSubReg := R_SUBW;
  9689. end;
  9690. ThisReg := taicpu(hp1).oper[1]^.reg;
  9691. setsubreg(ThisReg, TargetSubReg);
  9692. RegChanged := True;
  9693. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9694. TransferUsedRegs(TmpUsedRegs);
  9695. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9696. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9697. if p = hp1 then
  9698. begin
  9699. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9700. p_removed := True;
  9701. end
  9702. else
  9703. RemoveInstruction(hp1);
  9704. hp1_removed := True;
  9705. { Instruction will become "mov %reg,%reg" }
  9706. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9707. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9708. begin
  9709. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9710. RemoveCurrentP(p);
  9711. p_removed := True;
  9712. end
  9713. else
  9714. taicpu(p).oper[1]^.reg := ThisReg;
  9715. Result := True;
  9716. end
  9717. else
  9718. begin
  9719. if TargetSize <> MaxSize then
  9720. begin
  9721. { Since the register is in use, we have to force it to
  9722. MaxSize otherwise part of it may become undefined later on }
  9723. TargetSize := MaxSize;
  9724. case TargetSize of
  9725. S_B:
  9726. TargetSubReg := R_SUBL;
  9727. S_W:
  9728. TargetSubReg := R_SUBW;
  9729. S_L:
  9730. TargetSubReg := R_SUBD;
  9731. else
  9732. InternalError(2020112351);
  9733. end;
  9734. setsubreg(ThisReg, TargetSubReg);
  9735. end;
  9736. AdjustFinalLoad;
  9737. end;
  9738. end
  9739. else
  9740. AdjustFinalLoad;
  9741. Result := AdjustInitialLoadAndSize or Result;
  9742. { Now go through every instruction we found and change the
  9743. size. If TargetSize = MaxSize, then almost no changes are
  9744. needed and Result can remain False if it hasn't been set
  9745. yet.
  9746. If RegChanged is True, then the register requires changing
  9747. and so the point about TargetSize = MaxSize doesn't apply. }
  9748. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9749. begin
  9750. for LocalIndex := 0 to InstrMax do
  9751. begin
  9752. { If p_removed is true, then the original MOV/Z was removed
  9753. and removing the AND instruction may not be safe if it
  9754. appears first }
  9755. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9756. InternalError(2020112310);
  9757. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9758. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9759. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9760. InstrList[LocalIndex].opsize := TargetSize;
  9761. end;
  9762. Result := True;
  9763. end;
  9764. end;
  9765. begin
  9766. Result := False;
  9767. p_removed := False;
  9768. hp1_removed := False;
  9769. ThisReg := taicpu(p).oper[1]^.reg;
  9770. { Check for:
  9771. movs/z ###,%ecx (or %cx or %rcx)
  9772. ...
  9773. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9774. (dealloc %ecx)
  9775. Change to:
  9776. mov ###,%cl (if ### = %cl, then remove completely)
  9777. ...
  9778. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9779. }
  9780. if (getsupreg(ThisReg) = RS_ECX) and
  9781. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9782. (hp1.typ = ait_instruction) and
  9783. (
  9784. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9785. instruction that doesn't actually contain ECX }
  9786. (cs_opt_level3 in current_settings.optimizerswitches) or
  9787. RegInInstruction(NR_ECX, hp1) or
  9788. (
  9789. { It's common for the shift/rotate's read/write register to be
  9790. initialised in between, so under -O2 and under, search ahead
  9791. one more instruction
  9792. }
  9793. GetNextInstruction(hp1, hp1) and
  9794. (hp1.typ = ait_instruction) and
  9795. RegInInstruction(NR_ECX, hp1)
  9796. )
  9797. ) and
  9798. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9799. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9800. begin
  9801. TransferUsedRegs(TmpUsedRegs);
  9802. hp2 := p;
  9803. repeat
  9804. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9805. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9806. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9807. begin
  9808. case taicpu(p).opsize of
  9809. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9810. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9811. begin
  9812. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9813. RemoveCurrentP(p);
  9814. end
  9815. else
  9816. begin
  9817. taicpu(p).opcode := A_MOV;
  9818. taicpu(p).opsize := S_B;
  9819. taicpu(p).oper[1]^.reg := NR_CL;
  9820. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9821. end;
  9822. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9823. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9824. begin
  9825. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9826. RemoveCurrentP(p);
  9827. end
  9828. else
  9829. begin
  9830. taicpu(p).opcode := A_MOV;
  9831. taicpu(p).opsize := S_W;
  9832. taicpu(p).oper[1]^.reg := NR_CX;
  9833. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9834. end;
  9835. {$ifdef x86_64}
  9836. S_LQ:
  9837. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9838. begin
  9839. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9840. RemoveCurrentP(p);
  9841. end
  9842. else
  9843. begin
  9844. taicpu(p).opcode := A_MOV;
  9845. taicpu(p).opsize := S_L;
  9846. taicpu(p).oper[1]^.reg := NR_ECX;
  9847. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9848. end;
  9849. {$endif x86_64}
  9850. else
  9851. InternalError(2021120401);
  9852. end;
  9853. Result := True;
  9854. Exit;
  9855. end;
  9856. end;
  9857. { This is anything but quick! }
  9858. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9859. Exit;
  9860. SetLength(InstrList, 0);
  9861. InstrMax := -1;
  9862. case taicpu(p).opsize of
  9863. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9864. begin
  9865. {$if defined(i386) or defined(i8086)}
  9866. { If the target size is 8-bit, make sure we can actually encode it }
  9867. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9868. Exit;
  9869. {$endif i386 or i8086}
  9870. LowerLimit := $FF;
  9871. SignedLowerLimit := $7F;
  9872. SignedLowerLimitBottom := -128;
  9873. MinSize := S_B;
  9874. if taicpu(p).opsize = S_BW then
  9875. begin
  9876. MaxSize := S_W;
  9877. UpperLimit := $FFFF;
  9878. SignedUpperLimit := $7FFF;
  9879. SignedUpperLimitBottom := -32768;
  9880. end
  9881. else
  9882. begin
  9883. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9884. MaxSize := S_L;
  9885. UpperLimit := $FFFFFFFF;
  9886. SignedUpperLimit := $7FFFFFFF;
  9887. SignedUpperLimitBottom := -2147483648;
  9888. end;
  9889. end;
  9890. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9891. begin
  9892. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9893. LowerLimit := $FFFF;
  9894. SignedLowerLimit := $7FFF;
  9895. SignedLowerLimitBottom := -32768;
  9896. UpperLimit := $FFFFFFFF;
  9897. SignedUpperLimit := $7FFFFFFF;
  9898. SignedUpperLimitBottom := -2147483648;
  9899. MinSize := S_W;
  9900. MaxSize := S_L;
  9901. end;
  9902. {$ifdef x86_64}
  9903. S_LQ:
  9904. begin
  9905. { Both the lower and upper limits are set to 32-bit. If a limit
  9906. is breached, then optimisation is impossible }
  9907. LowerLimit := $FFFFFFFF;
  9908. SignedLowerLimit := $7FFFFFFF;
  9909. SignedLowerLimitBottom := -2147483648;
  9910. UpperLimit := $FFFFFFFF;
  9911. SignedUpperLimit := $7FFFFFFF;
  9912. SignedUpperLimitBottom := -2147483648;
  9913. MinSize := S_L;
  9914. MaxSize := S_L;
  9915. end;
  9916. {$endif x86_64}
  9917. else
  9918. InternalError(2020112301);
  9919. end;
  9920. TestValMin := 0;
  9921. TestValMax := LowerLimit;
  9922. TestValSignedMax := SignedLowerLimit;
  9923. TryShiftDownLimit := LowerLimit;
  9924. TryShiftDown := S_NO;
  9925. ShiftDownOverflow := False;
  9926. RegChanged := False;
  9927. BitwiseOnly := True;
  9928. OrXorUsed := False;
  9929. UpperSignedOverflow := False;
  9930. LowerSignedOverflow := False;
  9931. UpperUnsignedOverflow := False;
  9932. LowerUnsignedOverflow := False;
  9933. hp1 := p;
  9934. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9935. (hp1.typ = ait_instruction) and
  9936. (
  9937. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9938. instruction that doesn't actually contain ThisReg }
  9939. (cs_opt_level3 in current_settings.optimizerswitches) or
  9940. { This allows this Movx optimisation to work through the SETcc instructions
  9941. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9942. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9943. skip over these SETcc instructions). }
  9944. (taicpu(hp1).opcode = A_SETcc) or
  9945. RegInInstruction(ThisReg, hp1)
  9946. ) do
  9947. begin
  9948. case taicpu(hp1).opcode of
  9949. A_INC,A_DEC:
  9950. begin
  9951. { Has to be an exact match on the register }
  9952. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9953. Break;
  9954. if taicpu(hp1).opcode = A_INC then
  9955. begin
  9956. Inc(TestValMin);
  9957. Inc(TestValMax);
  9958. Inc(TestValSignedMax);
  9959. end
  9960. else
  9961. begin
  9962. Dec(TestValMin);
  9963. Dec(TestValMax);
  9964. Dec(TestValSignedMax);
  9965. end;
  9966. end;
  9967. A_TEST, A_CMP:
  9968. begin
  9969. if (
  9970. { Too high a risk of non-linear behaviour that breaks DFA
  9971. here, unless it's cmp $0,%reg, which is equivalent to
  9972. test %reg,%reg }
  9973. OrXorUsed and
  9974. (taicpu(hp1).opcode = A_CMP) and
  9975. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9976. ) or
  9977. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9978. { Has to be an exact match on the register }
  9979. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9980. (
  9981. { Permit "test %reg,%reg" }
  9982. (taicpu(hp1).opcode = A_TEST) and
  9983. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9984. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9985. ) or
  9986. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9987. { Make sure the comparison value is not smaller than the
  9988. smallest allowed signed value for the minimum size (e.g.
  9989. -128 for 8-bit) }
  9990. not (
  9991. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9992. { Is it in the negative range? }
  9993. (
  9994. (taicpu(hp1).oper[0]^.val < 0) and
  9995. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9996. )
  9997. ) then
  9998. Break;
  9999. { Check to see if the active register is used afterwards }
  10000. TransferUsedRegs(TmpUsedRegs);
  10001. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10002. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10003. begin
  10004. { Make sure the comparison or any previous instructions
  10005. hasn't pushed the test values outside of the range of
  10006. MinSize }
  10007. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10008. begin
  10009. { Exceeded lower bound but not upper bound }
  10010. Exit;
  10011. end
  10012. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10013. begin
  10014. { Size didn't exceed lower bound }
  10015. TargetSize := MinSize;
  10016. end
  10017. else
  10018. Break;
  10019. case TargetSize of
  10020. S_B:
  10021. TargetSubReg := R_SUBL;
  10022. S_W:
  10023. TargetSubReg := R_SUBW;
  10024. S_L:
  10025. TargetSubReg := R_SUBD;
  10026. else
  10027. InternalError(2021051002);
  10028. end;
  10029. if TargetSize <> MaxSize then
  10030. begin
  10031. { Update the register to its new size }
  10032. setsubreg(ThisReg, TargetSubReg);
  10033. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10034. taicpu(hp1).oper[1]^.reg := ThisReg;
  10035. taicpu(hp1).opsize := TargetSize;
  10036. { Convert the input MOVZX to a MOV if necessary }
  10037. AdjustInitialLoadAndSize;
  10038. if (InstrMax >= 0) then
  10039. begin
  10040. for Index := 0 to InstrMax do
  10041. begin
  10042. { If p_removed is true, then the original MOV/Z was removed
  10043. and removing the AND instruction may not be safe if it
  10044. appears first }
  10045. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10046. InternalError(2020112311);
  10047. if InstrList[Index].oper[0]^.typ = top_reg then
  10048. InstrList[Index].oper[0]^.reg := ThisReg;
  10049. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10050. InstrList[Index].opsize := MinSize;
  10051. end;
  10052. end;
  10053. Result := True;
  10054. end;
  10055. Exit;
  10056. end;
  10057. end;
  10058. A_SETcc:
  10059. begin
  10060. { This allows this Movx optimisation to work through the SETcc instructions
  10061. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10062. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10063. skip over these SETcc instructions). }
  10064. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10065. { Of course, break out if the current register is used }
  10066. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10067. Break
  10068. else
  10069. { We must use Continue so the instruction doesn't get added
  10070. to InstrList }
  10071. Continue;
  10072. end;
  10073. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10074. begin
  10075. if
  10076. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10077. { Has to be an exact match on the register }
  10078. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10079. (
  10080. (
  10081. (taicpu(hp1).oper[0]^.typ = top_const) and
  10082. (
  10083. (
  10084. (taicpu(hp1).opcode = A_SHL) and
  10085. (
  10086. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10087. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10088. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10089. )
  10090. ) or (
  10091. (taicpu(hp1).opcode <> A_SHL) and
  10092. (
  10093. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10094. { Is it in the negative range? }
  10095. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10096. )
  10097. )
  10098. )
  10099. ) or (
  10100. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10101. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10102. )
  10103. ) then
  10104. Break;
  10105. { Only process OR and XOR if there are only bitwise operations,
  10106. since otherwise they can too easily fool the data flow
  10107. analysis (they can cause non-linear behaviour) }
  10108. case taicpu(hp1).opcode of
  10109. A_ADD:
  10110. begin
  10111. if OrXorUsed then
  10112. { Too high a risk of non-linear behaviour that breaks DFA here }
  10113. Break
  10114. else
  10115. BitwiseOnly := False;
  10116. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10117. begin
  10118. TestValMin := TestValMin * 2;
  10119. TestValMax := TestValMax * 2;
  10120. TestValSignedMax := TestValSignedMax * 2;
  10121. end
  10122. else
  10123. begin
  10124. WorkingValue := taicpu(hp1).oper[0]^.val;
  10125. TestValMin := TestValMin + WorkingValue;
  10126. TestValMax := TestValMax + WorkingValue;
  10127. TestValSignedMax := TestValSignedMax + WorkingValue;
  10128. end;
  10129. end;
  10130. A_SUB:
  10131. begin
  10132. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10133. begin
  10134. TestValMin := 0;
  10135. TestValMax := 0;
  10136. TestValSignedMax := 0;
  10137. end
  10138. else
  10139. begin
  10140. if OrXorUsed then
  10141. { Too high a risk of non-linear behaviour that breaks DFA here }
  10142. Break
  10143. else
  10144. BitwiseOnly := False;
  10145. WorkingValue := taicpu(hp1).oper[0]^.val;
  10146. TestValMin := TestValMin - WorkingValue;
  10147. TestValMax := TestValMax - WorkingValue;
  10148. TestValSignedMax := TestValSignedMax - WorkingValue;
  10149. end;
  10150. end;
  10151. A_AND:
  10152. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10153. begin
  10154. { we might be able to go smaller if AND appears first }
  10155. if InstrMax = -1 then
  10156. case MinSize of
  10157. S_B:
  10158. ;
  10159. S_W:
  10160. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10161. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10162. begin
  10163. TryShiftDown := S_B;
  10164. TryShiftDownLimit := $FF;
  10165. end;
  10166. S_L:
  10167. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10168. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10169. begin
  10170. TryShiftDown := S_B;
  10171. TryShiftDownLimit := $FF;
  10172. end
  10173. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10174. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10175. begin
  10176. TryShiftDown := S_W;
  10177. TryShiftDownLimit := $FFFF;
  10178. end;
  10179. else
  10180. InternalError(2020112320);
  10181. end;
  10182. WorkingValue := taicpu(hp1).oper[0]^.val;
  10183. TestValMin := TestValMin and WorkingValue;
  10184. TestValMax := TestValMax and WorkingValue;
  10185. TestValSignedMax := TestValSignedMax and WorkingValue;
  10186. end;
  10187. A_OR:
  10188. begin
  10189. if not BitwiseOnly then
  10190. Break;
  10191. OrXorUsed := True;
  10192. WorkingValue := taicpu(hp1).oper[0]^.val;
  10193. TestValMin := TestValMin or WorkingValue;
  10194. TestValMax := TestValMax or WorkingValue;
  10195. TestValSignedMax := TestValSignedMax or WorkingValue;
  10196. end;
  10197. A_XOR:
  10198. begin
  10199. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10200. begin
  10201. TestValMin := 0;
  10202. TestValMax := 0;
  10203. TestValSignedMax := 0;
  10204. end
  10205. else
  10206. begin
  10207. if not BitwiseOnly then
  10208. Break;
  10209. OrXorUsed := True;
  10210. WorkingValue := taicpu(hp1).oper[0]^.val;
  10211. TestValMin := TestValMin xor WorkingValue;
  10212. TestValMax := TestValMax xor WorkingValue;
  10213. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10214. end;
  10215. end;
  10216. A_SHL:
  10217. begin
  10218. BitwiseOnly := False;
  10219. WorkingValue := taicpu(hp1).oper[0]^.val;
  10220. TestValMin := TestValMin shl WorkingValue;
  10221. TestValMax := TestValMax shl WorkingValue;
  10222. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10223. end;
  10224. A_SHR,
  10225. { The first instruction was MOVZX, so the value won't be negative }
  10226. A_SAR:
  10227. begin
  10228. if InstrMax <> -1 then
  10229. BitwiseOnly := False
  10230. else
  10231. { we might be able to go smaller if SHR appears first }
  10232. case MinSize of
  10233. S_B:
  10234. ;
  10235. S_W:
  10236. if (taicpu(hp1).oper[0]^.val >= 8) then
  10237. begin
  10238. TryShiftDown := S_B;
  10239. TryShiftDownLimit := $FF;
  10240. TryShiftDownSignedLimit := $7F;
  10241. TryShiftDownSignedLimitLower := -128;
  10242. end;
  10243. S_L:
  10244. if (taicpu(hp1).oper[0]^.val >= 24) then
  10245. begin
  10246. TryShiftDown := S_B;
  10247. TryShiftDownLimit := $FF;
  10248. TryShiftDownSignedLimit := $7F;
  10249. TryShiftDownSignedLimitLower := -128;
  10250. end
  10251. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10252. begin
  10253. TryShiftDown := S_W;
  10254. TryShiftDownLimit := $FFFF;
  10255. TryShiftDownSignedLimit := $7FFF;
  10256. TryShiftDownSignedLimitLower := -32768;
  10257. end;
  10258. else
  10259. InternalError(2020112321);
  10260. end;
  10261. WorkingValue := taicpu(hp1).oper[0]^.val;
  10262. if taicpu(hp1).opcode = A_SAR then
  10263. begin
  10264. TestValMin := SarInt64(TestValMin, WorkingValue);
  10265. TestValMax := SarInt64(TestValMax, WorkingValue);
  10266. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10267. end
  10268. else
  10269. begin
  10270. TestValMin := TestValMin shr WorkingValue;
  10271. TestValMax := TestValMax shr WorkingValue;
  10272. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10273. end;
  10274. end;
  10275. else
  10276. InternalError(2020112303);
  10277. end;
  10278. end;
  10279. (*
  10280. A_IMUL:
  10281. case taicpu(hp1).ops of
  10282. 2:
  10283. begin
  10284. if not MatchOpType(hp1, top_reg, top_reg) or
  10285. { Has to be an exact match on the register }
  10286. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10287. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10288. Break;
  10289. TestValMin := TestValMin * TestValMin;
  10290. TestValMax := TestValMax * TestValMax;
  10291. TestValSignedMax := TestValSignedMax * TestValMax;
  10292. end;
  10293. 3:
  10294. begin
  10295. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10296. { Has to be an exact match on the register }
  10297. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10298. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10299. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10300. { Is it in the negative range? }
  10301. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10302. Break;
  10303. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10304. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10305. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10306. end;
  10307. else
  10308. Break;
  10309. end;
  10310. A_IDIV:
  10311. case taicpu(hp1).ops of
  10312. 3:
  10313. begin
  10314. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10315. { Has to be an exact match on the register }
  10316. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10317. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10318. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10319. { Is it in the negative range? }
  10320. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10321. Break;
  10322. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10323. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10324. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10325. end;
  10326. else
  10327. Break;
  10328. end;
  10329. *)
  10330. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10331. begin
  10332. { If there are no instructions in between, then we might be able to make a saving }
  10333. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10334. Break;
  10335. { We have something like:
  10336. movzbw %dl,%dx
  10337. ...
  10338. movswl %dx,%edx
  10339. Change the latter to a zero-extension then enter the
  10340. A_MOVZX case branch.
  10341. }
  10342. {$ifdef x86_64}
  10343. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10344. begin
  10345. { this becomes a zero extension from 32-bit to 64-bit, but
  10346. the upper 32 bits are already zero, so just delete the
  10347. instruction }
  10348. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10349. RemoveInstruction(hp1);
  10350. Result := True;
  10351. Exit;
  10352. end
  10353. else
  10354. {$endif x86_64}
  10355. begin
  10356. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10357. taicpu(hp1).opcode := A_MOVZX;
  10358. {$ifdef x86_64}
  10359. case taicpu(hp1).opsize of
  10360. S_BQ:
  10361. begin
  10362. taicpu(hp1).opsize := S_BL;
  10363. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10364. end;
  10365. S_WQ:
  10366. begin
  10367. taicpu(hp1).opsize := S_WL;
  10368. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10369. end;
  10370. S_LQ:
  10371. begin
  10372. taicpu(hp1).opcode := A_MOV;
  10373. taicpu(hp1).opsize := S_L;
  10374. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10375. { In this instance, we need to break out because the
  10376. instruction is no longer MOVZX or MOVSXD }
  10377. Result := True;
  10378. Exit;
  10379. end;
  10380. else
  10381. ;
  10382. end;
  10383. {$endif x86_64}
  10384. Result := CompressInstructions;
  10385. Exit;
  10386. end;
  10387. end;
  10388. A_MOVZX:
  10389. begin
  10390. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10391. Break;
  10392. if (InstrMax = -1) then
  10393. begin
  10394. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10395. begin
  10396. { Optimise around i40003 }
  10397. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10398. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10399. {$ifndef x86_64}
  10400. and (
  10401. (taicpu(p).oper[0]^.typ <> top_reg) or
  10402. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10403. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10404. )
  10405. {$endif not x86_64}
  10406. then
  10407. begin
  10408. if (taicpu(p).oper[0]^.typ = top_reg) then
  10409. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10410. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10411. taicpu(p).opsize := S_BL;
  10412. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10413. RemoveInstruction(hp1);
  10414. Result := True;
  10415. Exit;
  10416. end;
  10417. end
  10418. else
  10419. begin
  10420. { Will return false if the second parameter isn't ThisReg
  10421. (can happen on -O2 and under) }
  10422. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10423. begin
  10424. { The two MOVZX instructions are adjacent, so remove the first one }
  10425. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10426. RemoveCurrentP(p);
  10427. Result := True;
  10428. Exit;
  10429. end;
  10430. Break;
  10431. end;
  10432. end;
  10433. Result := CompressInstructions;
  10434. Exit;
  10435. end;
  10436. else
  10437. { This includes ADC, SBB and IDIV }
  10438. Break;
  10439. end;
  10440. if not CheckOverflowConditions then
  10441. Break;
  10442. { Contains highest index (so instruction count - 1) }
  10443. Inc(InstrMax);
  10444. if InstrMax > High(InstrList) then
  10445. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10446. InstrList[InstrMax] := taicpu(hp1);
  10447. end;
  10448. end;
  10449. {$pop}
  10450. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10451. var
  10452. hp1 : tai;
  10453. begin
  10454. Result:=false;
  10455. if (taicpu(p).ops >= 2) and
  10456. ((taicpu(p).oper[0]^.typ = top_const) or
  10457. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10458. (taicpu(p).oper[1]^.typ = top_reg) and
  10459. ((taicpu(p).ops = 2) or
  10460. ((taicpu(p).oper[2]^.typ = top_reg) and
  10461. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10462. GetLastInstruction(p,hp1) and
  10463. MatchInstruction(hp1,A_MOV,[]) and
  10464. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10465. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10466. begin
  10467. TransferUsedRegs(TmpUsedRegs);
  10468. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10469. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10470. { change
  10471. mov reg1,reg2
  10472. imul y,reg2 to imul y,reg1,reg2 }
  10473. begin
  10474. taicpu(p).ops := 3;
  10475. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10476. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10477. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10478. RemoveInstruction(hp1);
  10479. result:=true;
  10480. end;
  10481. end;
  10482. end;
  10483. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10484. var
  10485. ThisLabel: TAsmLabel;
  10486. begin
  10487. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10488. ThisLabel.decrefs;
  10489. taicpu(p).condition := C_None;
  10490. taicpu(p).opcode := A_RET;
  10491. taicpu(p).is_jmp := false;
  10492. taicpu(p).ops := taicpu(ret_p).ops;
  10493. case taicpu(ret_p).ops of
  10494. 0:
  10495. taicpu(p).clearop(0);
  10496. 1:
  10497. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10498. else
  10499. internalerror(2016041301);
  10500. end;
  10501. { If the original label is now dead, it might turn out that the label
  10502. immediately follows p. As a result, everything beyond it, which will
  10503. be just some final register configuration and a RET instruction, is
  10504. now dead code. [Kit] }
  10505. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10506. running RemoveDeadCodeAfterJump for each RET instruction, because
  10507. this optimisation rarely happens and most RETs appear at the end of
  10508. routines where there is nothing that can be stripped. [Kit] }
  10509. if not ThisLabel.is_used then
  10510. RemoveDeadCodeAfterJump(p);
  10511. end;
  10512. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10513. var
  10514. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10515. Unconditional, PotentialModified: Boolean;
  10516. OperPtr: POper;
  10517. NewRef: TReference;
  10518. InstrList: array of taicpu;
  10519. InstrMax, Index: Integer;
  10520. const
  10521. {$ifdef DEBUG_AOPTCPU}
  10522. SNoFlags: shortstring = ' so the flags aren''t modified';
  10523. {$else DEBUG_AOPTCPU}
  10524. SNoFlags = '';
  10525. {$endif DEBUG_AOPTCPU}
  10526. begin
  10527. Result:=false;
  10528. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10529. begin
  10530. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10531. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10532. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10533. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10534. GetNextInstruction(hp1, hp2) and
  10535. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10536. { Change from: To:
  10537. set(C) %reg j(~C) label
  10538. test %reg,%reg/cmp $0,%reg
  10539. je label
  10540. set(C) %reg j(C) label
  10541. test %reg,%reg/cmp $0,%reg
  10542. jne label
  10543. (Also do something similar with sete/setne instead of je/jne)
  10544. }
  10545. begin
  10546. { Before we do anything else, we need to check the instructions
  10547. in between SETcc and TEST to make sure they don't modify the
  10548. FLAGS register - if -O2 or under, there won't be any
  10549. instructions between SET and TEST }
  10550. TransferUsedRegs(TmpUsedRegs);
  10551. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10552. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10553. begin
  10554. next := p;
  10555. SetLength(InstrList, 0);
  10556. InstrMax := -1;
  10557. PotentialModified := False;
  10558. { Make a note of every instruction that modifies the FLAGS
  10559. register }
  10560. while GetNextInstruction(next, next) and (next <> hp1) do
  10561. begin
  10562. if next.typ <> ait_instruction then
  10563. { GetNextInstructionUsingReg should have returned False }
  10564. InternalError(2021051701);
  10565. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10566. begin
  10567. case taicpu(next).opcode of
  10568. A_SETcc,
  10569. A_CMOVcc,
  10570. A_Jcc:
  10571. begin
  10572. if PotentialModified then
  10573. { Not safe because the flags were modified earlier }
  10574. Exit
  10575. else
  10576. { Condition is the same as the initial SETcc, so this is safe
  10577. (don't add to instruction list though) }
  10578. Continue;
  10579. end;
  10580. A_ADD:
  10581. begin
  10582. if (taicpu(next).opsize = S_B) or
  10583. { LEA doesn't support 8-bit operands }
  10584. (taicpu(next).oper[1]^.typ <> top_reg) or
  10585. { Must write to a register }
  10586. (taicpu(next).oper[0]^.typ = top_ref) then
  10587. { Require a constant or a register }
  10588. Exit;
  10589. PotentialModified := True;
  10590. end;
  10591. A_SUB:
  10592. begin
  10593. if (taicpu(next).opsize = S_B) or
  10594. { LEA doesn't support 8-bit operands }
  10595. (taicpu(next).oper[1]^.typ <> top_reg) or
  10596. { Must write to a register }
  10597. (taicpu(next).oper[0]^.typ <> top_const) or
  10598. (taicpu(next).oper[0]^.val = $80000000) then
  10599. { Can't subtract a register with LEA - also
  10600. check that the value isn't -2^31, as this
  10601. can't be negated }
  10602. Exit;
  10603. PotentialModified := True;
  10604. end;
  10605. A_SAL,
  10606. A_SHL:
  10607. begin
  10608. if (taicpu(next).opsize = S_B) or
  10609. { LEA doesn't support 8-bit operands }
  10610. (taicpu(next).oper[1]^.typ <> top_reg) or
  10611. { Must write to a register }
  10612. (taicpu(next).oper[0]^.typ <> top_const) or
  10613. (taicpu(next).oper[0]^.val < 0) or
  10614. (taicpu(next).oper[0]^.val > 3) then
  10615. Exit;
  10616. PotentialModified := True;
  10617. end;
  10618. A_IMUL:
  10619. begin
  10620. if (taicpu(next).ops <> 3) or
  10621. (taicpu(next).oper[1]^.typ <> top_reg) or
  10622. { Must write to a register }
  10623. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10624. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10625. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10626. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10627. Exit
  10628. else
  10629. PotentialModified := True;
  10630. end;
  10631. else
  10632. { Don't know how to change this, so abort }
  10633. Exit;
  10634. end;
  10635. { Contains highest index (so instruction count - 1) }
  10636. Inc(InstrMax);
  10637. if InstrMax > High(InstrList) then
  10638. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10639. InstrList[InstrMax] := taicpu(next);
  10640. end;
  10641. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10642. end;
  10643. if not Assigned(next) or (next <> hp1) then
  10644. { It should be equal to hp1 }
  10645. InternalError(2021051702);
  10646. { Cycle through each instruction and check to see if we can
  10647. change them to versions that don't modify the flags }
  10648. if (InstrMax >= 0) then
  10649. begin
  10650. for Index := 0 to InstrMax do
  10651. case InstrList[Index].opcode of
  10652. A_ADD:
  10653. begin
  10654. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10655. InstrList[Index].opcode := A_LEA;
  10656. reference_reset(NewRef, 1, []);
  10657. NewRef.base := InstrList[Index].oper[1]^.reg;
  10658. if InstrList[Index].oper[0]^.typ = top_reg then
  10659. begin
  10660. NewRef.index := InstrList[Index].oper[0]^.reg;
  10661. NewRef.scalefactor := 1;
  10662. end
  10663. else
  10664. NewRef.offset := InstrList[Index].oper[0]^.val;
  10665. InstrList[Index].loadref(0, NewRef);
  10666. end;
  10667. A_SUB:
  10668. begin
  10669. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10670. InstrList[Index].opcode := A_LEA;
  10671. reference_reset(NewRef, 1, []);
  10672. NewRef.base := InstrList[Index].oper[1]^.reg;
  10673. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10674. InstrList[Index].loadref(0, NewRef);
  10675. end;
  10676. A_SHL,
  10677. A_SAL:
  10678. begin
  10679. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10680. InstrList[Index].opcode := A_LEA;
  10681. reference_reset(NewRef, 1, []);
  10682. NewRef.index := InstrList[Index].oper[1]^.reg;
  10683. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10684. InstrList[Index].loadref(0, NewRef);
  10685. end;
  10686. A_IMUL:
  10687. begin
  10688. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10689. InstrList[Index].opcode := A_LEA;
  10690. reference_reset(NewRef, 1, []);
  10691. NewRef.index := InstrList[Index].oper[1]^.reg;
  10692. case InstrList[Index].oper[0]^.val of
  10693. 2, 4, 8:
  10694. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10695. else {3, 5 and 9}
  10696. begin
  10697. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10698. NewRef.base := InstrList[Index].oper[1]^.reg;
  10699. end;
  10700. end;
  10701. InstrList[Index].loadref(0, NewRef);
  10702. end;
  10703. else
  10704. InternalError(2021051710);
  10705. end;
  10706. end;
  10707. { Mark the FLAGS register as used across this whole block }
  10708. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10709. end;
  10710. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10711. JumpC := taicpu(hp2).condition;
  10712. Unconditional := False;
  10713. if conditions_equal(JumpC, C_E) then
  10714. SetC := inverse_cond(taicpu(p).condition)
  10715. else if conditions_equal(JumpC, C_NE) then
  10716. SetC := taicpu(p).condition
  10717. else
  10718. { We've got something weird here (and inefficent) }
  10719. begin
  10720. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10721. SetC := C_NONE;
  10722. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10723. if condition_in(C_AE, JumpC) then
  10724. Unconditional := True
  10725. else
  10726. { Not sure what to do with this jump - drop out }
  10727. Exit;
  10728. end;
  10729. RemoveInstruction(hp1);
  10730. if Unconditional then
  10731. MakeUnconditional(taicpu(hp2))
  10732. else
  10733. begin
  10734. if SetC = C_NONE then
  10735. InternalError(2018061402);
  10736. taicpu(hp2).SetCondition(SetC);
  10737. end;
  10738. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10739. TmpUsedRegs }
  10740. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10741. begin
  10742. RemoveCurrentp(p, hp2);
  10743. if taicpu(hp2).opcode = A_SETcc then
  10744. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10745. else
  10746. begin
  10747. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10748. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10749. Include(OptsToCheck, aoc_DoPass2JccOpts);
  10750. end;
  10751. end
  10752. else
  10753. if taicpu(hp2).opcode = A_SETcc then
  10754. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10755. else
  10756. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10757. Result := True;
  10758. end
  10759. else if
  10760. { Make sure the instructions are adjacent }
  10761. (
  10762. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10763. GetNextInstruction(p, hp1)
  10764. ) and
  10765. MatchInstruction(hp1, A_MOV, [S_B]) and
  10766. { Writing to memory is allowed }
  10767. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10768. begin
  10769. {
  10770. Watch out for sequences such as:
  10771. set(c)b %regb
  10772. movb %regb,(ref)
  10773. movb $0,1(ref)
  10774. movb $0,2(ref)
  10775. movb $0,3(ref)
  10776. Much more efficient to turn it into:
  10777. movl $0,%regl
  10778. set(c)b %regb
  10779. movl %regl,(ref)
  10780. Or:
  10781. set(c)b %regb
  10782. movzbl %regb,%regl
  10783. movl %regl,(ref)
  10784. }
  10785. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10786. GetNextInstruction(hp1, hp2) and
  10787. MatchInstruction(hp2, A_MOV, [S_B]) and
  10788. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10789. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10790. begin
  10791. { Don't do anything else except set Result to True }
  10792. end
  10793. else
  10794. begin
  10795. if taicpu(p).oper[0]^.typ = top_reg then
  10796. begin
  10797. TransferUsedRegs(TmpUsedRegs);
  10798. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10799. end;
  10800. { If it's not a register, it's a memory address }
  10801. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10802. begin
  10803. { Even if the register is still in use, we can minimise the
  10804. pipeline stall by changing the MOV into another SETcc. }
  10805. taicpu(hp1).opcode := A_SETcc;
  10806. taicpu(hp1).condition := taicpu(p).condition;
  10807. if taicpu(hp1).oper[1]^.typ = top_ref then
  10808. begin
  10809. { Swapping the operand pointers like this is probably a
  10810. bit naughty, but it is far faster than using loadoper
  10811. to transfer the reference from oper[1] to oper[0] if
  10812. you take into account the extra procedure calls and
  10813. the memory allocation and deallocation required }
  10814. OperPtr := taicpu(hp1).oper[1];
  10815. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10816. taicpu(hp1).oper[0] := OperPtr;
  10817. end
  10818. else
  10819. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10820. taicpu(hp1).clearop(1);
  10821. taicpu(hp1).ops := 1;
  10822. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10823. end
  10824. else
  10825. begin
  10826. if taicpu(hp1).oper[1]^.typ = top_reg then
  10827. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10828. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10829. RemoveInstruction(hp1);
  10830. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10831. end
  10832. end;
  10833. Result := True;
  10834. end;
  10835. end;
  10836. end;
  10837. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  10838. var
  10839. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  10840. TargetReg: TRegister;
  10841. condition, inverted_condition: TAsmCond;
  10842. FoundMOV: Boolean;
  10843. begin
  10844. Result := False;
  10845. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  10846. create the most optimial instructions possible due to limited
  10847. register availability, and there are situations where two
  10848. complementary "simple" CMOV blocks are created which, after the fact
  10849. can be merged into a "double" block. For example:
  10850. movw $257,%ax
  10851. movw $2,%r8w
  10852. xorl r9d,%r9d
  10853. testw $16,18(%rcx)
  10854. cmovew %ax,%dx
  10855. cmovew %r8w,%bx
  10856. cmovel %r9d,%r14d
  10857. movw $1283,%ax
  10858. movw $4,%r8w
  10859. movl $9,%r9d
  10860. cmovnew %ax,%dx
  10861. cmovnew %r8w,%bx
  10862. cmovnel %r9d,%r14d
  10863. The CMOVNE instructions at the end can be removed, and the
  10864. destination registers copied into the MOV instructions directly
  10865. above them, before finally being moved to before the first CMOVE
  10866. instructions, to produce:
  10867. movw $257,%ax
  10868. movw $2,%r8w
  10869. xorl r9d,%r9d
  10870. testw $16,18(%rcx)
  10871. movw $1283,%dx
  10872. movw $4,%bx
  10873. movl $9,%r14d
  10874. cmovew %ax,%dx
  10875. cmovew %r8w,%bx
  10876. cmovel %r9d,%r14d
  10877. Which can then be later optimised to:
  10878. movw $257,%ax
  10879. movw $2,%r8w
  10880. xorl r9d,%r9d
  10881. movw $1283,%dx
  10882. movw $4,%bx
  10883. movl $9,%r14d
  10884. testw $16,18(%rcx)
  10885. cmovew %ax,%dx
  10886. cmovew %r8w,%bx
  10887. cmovel %r9d,%r14d
  10888. }
  10889. TargetReg := taicpu(hp1).oper[1]^.reg;
  10890. condition := taicpu(hp1).condition;
  10891. inverted_condition := inverse_cond(condition);
  10892. pFirstMov := nil;
  10893. pLastMov := nil;
  10894. pCMOV := nil;
  10895. if (p.typ = ait_instruction) then
  10896. pCond := p
  10897. else if not GetNextInstruction(p, pCond) then
  10898. InternalError(2024012501);
  10899. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  10900. { We should get the CMP or TEST instructeion }
  10901. InternalError(2024012502);
  10902. if (
  10903. (taicpu(hp1).oper[0]^.typ = top_reg) or
  10904. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  10905. ) then
  10906. begin
  10907. { We have to tread carefully here, hence why we're not using
  10908. GetNextInstructionUsingReg... we can only accept MOV and other
  10909. CMOV instructions. Anything else and we must drop out}
  10910. hp2 := hp1;
  10911. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  10912. begin
  10913. if (hp2.typ <> ait_instruction) then
  10914. Exit;
  10915. case taicpu(hp2).opcode of
  10916. A_MOV:
  10917. begin
  10918. if not Assigned(pFirstMov) then
  10919. pFirstMov := hp2;
  10920. pLastMOV := hp2;
  10921. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  10922. { Something different - drop out }
  10923. Exit;
  10924. { Otherwise, leave it for now }
  10925. end;
  10926. A_CMOVcc:
  10927. begin
  10928. if taicpu(hp2).condition = inverted_condition then
  10929. begin
  10930. { We found what we're looking for }
  10931. if taicpu(hp2).oper[1]^.reg = TargetReg then
  10932. begin
  10933. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  10934. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  10935. begin
  10936. pCMOV := hp2;
  10937. Break;
  10938. end
  10939. else
  10940. { Unsafe reference - drop out }
  10941. Exit;
  10942. end;
  10943. end
  10944. else if taicpu(hp2).condition <> condition then
  10945. { Something weird - drop out }
  10946. Exit;
  10947. end;
  10948. else
  10949. { Invalid }
  10950. Exit;
  10951. end;
  10952. end;
  10953. if not Assigned(pCMOV) then
  10954. { No complementary CMOV found }
  10955. Exit;
  10956. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  10957. begin
  10958. { Don't need to do anything special or search for a matching MOV }
  10959. Asml.Remove(pCMOV);
  10960. if RegInInstruction(TargetReg, pCond) then
  10961. { Make sure we don't overwrite the register if it's being used in the condition }
  10962. Asml.InsertAfter(pCMOV, pCond)
  10963. else
  10964. Asml.InsertBefore(pCMOV, pCond);
  10965. taicpu(pCMOV).opcode := A_MOV;
  10966. taicpu(pCMOV).condition := C_None;
  10967. { Don't need to worry about allocating new registers in these cases }
  10968. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  10969. Result := True;
  10970. Exit;
  10971. end
  10972. else
  10973. begin
  10974. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  10975. FoundMOV := False;
  10976. { Search for the MOV that sets the target register }
  10977. hp2 := pFirstMov;
  10978. repeat
  10979. if (taicpu(hp2).opcode = A_MOV) and
  10980. (taicpu(hp2).oper[1]^.typ = top_reg) and
  10981. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  10982. begin
  10983. { Change the destination }
  10984. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  10985. if not FoundMOV then
  10986. begin
  10987. FoundMOV := True;
  10988. { Make sure the register is allocated }
  10989. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  10990. end;
  10991. hp1 := tai(hp2.Previous);
  10992. Asml.Remove(hp2);
  10993. if RegInInstruction(TargetReg, pCond) then
  10994. { Make sure we don't overwrite the register if it's being used in the condition }
  10995. Asml.InsertAfter(hp2, pCond)
  10996. else
  10997. Asml.InsertBefore(hp2, pCond);
  10998. if (hp2 = pLastMov) then
  10999. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11000. Break;
  11001. hp2 := hp1;
  11002. end;
  11003. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11004. if FoundMOV then
  11005. { Delete the CMOV }
  11006. RemoveInstruction(pCMOV)
  11007. else
  11008. begin
  11009. { If no MOV was found, we have to actually move and transmute the CMOV }
  11010. Asml.Remove(pCMOV);
  11011. if RegInInstruction(TargetReg, pCond) then
  11012. { Make sure we don't overwrite the register if it's being used in the condition }
  11013. Asml.InsertAfter(pCMOV, pCond)
  11014. else
  11015. Asml.InsertBefore(pCMOV, pCond);
  11016. taicpu(pCMOV).opcode := A_MOV;
  11017. taicpu(pCMOV).condition := C_None;
  11018. end;
  11019. Result := True;
  11020. Exit;
  11021. end;
  11022. end;
  11023. end;
  11024. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11025. var
  11026. hp1, hp2, pCond: tai;
  11027. begin
  11028. Result := False;
  11029. { Search ahead for CMOV instructions }
  11030. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11031. begin
  11032. hp1 := p;
  11033. hp2 := p;
  11034. pCond := nil; { To prevent compiler warnings }
  11035. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11036. DEFAULTFLAGS }
  11037. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11038. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11039. pCond := p;
  11040. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11041. begin
  11042. if (hp1.typ <> ait_instruction) then
  11043. { Break out on markers and labels etc. }
  11044. Break;
  11045. case taicpu(hp1).opcode of
  11046. A_MOV:
  11047. { Ignore regular MOVs unless they are obviously not related
  11048. to a CMOV block }
  11049. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11050. Break;
  11051. A_CMOVcc:
  11052. if TryCmpCMovOpts(pCond, hp1) then
  11053. begin
  11054. hp1 := hp2;
  11055. { p itself isn't changed, and we're still inside a
  11056. while loop to catch subsequent CMOVs, so just flag
  11057. a new iteration }
  11058. Include(OptsToCheck, aoc_ForceNewIteration);
  11059. Continue;
  11060. end;
  11061. else
  11062. { Drop out if we find anything else }
  11063. Break;
  11064. end;
  11065. hp2 := hp1;
  11066. end;
  11067. end;
  11068. end;
  11069. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11070. var
  11071. hp1, hp2, pCond: tai;
  11072. begin
  11073. Result := False;
  11074. { Search ahead for CMOV instructions }
  11075. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11076. begin
  11077. hp1 := p;
  11078. hp2 := p;
  11079. pCond := nil; { To prevent compiler warnings }
  11080. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11081. DEFAULTFLAGS }
  11082. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11083. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11084. pCond := p;
  11085. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11086. begin
  11087. if (hp1.typ <> ait_instruction) then
  11088. { Break out on markers and labels etc. }
  11089. Break;
  11090. case taicpu(hp1).opcode of
  11091. A_MOV:
  11092. { Ignore regular MOVs unless they are obviously not related
  11093. to a CMOV block }
  11094. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11095. Break;
  11096. A_CMOVcc:
  11097. if TryCmpCMovOpts(pCond, hp1) then
  11098. begin
  11099. hp1 := hp2;
  11100. { p itself isn't changed, and we're still inside a
  11101. while loop to catch subsequent CMOVs, so just flag
  11102. a new iteration }
  11103. Include(OptsToCheck, aoc_ForceNewIteration);
  11104. Continue;
  11105. end;
  11106. else
  11107. { Drop out if we find anything else }
  11108. Break;
  11109. end;
  11110. hp2 := hp1;
  11111. end;
  11112. end;
  11113. end;
  11114. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11115. var
  11116. hp1: tai;
  11117. Count: Integer;
  11118. OrigLabel: TAsmLabel;
  11119. begin
  11120. result := False;
  11121. { Sometimes, the optimisations below can permit this }
  11122. RemoveDeadCodeAfterJump(p);
  11123. 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
  11124. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11125. begin
  11126. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11127. { Also a side-effect of optimisations }
  11128. if CollapseZeroDistJump(p, OrigLabel) then
  11129. begin
  11130. Result := True;
  11131. Exit;
  11132. end;
  11133. hp1 := GetLabelWithSym(OrigLabel);
  11134. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11135. begin
  11136. if taicpu(hp1).opcode = A_RET then
  11137. begin
  11138. {
  11139. change
  11140. jmp .L1
  11141. ...
  11142. .L1:
  11143. ret
  11144. into
  11145. ret
  11146. }
  11147. begin
  11148. ConvertJumpToRET(p, hp1);
  11149. result:=true;
  11150. end;
  11151. end
  11152. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11153. not (cs_opt_size in current_settings.optimizerswitches) and
  11154. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11155. begin
  11156. Result := True;
  11157. Exit;
  11158. end;
  11159. end;
  11160. end;
  11161. end;
  11162. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11163. begin
  11164. Result := assigned(p) and
  11165. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11166. (taicpu(p).oper[1]^.typ = top_reg) and
  11167. (
  11168. (taicpu(p).oper[0]^.typ = top_reg) or
  11169. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11170. it is not expected that this can cause a seg. violation }
  11171. (
  11172. (taicpu(p).oper[0]^.typ = top_ref) and
  11173. { TODO: Can we detect which references become constants at this
  11174. stage so we don't have to do a blanket ban? }
  11175. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11176. (
  11177. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11178. (
  11179. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11180. not RefModified and
  11181. { If the reference also appears in the condition, then we know it's safe, otherwise
  11182. any kind of access violation would have occurred already }
  11183. Assigned(cond_p) and
  11184. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11185. (cond_p.typ = ait_instruction) and
  11186. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11187. { Just consider 2-operand comparison instructions for now to be safe }
  11188. (taicpu(cond_p).ops = 2) and
  11189. (
  11190. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11191. (
  11192. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11193. { Don't risk identical registers but different offsets, as we may have constructs
  11194. such as buffer streams with things like length fields that indicate whether
  11195. any more data follows. And there are probably some contrived examples where
  11196. writing to offsets behind the one being read also lead to access violations }
  11197. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11198. (
  11199. { Check that we're not modifying a register that appears in the reference }
  11200. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11201. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11202. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11203. )
  11204. )
  11205. )
  11206. )
  11207. )
  11208. )
  11209. );
  11210. end;
  11211. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11212. begin
  11213. { Update integer registers, ignoring deallocations }
  11214. repeat
  11215. while assigned(p) and
  11216. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11217. (p.typ = ait_label) or
  11218. ((p.typ = ait_marker) and
  11219. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11220. p := tai(p.next);
  11221. while assigned(p) and
  11222. (p.typ=ait_RegAlloc) Do
  11223. begin
  11224. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11225. begin
  11226. case tai_regalloc(p).ratype of
  11227. ra_alloc :
  11228. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11229. else
  11230. ;
  11231. end;
  11232. end;
  11233. p := tai(p.next);
  11234. end;
  11235. until not(assigned(p)) or
  11236. (not(p.typ in SkipInstr) and
  11237. not((p.typ = ait_label) and
  11238. labelCanBeSkipped(tai_label(p))));
  11239. end;
  11240. {$ifndef 8086}
  11241. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11242. begin
  11243. Result := False;
  11244. EndJump := nil;
  11245. BlockStop := nil;
  11246. while (BlockStart <> fOptimizer.BlockEnd) and
  11247. { stop on labels }
  11248. (BlockStart.typ <> ait_label) do
  11249. begin
  11250. { Keep track of all integer registers that are used }
  11251. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11252. if BlockStart.typ = ait_instruction then
  11253. begin
  11254. if (taicpu(BlockStart).opcode = A_JMP) then
  11255. begin
  11256. if not IsJumpToLabel(taicpu(BlockStart)) or
  11257. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11258. Exit;
  11259. EndJump := BlockStart;
  11260. Break;
  11261. end
  11262. { Check to see if we have a valid MOV instruction instead }
  11263. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11264. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11265. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11266. begin
  11267. Exit;
  11268. end
  11269. else
  11270. { This will be a valid MOV }
  11271. fAllocationRange := BlockStart;
  11272. end;
  11273. OneBeforeBlock := BlockStart;
  11274. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11275. end;
  11276. if (BlockStart = fOptimizer.BlockEnd) then
  11277. Exit;
  11278. BlockStop := BlockStart;
  11279. Result := True;
  11280. end;
  11281. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11282. var
  11283. hp1: tai;
  11284. RefModified: Boolean;
  11285. begin
  11286. Result := 0;
  11287. hp1 := BlockStart;
  11288. RefModified := False; { As long as the condition is inverted, this can be reset }
  11289. while assigned(hp1) and
  11290. (hp1 <> BlockStop) do
  11291. begin
  11292. case hp1.typ of
  11293. ait_instruction:
  11294. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11295. begin
  11296. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11297. begin
  11298. Inc(Result);
  11299. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11300. Assigned(fCondition) and
  11301. { Will have 2 operands }
  11302. (
  11303. (
  11304. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11305. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11306. ) or
  11307. (
  11308. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11309. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11310. )
  11311. ) then
  11312. { It is no longer safe to use the reference in the condition.
  11313. this prevents problems such as:
  11314. mov (%reg),%reg
  11315. mov (%reg),...
  11316. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11317. (fixes #40165)
  11318. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11319. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11320. }
  11321. RefModified := True;
  11322. end
  11323. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11324. { CMOV with constants grows the code size }
  11325. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11326. begin
  11327. { Register was reserved by TryCMOVConst and
  11328. stored on ConstRegs }
  11329. end
  11330. else
  11331. begin
  11332. Result := -1;
  11333. Exit;
  11334. end;
  11335. end
  11336. else
  11337. begin
  11338. Result := -1;
  11339. Exit;
  11340. end;
  11341. else
  11342. { Most likely an align };
  11343. end;
  11344. fOptimizer.GetNextInstruction(hp1, hp1);
  11345. end;
  11346. end;
  11347. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11348. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11349. (this is done as a separate stage because the double types are extensions of the branching type,
  11350. but we can't discount the conditional jump until the last step) }
  11351. procedure EvaluateBranchingType;
  11352. begin
  11353. Inc(CMOVScore);
  11354. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11355. { Too many instructions to be worthwhile }
  11356. fState := tsInvalid;
  11357. end;
  11358. var
  11359. hp1: tai;
  11360. Count: Integer;
  11361. begin
  11362. { Table of valid CMOV block types
  11363. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11364. ---------- --------- --------- --------- --------- ---------
  11365. tsSimple X Yes X X X
  11366. tsDetour = 1st X X X X
  11367. tsBranching <> Mid Yes X X X
  11368. tsDouble End-label Yes * Yes X Yes
  11369. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11370. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11371. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11372. * Only one reference allowed
  11373. }
  11374. hp1 := nil; { To prevent compiler warnings }
  11375. Optimizer.CopyUsedRegs(RegisterTracking);
  11376. fOptimizer := Optimizer;
  11377. fLabel := AFirstLabel;
  11378. CMOVScore := 0;
  11379. ConstCount := 0;
  11380. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11381. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11382. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11383. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11384. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11385. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11386. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11387. fInsertionPoint := p_initialjump;
  11388. fCondition := nil;
  11389. fInitialJump := p_initialjump;
  11390. fFirstMovBlock := p_initialmov;
  11391. fFirstMovBlockStop := nil;
  11392. fSecondJump := nil;
  11393. fSecondMovBlock := nil;
  11394. fSecondMovBlockStop := nil;
  11395. fMidLabel := nil;
  11396. fSecondJump := nil;
  11397. fSecondMovBlock := nil;
  11398. fEndLabel := nil;
  11399. fAllocationRange := nil;
  11400. { Assume it all goes horribly wrong! }
  11401. fState := tsInvalid;
  11402. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11403. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11404. 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
  11405. begin
  11406. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11407. for Count := 0 to 1 do
  11408. with taicpu(fCondition).oper[Count]^ do
  11409. case typ of
  11410. top_reg:
  11411. if getregtype(reg) = R_INTREGISTER then
  11412. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11413. top_ref:
  11414. begin
  11415. if
  11416. {$ifdef x86_64}
  11417. (ref^.base <> NR_RIP) and
  11418. {$endif x86_64}
  11419. (ref^.base <> NR_NO) then
  11420. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11421. if (ref^.index <> NR_NO) then
  11422. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11423. end
  11424. else
  11425. ;
  11426. end;
  11427. { When inserting instructions before hp_prev, try to insert them
  11428. before the allocation of the FLAGS register }
  11429. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11430. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11431. { If not found, set it equal to the condition so it's something sensible }
  11432. fInsertionPoint := fCondition;
  11433. { When dealing with a comparison against zero, take note of the
  11434. instruction before it to see if we can move instructions further
  11435. back in order to benefit PostPeepholeOptTestOr.
  11436. }
  11437. if (
  11438. (
  11439. (taicpu(fCondition).opcode = A_CMP) and
  11440. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11441. ) or
  11442. (
  11443. (taicpu(fCondition).opcode = A_TEST) and
  11444. (
  11445. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11446. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11447. )
  11448. )
  11449. ) and
  11450. Optimizer.GetLastInstruction(fCondition, hp1) then
  11451. begin
  11452. { These instructions set the zero flag if the result is zero }
  11453. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11454. begin
  11455. fInsertionPoint := hp1;
  11456. { Also mark all the registers in this previous instruction
  11457. as 'in use', even if they've just been deallocated }
  11458. for Count := 0 to 1 do
  11459. with taicpu(hp1).oper[Count]^ do
  11460. case typ of
  11461. top_reg:
  11462. if getregtype(reg) = R_INTREGISTER then
  11463. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11464. top_ref:
  11465. begin
  11466. if
  11467. {$ifdef x86_64}
  11468. (ref^.base <> NR_RIP) and
  11469. {$endif x86_64}
  11470. (ref^.base <> NR_NO) then
  11471. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11472. if (ref^.index <> NR_NO) then
  11473. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11474. end
  11475. else
  11476. ;
  11477. end;
  11478. end;
  11479. end;
  11480. end
  11481. else
  11482. fCondition := nil;
  11483. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11484. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11485. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11486. { If not found, set it equal to p so it's something sensible }
  11487. fInsertionPoint := hp1;
  11488. hp1 := p_initialmov;
  11489. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11490. Exit;
  11491. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11492. if (hp1.typ <> ait_label) then { should be on a jump }
  11493. begin
  11494. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11495. { Need a label afterwards }
  11496. Exit;
  11497. end
  11498. else
  11499. fMidLabel := hp1;
  11500. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11501. { Not the correct label }
  11502. fMidLabel := nil;
  11503. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  11504. { If there's neither a 2nd jump nor correct label, then it's invalid
  11505. (see above table) }
  11506. Exit;
  11507. { Analyse the first block of MOVs more closely }
  11508. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  11509. if Assigned(fSecondJump) then
  11510. begin
  11511. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  11512. begin
  11513. fState := tsDetour
  11514. end
  11515. else
  11516. begin
  11517. { Need the correct mid-label for this one }
  11518. if not Assigned(fMidLabel) then
  11519. Exit;
  11520. fState := tsBranching;
  11521. end;
  11522. end
  11523. else
  11524. { No jump. but mid-label is present }
  11525. fState := tsSimple;
  11526. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  11527. begin
  11528. { Invalid or too many instructions to be worthwhile }
  11529. fState := tsInvalid;
  11530. Exit;
  11531. end;
  11532. { check further for
  11533. jCC xxx
  11534. <several movs 1>
  11535. jmp yyy
  11536. xxx:
  11537. <several movs 2>
  11538. yyy:
  11539. etc.
  11540. }
  11541. if (fState = tsBranching) and
  11542. { Estimate for required savings for extra jump }
  11543. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  11544. { Only one reference is allowed for double blocks }
  11545. (AFirstLabel.getrefs = 1) then
  11546. begin
  11547. Optimizer.GetNextInstruction(fMidLabel, hp1);
  11548. fSecondMovBlock := hp1;
  11549. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  11550. begin
  11551. EvaluateBranchingType;
  11552. Exit;
  11553. end;
  11554. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  11555. if (hp1.typ <> ait_label) then { should be on a jump }
  11556. begin
  11557. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  11558. begin
  11559. { Need a label afterwards }
  11560. EvaluateBranchingType;
  11561. Exit;
  11562. end;
  11563. end
  11564. else
  11565. fEndLabel := hp1;
  11566. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  11567. { Second jump doesn't go to the end }
  11568. fEndLabel := nil;
  11569. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  11570. begin
  11571. { If there's neither a 3rd jump nor correct end label, then it's
  11572. not a invalid double block, but is a valid single branching
  11573. block (see above table) }
  11574. EvaluateBranchingType;
  11575. Exit;
  11576. end;
  11577. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  11578. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  11579. { Invalid or too many instructions to be worthwhile }
  11580. Exit;
  11581. Inc(CMOVScore, Count);
  11582. if Assigned(fThirdJump) then
  11583. begin
  11584. if not Assigned(fSecondJump) then
  11585. fState := tsDoubleSecondBranching
  11586. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  11587. fState := tsDoubleBranchSame
  11588. else
  11589. fState := tsDoubleBranchDifferent;
  11590. end
  11591. else
  11592. fState := tsDouble;
  11593. end;
  11594. if fState = tsBranching then
  11595. EvaluateBranchingType;
  11596. end;
  11597. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  11598. new register to store the constant }
  11599. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  11600. var
  11601. RegSize: TSubRegister;
  11602. CurrentVal: TCGInt;
  11603. ANewReg: TRegister;
  11604. X: ShortInt;
  11605. begin
  11606. Result := False;
  11607. if not MatchOpType(taicpu(p), top_const, top_reg) then
  11608. Exit;
  11609. if ConstCount >= MAX_CMOV_REGISTERS then
  11610. { Arrays are full }
  11611. Exit;
  11612. { Remember that CMOV can't encode 8-bit registers }
  11613. case taicpu(p).opsize of
  11614. S_W:
  11615. RegSize := R_SUBW;
  11616. S_L:
  11617. RegSize := R_SUBD;
  11618. {$ifdef x86_64}
  11619. S_Q:
  11620. RegSize := R_SUBQ;
  11621. {$endif x86_64}
  11622. else
  11623. InternalError(2021100401);
  11624. end;
  11625. { See if the value has already been reserved for another CMOV instruction }
  11626. CurrentVal := taicpu(p).oper[0]^.val;
  11627. for X := 0 to ConstCount - 1 do
  11628. if ConstVals[X] = CurrentVal then
  11629. begin
  11630. ConstRegs[ConstCount] := ConstRegs[X];
  11631. ConstSizes[ConstCount] := RegSize;
  11632. ConstVals[ConstCount] := CurrentVal;
  11633. Inc(ConstCount);
  11634. Inc(Count);
  11635. Result := True;
  11636. Exit;
  11637. end;
  11638. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  11639. if ANewReg = NR_NO then
  11640. { No free registers }
  11641. Exit;
  11642. { Reserve the register so subsequent TryCMOVConst calls don't all end
  11643. up vying for the same register }
  11644. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  11645. ConstRegs[ConstCount] := ANewReg;
  11646. ConstSizes[ConstCount] := RegSize;
  11647. ConstVals[ConstCount] := CurrentVal;
  11648. Inc(ConstCount);
  11649. Inc(Count);
  11650. Result := True;
  11651. end;
  11652. destructor TCMOVTracking.Done;
  11653. begin
  11654. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  11655. end;
  11656. procedure TCMOVTracking.Process(out new_p: tai);
  11657. var
  11658. Count, Writes: LongInt;
  11659. RegMatch: Boolean;
  11660. hp1, hp_new: tai;
  11661. inverted_condition, condition: TAsmCond;
  11662. begin
  11663. if (fState in [tsInvalid, tsProcessed]) then
  11664. InternalError(2023110701);
  11665. { Repurpose RegisterTracking to mark registers that we've defined }
  11666. RegisterTracking[R_INTREGISTER].Clear;
  11667. Count := 0;
  11668. Writes := 0;
  11669. condition := taicpu(fInitialJump).condition;
  11670. inverted_condition := inverse_cond(condition);
  11671. { Exclude tsDoubleBranchDifferent from this check, as the second block
  11672. doesn't get CMOVs in this case }
  11673. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  11674. begin
  11675. { Include the jump in the flag tracking }
  11676. if Assigned(fThirdJump) then
  11677. begin
  11678. if (fState = tsDoubleBranchSame) then
  11679. begin
  11680. { Will be an unconditional jump, so track to the instruction before it }
  11681. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  11682. InternalError(2023110710);
  11683. end
  11684. else
  11685. hp1 := fThirdJump;
  11686. end
  11687. else
  11688. hp1 := fSecondMovBlockStop;
  11689. end
  11690. else
  11691. begin
  11692. { Include a conditional jump in the flag tracking }
  11693. if Assigned(fSecondJump) then
  11694. begin
  11695. if (fState = tsDetour) then
  11696. begin
  11697. { Will be an unconditional jump, so track to the instruction before it }
  11698. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  11699. InternalError(2023110711);
  11700. end
  11701. else
  11702. hp1 := fSecondJump;
  11703. end
  11704. else
  11705. hp1 := fFirstMovBlockStop;
  11706. end;
  11707. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  11708. { Process the second set of MOVs first, because if a destination
  11709. register is shared between the first and second MOV sets, it is more
  11710. efficient to turn the first one into a MOV instruction and place it
  11711. before the CMP if possible, but we won't know which registers are
  11712. shared until we've processed at least one list, so we might as well
  11713. make it the second one since that won't be modified again. }
  11714. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  11715. begin
  11716. hp1 := fSecondMovBlock;
  11717. repeat
  11718. if not Assigned(hp1) then
  11719. InternalError(2018062902);
  11720. if (hp1.typ = ait_instruction) then
  11721. begin
  11722. { Extra safeguard }
  11723. if (taicpu(hp1).opcode <> A_MOV) then
  11724. InternalError(2018062903);
  11725. { Note: tsDoubleBranchDifferent is essentially identical to
  11726. tsBranching and the 2nd block is best left largely
  11727. untouched, but we need to evaluate which registers the MOVs
  11728. write to in order to track what would be complementary CMOV
  11729. pairs that can be further optimised. [Kit] }
  11730. if fState <> tsDoubleBranchDifferent then
  11731. begin
  11732. if taicpu(hp1).oper[0]^.typ = top_const then
  11733. begin
  11734. RegMatch := False;
  11735. for Count := 0 to ConstCount - 1 do
  11736. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  11737. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  11738. begin
  11739. RegMatch := True;
  11740. { If it's in RegisterTracking, then this register
  11741. is being used more than once and hence has
  11742. already had its value defined (it gets added to
  11743. UsedRegs through AllocRegBetween below) }
  11744. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  11745. begin
  11746. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  11747. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  11748. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  11749. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  11750. ConstMovs[Count] := hp_new;
  11751. end
  11752. else
  11753. { We just need an instruction between hp_prev and hp1
  11754. where we know the register is marked as in use }
  11755. hp_new := fSecondMovBlock;
  11756. { Keep track of largest write for this register so it can be optimised later }
  11757. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  11758. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11759. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  11760. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  11761. Break;
  11762. end;
  11763. if not RegMatch then
  11764. InternalError(2021100411);
  11765. end;
  11766. taicpu(hp1).opcode := A_CMOVcc;
  11767. taicpu(hp1).condition := condition;
  11768. end;
  11769. { Store these writes to search for duplicates later on }
  11770. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  11771. Inc(Writes);
  11772. end;
  11773. fOptimizer.GetNextInstruction(hp1, hp1);
  11774. until (hp1 = fSecondMovBlockStop);
  11775. end;
  11776. { Now do the first set of MOVs }
  11777. hp1 := fFirstMovBlock;
  11778. repeat
  11779. if not Assigned(hp1) then
  11780. InternalError(2018062904);
  11781. if (hp1.typ = ait_instruction) then
  11782. begin
  11783. RegMatch := False;
  11784. { Extra safeguard }
  11785. if (taicpu(hp1).opcode <> A_MOV) then
  11786. InternalError(2018062905);
  11787. { Search through the RegWrites list to see if there are any
  11788. opposing CMOV pairs that write to the same register }
  11789. for Count := 0 to Writes - 1 do
  11790. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  11791. begin
  11792. { We have a match. Keep this as a MOV }
  11793. { Move ahead in preparation }
  11794. fOptimizer.GetNextInstruction(hp1, hp1);
  11795. RegMatch := True;
  11796. Break;
  11797. end;
  11798. if RegMatch then
  11799. Continue;
  11800. if taicpu(hp1).oper[0]^.typ = top_const then
  11801. begin
  11802. for Count := 0 to ConstCount - 1 do
  11803. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  11804. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  11805. begin
  11806. RegMatch := True;
  11807. { If it's in RegisterTracking, then this register is
  11808. being used more than once and hence has already had
  11809. its value defined (it gets added to UsedRegs through
  11810. AllocRegBetween below) }
  11811. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  11812. begin
  11813. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  11814. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  11815. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  11816. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  11817. ConstMovs[Count] := hp_new;
  11818. end
  11819. else
  11820. { We just need an instruction between hp_prev and hp1
  11821. where we know the register is marked as in use }
  11822. hp_new := fFirstMovBlock;
  11823. { Keep track of largest write for this register so it can be optimised later }
  11824. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  11825. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11826. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  11827. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  11828. Break;
  11829. end;
  11830. if not RegMatch then
  11831. InternalError(2021100412);
  11832. end;
  11833. taicpu(hp1).opcode := A_CMOVcc;
  11834. taicpu(hp1).condition := inverted_condition;
  11835. if (fState = tsDoubleBranchDifferent) then
  11836. begin
  11837. { Store these writes to search for duplicates later on }
  11838. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  11839. Inc(Writes);
  11840. end;
  11841. end;
  11842. fOptimizer.GetNextInstruction(hp1, hp1);
  11843. until (hp1 = fFirstMovBlockStop);
  11844. { Update initialisation MOVs to the smallest possible size }
  11845. for Count := 0 to ConstCount - 1 do
  11846. if Assigned(ConstMovs[Count]) then
  11847. begin
  11848. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  11849. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  11850. end;
  11851. case fState of
  11852. tsSimple:
  11853. begin
  11854. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  11855. { No branch to delete }
  11856. end;
  11857. tsDetour:
  11858. begin
  11859. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  11860. { Preserve jump }
  11861. end;
  11862. tsBranching, tsDoubleBranchDifferent:
  11863. begin
  11864. if (fState = tsBranching) then
  11865. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  11866. else
  11867. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  11868. taicpu(fSecondJump).opcode := A_JCC;
  11869. taicpu(fSecondJump).condition := inverted_condition;
  11870. end;
  11871. tsDouble, tsDoubleBranchSame:
  11872. begin
  11873. if (fState = tsDouble) then
  11874. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  11875. else
  11876. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  11877. { Delete second jump }
  11878. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  11879. fOptimizer.RemoveInstruction(fSecondJump);
  11880. end;
  11881. tsDoubleSecondBranching:
  11882. begin
  11883. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  11884. { Delete second jump, preserve third jump as conditional }
  11885. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  11886. fOptimizer.RemoveInstruction(fSecondJump);
  11887. taicpu(fThirdJump).opcode := A_JCC;
  11888. taicpu(fThirdJump).condition := condition;
  11889. end;
  11890. else
  11891. InternalError(2023110720);
  11892. end;
  11893. { Now we can safely decrement the reference count }
  11894. tasmlabel(fLabel).decrefs;
  11895. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  11896. { Remove the original jump }
  11897. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  11898. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  11899. fState := tsProcessed;
  11900. end;
  11901. {$endif 8086}
  11902. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  11903. var
  11904. hp1,hp2: tai;
  11905. carryadd_opcode : TAsmOp;
  11906. symbol: TAsmSymbol;
  11907. increg, tmpreg: TRegister;
  11908. {$ifndef i8086}
  11909. CMOVTracking: PCMOVTracking;
  11910. hp3,hp4,hp5: tai;
  11911. {$endif i8086}
  11912. TempBool: Boolean;
  11913. begin
  11914. if (aoc_DoPass2JccOpts in OptsToCheck) and
  11915. DoJumpOptimizations(p, TempBool) then
  11916. Exit(True);
  11917. result:=false;
  11918. if GetNextInstruction(p,hp1) then
  11919. begin
  11920. if (hp1.typ=ait_label) then
  11921. begin
  11922. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  11923. Exit;
  11924. end
  11925. else if (hp1.typ<>ait_instruction) then
  11926. Exit;
  11927. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11928. if (
  11929. (
  11930. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  11931. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  11932. (Taicpu(hp1).oper[0]^.val=1)
  11933. ) or
  11934. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  11935. ) and
  11936. GetNextInstruction(hp1,hp2) and
  11937. (hp2.typ = ait_label) and
  11938. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  11939. { jb @@1 cmc
  11940. inc/dec operand --> adc/sbb operand,0
  11941. @@1:
  11942. ... and ...
  11943. jnb @@1
  11944. inc/dec operand --> adc/sbb operand,0
  11945. @@1: }
  11946. begin
  11947. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  11948. begin
  11949. case taicpu(hp1).opcode of
  11950. A_INC,
  11951. A_ADD:
  11952. carryadd_opcode:=A_ADC;
  11953. A_DEC,
  11954. A_SUB:
  11955. carryadd_opcode:=A_SBB;
  11956. else
  11957. InternalError(2021011001);
  11958. end;
  11959. Taicpu(p).clearop(0);
  11960. Taicpu(p).ops:=0;
  11961. Taicpu(p).is_jmp:=false;
  11962. Taicpu(p).opcode:=A_CMC;
  11963. Taicpu(p).condition:=C_NONE;
  11964. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  11965. Taicpu(hp1).ops:=2;
  11966. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  11967. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  11968. else
  11969. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  11970. Taicpu(hp1).loadconst(0,0);
  11971. Taicpu(hp1).opcode:=carryadd_opcode;
  11972. result:=true;
  11973. exit;
  11974. end
  11975. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  11976. begin
  11977. case taicpu(hp1).opcode of
  11978. A_INC,
  11979. A_ADD:
  11980. carryadd_opcode:=A_ADC;
  11981. A_DEC,
  11982. A_SUB:
  11983. carryadd_opcode:=A_SBB;
  11984. else
  11985. InternalError(2021011002);
  11986. end;
  11987. Taicpu(hp1).ops:=2;
  11988. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  11989. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  11990. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  11991. else
  11992. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  11993. Taicpu(hp1).loadconst(0,0);
  11994. Taicpu(hp1).opcode:=carryadd_opcode;
  11995. RemoveCurrentP(p, hp1);
  11996. result:=true;
  11997. exit;
  11998. end
  11999. {
  12000. jcc @@1 setcc tmpreg
  12001. inc/dec/add/sub operand -> (movzx tmpreg)
  12002. @@1: add/sub tmpreg,operand
  12003. While this increases code size slightly, it makes the code much faster if the
  12004. jump is unpredictable
  12005. }
  12006. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12007. begin
  12008. { search for an available register which is volatile }
  12009. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12010. if increg <> NR_NO then
  12011. begin
  12012. { We don't need to check if tmpreg is in hp1 or not, because
  12013. it will be marked as in use at p (if not, this is
  12014. indictive of a compiler bug). }
  12015. TAsmLabel(symbol).decrefs;
  12016. Taicpu(p).clearop(0);
  12017. Taicpu(p).ops:=1;
  12018. Taicpu(p).is_jmp:=false;
  12019. Taicpu(p).opcode:=A_SETcc;
  12020. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12021. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12022. Taicpu(p).loadreg(0,increg);
  12023. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12024. begin
  12025. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12026. R_SUBW:
  12027. begin
  12028. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12029. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12030. end;
  12031. R_SUBD:
  12032. begin
  12033. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12034. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12035. end;
  12036. {$ifdef x86_64}
  12037. R_SUBQ:
  12038. begin
  12039. { MOVZX doesn't have a 64-bit variant, because
  12040. the 32-bit version implicitly zeroes the
  12041. upper 32-bits of the destination register }
  12042. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12043. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12044. setsubreg(tmpreg, R_SUBQ);
  12045. end;
  12046. {$endif x86_64}
  12047. else
  12048. Internalerror(2020030601);
  12049. end;
  12050. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12051. asml.InsertAfter(hp2,p);
  12052. end
  12053. else
  12054. tmpreg := increg;
  12055. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12056. begin
  12057. Taicpu(hp1).ops:=2;
  12058. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12059. end;
  12060. Taicpu(hp1).loadreg(0,tmpreg);
  12061. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12062. Result := True;
  12063. { p is no longer a Jcc instruction, so exit }
  12064. Exit;
  12065. end;
  12066. end;
  12067. end;
  12068. { Detect the following:
  12069. jmp<cond> @Lbl1
  12070. jmp @Lbl2
  12071. ...
  12072. @Lbl1:
  12073. ret
  12074. Change to:
  12075. jmp<inv_cond> @Lbl2
  12076. ret
  12077. }
  12078. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12079. begin
  12080. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12081. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12082. MatchInstruction(hp2,A_RET,[S_NO]) then
  12083. begin
  12084. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12085. { Change label address to that of the unconditional jump }
  12086. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12087. TAsmLabel(symbol).DecRefs;
  12088. taicpu(hp1).opcode := A_RET;
  12089. taicpu(hp1).is_jmp := false;
  12090. taicpu(hp1).ops := taicpu(hp2).ops;
  12091. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12092. case taicpu(hp2).ops of
  12093. 0:
  12094. taicpu(hp1).clearop(0);
  12095. 1:
  12096. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12097. else
  12098. internalerror(2016041302);
  12099. end;
  12100. end;
  12101. {$ifndef i8086}
  12102. end
  12103. {
  12104. convert
  12105. j<c> .L1
  12106. mov 1,reg
  12107. jmp .L2
  12108. .L1
  12109. mov 0,reg
  12110. .L2
  12111. into
  12112. mov 0,reg
  12113. set<not(c)> reg
  12114. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12115. would destroy the flag contents
  12116. }
  12117. else if MatchInstruction(hp1,A_MOV,[]) and
  12118. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12119. {$ifdef i386}
  12120. (
  12121. { Under i386, ESI, EDI, EBP and ESP
  12122. don't have an 8-bit representation }
  12123. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12124. ) and
  12125. {$endif i386}
  12126. (taicpu(hp1).oper[0]^.val=1) and
  12127. GetNextInstruction(hp1,hp2) and
  12128. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12129. GetNextInstruction(hp2,hp3) and
  12130. (hp3.typ=ait_label) and
  12131. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12132. (tai_label(hp3).labsym.getrefs=1) and
  12133. GetNextInstruction(hp3,hp4) and
  12134. MatchInstruction(hp4,A_MOV,[]) and
  12135. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12136. (taicpu(hp4).oper[0]^.val=0) and
  12137. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12138. GetNextInstruction(hp4,hp5) and
  12139. (hp5.typ=ait_label) and
  12140. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12141. (tai_label(hp5).labsym.getrefs=1) then
  12142. begin
  12143. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12144. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12145. { remove last label }
  12146. RemoveInstruction(hp5);
  12147. { remove second label }
  12148. RemoveInstruction(hp3);
  12149. { remove jmp }
  12150. RemoveInstruction(hp2);
  12151. if taicpu(hp1).opsize=S_B then
  12152. RemoveInstruction(hp1)
  12153. else
  12154. taicpu(hp1).loadconst(0,0);
  12155. taicpu(hp4).opcode:=A_SETcc;
  12156. taicpu(hp4).opsize:=S_B;
  12157. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12158. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12159. taicpu(hp4).opercnt:=1;
  12160. taicpu(hp4).ops:=1;
  12161. taicpu(hp4).freeop(1);
  12162. RemoveCurrentP(p);
  12163. Result:=true;
  12164. exit;
  12165. end
  12166. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12167. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12168. begin
  12169. { check for
  12170. jCC xxx
  12171. <several movs>
  12172. xxx:
  12173. Also spot:
  12174. Jcc xxx
  12175. <several movs>
  12176. jmp xxx
  12177. Change to:
  12178. <several cmovs with inverted condition>
  12179. jmp xxx (only for the 2nd case)
  12180. }
  12181. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12182. if CMOVTracking^.State <> tsInvalid then
  12183. begin
  12184. CMovTracking^.Process(p);
  12185. Result := True;
  12186. end;
  12187. CMOVTracking^.Done;
  12188. {$endif i8086}
  12189. end;
  12190. end;
  12191. end;
  12192. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12193. var
  12194. hp1,hp2,hp3: tai;
  12195. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12196. NewSize: TOpSize;
  12197. NewRegSize: TSubRegister;
  12198. Limit: TCgInt;
  12199. SwapOper: POper;
  12200. begin
  12201. result:=false;
  12202. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12203. GetNextInstruction(p,hp1) and
  12204. (hp1.typ = ait_instruction);
  12205. if reg_and_hp1_is_instr and
  12206. (
  12207. (taicpu(hp1).opcode <> A_LEA) or
  12208. { If the LEA instruction can be converted into an arithmetic instruction,
  12209. it may be possible to then fold it. }
  12210. (
  12211. { If the flags register is in use, don't change the instruction
  12212. to an ADD otherwise this will scramble the flags. [Kit] }
  12213. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12214. ConvertLEA(taicpu(hp1))
  12215. )
  12216. ) and
  12217. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12218. GetNextInstruction(hp1,hp2) and
  12219. MatchInstruction(hp2,A_MOV,[]) and
  12220. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12221. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12222. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12223. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12224. {$ifdef i386}
  12225. { not all registers have byte size sub registers on i386 }
  12226. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12227. {$endif i386}
  12228. (((taicpu(hp1).ops=2) and
  12229. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12230. ((taicpu(hp1).ops=1) and
  12231. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12232. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12233. begin
  12234. { change movsX/movzX reg/ref, reg2
  12235. add/sub/or/... reg3/$const, reg2
  12236. mov reg2 reg/ref
  12237. to add/sub/or/... reg3/$const, reg/ref }
  12238. { by example:
  12239. movswl %si,%eax movswl %si,%eax p
  12240. decl %eax addl %edx,%eax hp1
  12241. movw %ax,%si movw %ax,%si hp2
  12242. ->
  12243. movswl %si,%eax movswl %si,%eax p
  12244. decw %eax addw %edx,%eax hp1
  12245. movw %ax,%si movw %ax,%si hp2
  12246. }
  12247. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12248. {
  12249. ->
  12250. movswl %si,%eax movswl %si,%eax p
  12251. decw %si addw %dx,%si hp1
  12252. movw %ax,%si movw %ax,%si hp2
  12253. }
  12254. case taicpu(hp1).ops of
  12255. 1:
  12256. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12257. 2:
  12258. begin
  12259. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12260. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12261. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12262. end;
  12263. else
  12264. internalerror(2008042702);
  12265. end;
  12266. {
  12267. ->
  12268. decw %si addw %dx,%si p
  12269. }
  12270. DebugMsg(SPeepholeOptimization + 'var3',p);
  12271. RemoveCurrentP(p, hp1);
  12272. RemoveInstruction(hp2);
  12273. Result := True;
  12274. Exit;
  12275. end;
  12276. if reg_and_hp1_is_instr and
  12277. (taicpu(hp1).opcode = A_MOV) and
  12278. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12279. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12280. {$ifdef x86_64}
  12281. { check for implicit extension to 64 bit }
  12282. or
  12283. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12284. (taicpu(hp1).opsize=S_Q) and
  12285. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12286. )
  12287. {$endif x86_64}
  12288. )
  12289. then
  12290. begin
  12291. { change
  12292. movx %reg1,%reg2
  12293. mov %reg2,%reg3
  12294. dealloc %reg2
  12295. into
  12296. movx %reg,%reg3
  12297. }
  12298. TransferUsedRegs(TmpUsedRegs);
  12299. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12300. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12301. begin
  12302. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12303. {$ifdef x86_64}
  12304. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12305. (taicpu(hp1).opsize=S_Q) then
  12306. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12307. else
  12308. {$endif x86_64}
  12309. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12310. RemoveInstruction(hp1);
  12311. Result := True;
  12312. Exit;
  12313. end;
  12314. end;
  12315. if reg_and_hp1_is_instr and
  12316. ((taicpu(hp1).opcode=A_MOV) or
  12317. (taicpu(hp1).opcode=A_ADD) or
  12318. (taicpu(hp1).opcode=A_SUB) or
  12319. (taicpu(hp1).opcode=A_CMP) or
  12320. (taicpu(hp1).opcode=A_OR) or
  12321. (taicpu(hp1).opcode=A_XOR) or
  12322. (taicpu(hp1).opcode=A_AND)
  12323. ) and
  12324. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12325. begin
  12326. AndTest := (taicpu(hp1).opcode=A_AND) and
  12327. GetNextInstruction(hp1, hp2) and
  12328. (hp2.typ = ait_instruction) and
  12329. (
  12330. (
  12331. (taicpu(hp2).opcode=A_TEST) and
  12332. (
  12333. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12334. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12335. (
  12336. { If the AND and TEST instructions share a constant, this is also valid }
  12337. (taicpu(hp1).oper[0]^.typ = top_const) and
  12338. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12339. )
  12340. ) and
  12341. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12342. ) or
  12343. (
  12344. (taicpu(hp2).opcode=A_CMP) and
  12345. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12346. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12347. )
  12348. );
  12349. { change
  12350. movx (oper),%reg2
  12351. and $x,%reg2
  12352. test %reg2,%reg2
  12353. dealloc %reg2
  12354. into
  12355. op %reg1,%reg3
  12356. if the second op accesses only the bits stored in reg1
  12357. }
  12358. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12359. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12360. (taicpu(hp1).oper[0]^.typ = top_const) and
  12361. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12362. AndTest then
  12363. begin
  12364. { Check if the AND constant is in range }
  12365. case taicpu(p).opsize of
  12366. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12367. begin
  12368. NewSize := S_B;
  12369. Limit := $FF;
  12370. end;
  12371. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12372. begin
  12373. NewSize := S_W;
  12374. Limit := $FFFF;
  12375. end;
  12376. {$ifdef x86_64}
  12377. S_LQ:
  12378. begin
  12379. NewSize := S_L;
  12380. Limit := $FFFFFFFF;
  12381. end;
  12382. {$endif x86_64}
  12383. else
  12384. InternalError(2021120303);
  12385. end;
  12386. if (
  12387. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12388. { Check for negative operands }
  12389. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12390. ) and
  12391. GetNextInstruction(hp2,hp3) and
  12392. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12393. (taicpu(hp3).condition in [C_E,C_NE]) then
  12394. begin
  12395. TransferUsedRegs(TmpUsedRegs);
  12396. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12397. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12398. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12399. begin
  12400. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12401. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12402. taicpu(hp1).opcode := A_TEST;
  12403. taicpu(hp1).opsize := NewSize;
  12404. RemoveInstruction(hp2);
  12405. RemoveCurrentP(p, hp1);
  12406. Result:=true;
  12407. exit;
  12408. end;
  12409. end;
  12410. end;
  12411. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12412. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12413. (taicpu(hp1).opsize=S_B)) or
  12414. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12415. (taicpu(hp1).opsize=S_W))
  12416. {$ifdef x86_64}
  12417. or ((taicpu(p).opsize=S_LQ) and
  12418. (taicpu(hp1).opsize=S_L))
  12419. {$endif x86_64}
  12420. ) and
  12421. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12422. begin
  12423. { change
  12424. movx %reg1,%reg2
  12425. op %reg2,%reg3
  12426. dealloc %reg2
  12427. into
  12428. op %reg1,%reg3
  12429. if the second op accesses only the bits stored in reg1
  12430. }
  12431. TransferUsedRegs(TmpUsedRegs);
  12432. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12433. if AndTest then
  12434. begin
  12435. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12436. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12437. end
  12438. else
  12439. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12440. if not RegUsed then
  12441. begin
  12442. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12443. if taicpu(p).oper[0]^.typ=top_reg then
  12444. begin
  12445. case taicpu(hp1).opsize of
  12446. S_B:
  12447. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12448. S_W:
  12449. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12450. S_L:
  12451. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12452. else
  12453. Internalerror(2020102301);
  12454. end;
  12455. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12456. end
  12457. else
  12458. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12459. RemoveCurrentP(p);
  12460. if AndTest then
  12461. RemoveInstruction(hp2);
  12462. result:=true;
  12463. exit;
  12464. end;
  12465. end
  12466. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12467. (
  12468. { Bitwise operations only }
  12469. (taicpu(hp1).opcode=A_AND) or
  12470. (taicpu(hp1).opcode=A_TEST) or
  12471. (
  12472. (taicpu(hp1).oper[0]^.typ = top_const) and
  12473. (
  12474. (taicpu(hp1).opcode=A_OR) or
  12475. (taicpu(hp1).opcode=A_XOR)
  12476. )
  12477. )
  12478. ) and
  12479. (
  12480. (taicpu(hp1).oper[0]^.typ = top_const) or
  12481. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12482. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12483. ) then
  12484. begin
  12485. { change
  12486. movx %reg2,%reg2
  12487. op const,%reg2
  12488. into
  12489. op const,%reg2 (smaller version)
  12490. movx %reg2,%reg2
  12491. also change
  12492. movx %reg1,%reg2
  12493. and/test (oper),%reg2
  12494. dealloc %reg2
  12495. into
  12496. and/test (oper),%reg1
  12497. }
  12498. case taicpu(p).opsize of
  12499. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12500. begin
  12501. NewSize := S_B;
  12502. NewRegSize := R_SUBL;
  12503. Limit := $FF;
  12504. end;
  12505. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12506. begin
  12507. NewSize := S_W;
  12508. NewRegSize := R_SUBW;
  12509. Limit := $FFFF;
  12510. end;
  12511. {$ifdef x86_64}
  12512. S_LQ:
  12513. begin
  12514. NewSize := S_L;
  12515. NewRegSize := R_SUBD;
  12516. Limit := $FFFFFFFF;
  12517. end;
  12518. {$endif x86_64}
  12519. else
  12520. Internalerror(2021120302);
  12521. end;
  12522. TransferUsedRegs(TmpUsedRegs);
  12523. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12524. if AndTest then
  12525. begin
  12526. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12527. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12528. end
  12529. else
  12530. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12531. if
  12532. (
  12533. (taicpu(p).opcode = A_MOVZX) and
  12534. (
  12535. (taicpu(hp1).opcode=A_AND) or
  12536. (taicpu(hp1).opcode=A_TEST)
  12537. ) and
  12538. not (
  12539. { If both are references, then the final instruction will have
  12540. both operands as references, which is not allowed }
  12541. (taicpu(p).oper[0]^.typ = top_ref) and
  12542. (taicpu(hp1).oper[0]^.typ = top_ref)
  12543. ) and
  12544. not RegUsed
  12545. ) or
  12546. (
  12547. (
  12548. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  12549. not RegUsed
  12550. ) and
  12551. (taicpu(p).oper[0]^.typ = top_reg) and
  12552. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12553. (taicpu(hp1).oper[0]^.typ = top_const) and
  12554. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12555. ) then
  12556. begin
  12557. {$if defined(i386) or defined(i8086)}
  12558. { If the target size is 8-bit, make sure we can actually encode it }
  12559. 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
  12560. Exit;
  12561. {$endif i386 or i8086}
  12562. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12563. taicpu(hp1).opsize := NewSize;
  12564. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12565. if AndTest then
  12566. begin
  12567. RemoveInstruction(hp2);
  12568. if not RegUsed then
  12569. begin
  12570. taicpu(hp1).opcode := A_TEST;
  12571. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12572. begin
  12573. { Make sure the reference is the second operand }
  12574. SwapOper := taicpu(hp1).oper[0];
  12575. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12576. taicpu(hp1).oper[1] := SwapOper;
  12577. end;
  12578. end;
  12579. end;
  12580. case taicpu(hp1).oper[0]^.typ of
  12581. top_reg:
  12582. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12583. top_const:
  12584. { For the AND/TEST case }
  12585. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12586. else
  12587. ;
  12588. end;
  12589. if RegUsed then
  12590. begin
  12591. AsmL.Remove(p);
  12592. AsmL.InsertAfter(p, hp1);
  12593. p := hp1;
  12594. end
  12595. else
  12596. RemoveCurrentP(p, hp1);
  12597. result:=true;
  12598. exit;
  12599. end;
  12600. end;
  12601. end;
  12602. if reg_and_hp1_is_instr and
  12603. (taicpu(p).oper[0]^.typ = top_reg) and
  12604. (
  12605. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12606. ) and
  12607. (taicpu(hp1).oper[0]^.typ = top_const) and
  12608. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12609. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12610. { Minimum shift value allowed is the bit difference between the sizes }
  12611. (taicpu(hp1).oper[0]^.val >=
  12612. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12613. 8 * (
  12614. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12615. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12616. )
  12617. ) then
  12618. begin
  12619. { For:
  12620. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12621. shl/sal ##, %reg1
  12622. Remove the movsx/movzx instruction if the shift overwrites the
  12623. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12624. }
  12625. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12626. RemoveCurrentP(p, hp1);
  12627. Result := True;
  12628. Exit;
  12629. end
  12630. else if reg_and_hp1_is_instr and
  12631. (taicpu(p).oper[0]^.typ = top_reg) and
  12632. (
  12633. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12634. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12635. ) and
  12636. (taicpu(hp1).oper[0]^.typ = top_const) and
  12637. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12638. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12639. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12640. (taicpu(hp1).oper[0]^.val <
  12641. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12642. 8 * (
  12643. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12644. )
  12645. ) then
  12646. begin
  12647. { For:
  12648. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12649. sar ##, %reg1 shr ##, %reg1
  12650. Move the shift to before the movx instruction if the shift value
  12651. is not too large.
  12652. }
  12653. asml.Remove(hp1);
  12654. asml.InsertBefore(hp1, p);
  12655. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12656. case taicpu(p).opsize of
  12657. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12658. taicpu(hp1).opsize := S_B;
  12659. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12660. taicpu(hp1).opsize := S_W;
  12661. {$ifdef x86_64}
  12662. S_LQ:
  12663. taicpu(hp1).opsize := S_L;
  12664. {$endif}
  12665. else
  12666. InternalError(2020112401);
  12667. end;
  12668. if (taicpu(hp1).opcode = A_SHR) then
  12669. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12670. else
  12671. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12672. Result := True;
  12673. end;
  12674. if reg_and_hp1_is_instr and
  12675. (taicpu(p).oper[0]^.typ = top_reg) and
  12676. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12677. (
  12678. (taicpu(hp1).opcode = taicpu(p).opcode)
  12679. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12680. {$ifdef x86_64}
  12681. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12682. {$endif x86_64}
  12683. ) then
  12684. begin
  12685. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12686. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12687. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12688. begin
  12689. {
  12690. For example:
  12691. movzbw %al,%ax
  12692. movzwl %ax,%eax
  12693. Compress into:
  12694. movzbl %al,%eax
  12695. }
  12696. RegUsed := False;
  12697. case taicpu(p).opsize of
  12698. S_BW:
  12699. case taicpu(hp1).opsize of
  12700. S_WL:
  12701. begin
  12702. taicpu(p).opsize := S_BL;
  12703. RegUsed := True;
  12704. end;
  12705. {$ifdef x86_64}
  12706. S_WQ:
  12707. begin
  12708. if taicpu(p).opcode = A_MOVZX then
  12709. begin
  12710. taicpu(p).opsize := S_BL;
  12711. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12712. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12713. end
  12714. else
  12715. taicpu(p).opsize := S_BQ;
  12716. RegUsed := True;
  12717. end;
  12718. {$endif x86_64}
  12719. else
  12720. ;
  12721. end;
  12722. {$ifdef x86_64}
  12723. S_BL:
  12724. case taicpu(hp1).opsize of
  12725. S_LQ:
  12726. begin
  12727. if taicpu(p).opcode = A_MOVZX then
  12728. begin
  12729. taicpu(p).opsize := S_BL;
  12730. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12731. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12732. end
  12733. else
  12734. taicpu(p).opsize := S_BQ;
  12735. RegUsed := True;
  12736. end;
  12737. else
  12738. ;
  12739. end;
  12740. S_WL:
  12741. case taicpu(hp1).opsize of
  12742. S_LQ:
  12743. begin
  12744. if taicpu(p).opcode = A_MOVZX then
  12745. begin
  12746. taicpu(p).opsize := S_WL;
  12747. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12748. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12749. end
  12750. else
  12751. taicpu(p).opsize := S_WQ;
  12752. RegUsed := True;
  12753. end;
  12754. else
  12755. ;
  12756. end;
  12757. {$endif x86_64}
  12758. else
  12759. ;
  12760. end;
  12761. if RegUsed then
  12762. begin
  12763. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12764. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12765. RemoveInstruction(hp1);
  12766. Result := True;
  12767. Exit;
  12768. end;
  12769. end;
  12770. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12771. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12772. GetNextInstruction(hp1, hp2) and
  12773. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12774. (
  12775. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12776. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12777. {$ifdef x86_64}
  12778. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12779. {$endif x86_64}
  12780. ) and
  12781. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12782. (
  12783. (
  12784. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12785. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12786. ) or
  12787. (
  12788. { Only allow the operands in reverse order for TEST instructions }
  12789. (taicpu(hp2).opcode = A_TEST) and
  12790. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12791. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12792. )
  12793. ) then
  12794. begin
  12795. {
  12796. For example:
  12797. movzbl %al,%eax
  12798. movzbl (ref),%edx
  12799. andl %edx,%eax
  12800. (%edx deallocated)
  12801. Change to:
  12802. andb (ref),%al
  12803. movzbl %al,%eax
  12804. Rules are:
  12805. - First two instructions have the same opcode and opsize
  12806. - First instruction's operands are the same super-register
  12807. - Second instruction operates on a different register
  12808. - Third instruction is AND, OR, XOR or TEST
  12809. - Third instruction's operands are the destination registers of the first two instructions
  12810. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12811. - Second instruction's destination register is deallocated afterwards
  12812. }
  12813. TransferUsedRegs(TmpUsedRegs);
  12814. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12815. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12816. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12817. begin
  12818. case taicpu(p).opsize of
  12819. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12820. NewSize := S_B;
  12821. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12822. NewSize := S_W;
  12823. {$ifdef x86_64}
  12824. S_LQ:
  12825. NewSize := S_L;
  12826. {$endif x86_64}
  12827. else
  12828. InternalError(2021120301);
  12829. end;
  12830. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12831. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12832. taicpu(hp2).opsize := NewSize;
  12833. RemoveInstruction(hp1);
  12834. { With TEST, it's best to keep the MOVX instruction at the top }
  12835. if (taicpu(hp2).opcode <> A_TEST) then
  12836. begin
  12837. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12838. asml.Remove(p);
  12839. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12840. asml.InsertAfter(p, hp2);
  12841. p := hp2;
  12842. end
  12843. else
  12844. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12845. Result := True;
  12846. Exit;
  12847. end;
  12848. end;
  12849. end;
  12850. if taicpu(p).opcode=A_MOVZX then
  12851. begin
  12852. { removes superfluous And's after movzx's }
  12853. if reg_and_hp1_is_instr and
  12854. (taicpu(hp1).opcode = A_AND) and
  12855. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12856. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12857. {$ifdef x86_64}
  12858. { check for implicit extension to 64 bit }
  12859. or
  12860. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12861. (taicpu(hp1).opsize=S_Q) and
  12862. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12863. )
  12864. {$endif x86_64}
  12865. )
  12866. then
  12867. begin
  12868. case taicpu(p).opsize Of
  12869. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12870. if (taicpu(hp1).oper[0]^.val = $ff) then
  12871. begin
  12872. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12873. RemoveInstruction(hp1);
  12874. Result:=true;
  12875. exit;
  12876. end;
  12877. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12878. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12879. begin
  12880. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12881. RemoveInstruction(hp1);
  12882. Result:=true;
  12883. exit;
  12884. end;
  12885. {$ifdef x86_64}
  12886. S_LQ:
  12887. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12888. begin
  12889. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12890. RemoveInstruction(hp1);
  12891. Result:=true;
  12892. exit;
  12893. end;
  12894. {$endif x86_64}
  12895. else
  12896. ;
  12897. end;
  12898. { we cannot get rid of the and, but can we get rid of the movz ?}
  12899. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12900. begin
  12901. case taicpu(p).opsize Of
  12902. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12903. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12904. begin
  12905. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12906. RemoveCurrentP(p,hp1);
  12907. Result:=true;
  12908. exit;
  12909. end;
  12910. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12911. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12912. begin
  12913. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12914. RemoveCurrentP(p,hp1);
  12915. Result:=true;
  12916. exit;
  12917. end;
  12918. {$ifdef x86_64}
  12919. S_LQ:
  12920. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12921. begin
  12922. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12923. RemoveCurrentP(p,hp1);
  12924. Result:=true;
  12925. exit;
  12926. end;
  12927. {$endif x86_64}
  12928. else
  12929. ;
  12930. end;
  12931. end;
  12932. end;
  12933. { changes some movzx constructs to faster synonyms (all examples
  12934. are given with eax/ax, but are also valid for other registers)}
  12935. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12936. begin
  12937. case taicpu(p).opsize of
  12938. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12939. (the machine code is equivalent to movzbl %al,%eax), but the
  12940. code generator still generates that assembler instruction and
  12941. it is silently converted. This should probably be checked.
  12942. [Kit] }
  12943. S_BW:
  12944. begin
  12945. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12946. (
  12947. not IsMOVZXAcceptable
  12948. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12949. or (
  12950. (cs_opt_size in current_settings.optimizerswitches) and
  12951. (taicpu(p).oper[1]^.reg = NR_AX)
  12952. )
  12953. ) then
  12954. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12955. begin
  12956. DebugMsg(SPeepholeOptimization + 'var7',p);
  12957. taicpu(p).opcode := A_AND;
  12958. taicpu(p).changeopsize(S_W);
  12959. taicpu(p).loadConst(0,$ff);
  12960. Result := True;
  12961. end
  12962. else if not IsMOVZXAcceptable and
  12963. GetNextInstruction(p, hp1) and
  12964. (tai(hp1).typ = ait_instruction) and
  12965. (taicpu(hp1).opcode = A_AND) and
  12966. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12967. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12968. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12969. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12970. begin
  12971. DebugMsg(SPeepholeOptimization + 'var8',p);
  12972. taicpu(p).opcode := A_MOV;
  12973. taicpu(p).changeopsize(S_W);
  12974. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12975. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12976. Result := True;
  12977. end;
  12978. end;
  12979. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12980. S_BL:
  12981. if not IsMOVZXAcceptable then
  12982. begin
  12983. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12984. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12985. begin
  12986. DebugMsg(SPeepholeOptimization + 'var9',p);
  12987. taicpu(p).opcode := A_AND;
  12988. taicpu(p).changeopsize(S_L);
  12989. taicpu(p).loadConst(0,$ff);
  12990. Result := True;
  12991. end
  12992. else if GetNextInstruction(p, hp1) and
  12993. (tai(hp1).typ = ait_instruction) and
  12994. (taicpu(hp1).opcode = A_AND) and
  12995. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12996. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12997. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12998. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12999. begin
  13000. DebugMsg(SPeepholeOptimization + 'var10',p);
  13001. taicpu(p).opcode := A_MOV;
  13002. taicpu(p).changeopsize(S_L);
  13003. { do not use R_SUBWHOLE
  13004. as movl %rdx,%eax
  13005. is invalid in assembler PM }
  13006. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13007. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13008. Result := True;
  13009. end;
  13010. end;
  13011. {$endif i8086}
  13012. S_WL:
  13013. if not IsMOVZXAcceptable then
  13014. begin
  13015. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13016. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13017. begin
  13018. DebugMsg(SPeepholeOptimization + 'var11',p);
  13019. taicpu(p).opcode := A_AND;
  13020. taicpu(p).changeopsize(S_L);
  13021. taicpu(p).loadConst(0,$ffff);
  13022. Result := True;
  13023. end
  13024. else if GetNextInstruction(p, hp1) and
  13025. (tai(hp1).typ = ait_instruction) and
  13026. (taicpu(hp1).opcode = A_AND) and
  13027. (taicpu(hp1).oper[0]^.typ = top_const) and
  13028. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13029. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13030. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13031. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13032. begin
  13033. DebugMsg(SPeepholeOptimization + 'var12',p);
  13034. taicpu(p).opcode := A_MOV;
  13035. taicpu(p).changeopsize(S_L);
  13036. { do not use R_SUBWHOLE
  13037. as movl %rdx,%eax
  13038. is invalid in assembler PM }
  13039. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13040. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13041. Result := True;
  13042. end;
  13043. end;
  13044. else
  13045. InternalError(2017050705);
  13046. end;
  13047. end
  13048. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13049. begin
  13050. if GetNextInstruction(p, hp1) and
  13051. (tai(hp1).typ = ait_instruction) and
  13052. (taicpu(hp1).opcode = A_AND) and
  13053. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13054. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13055. begin
  13056. //taicpu(p).opcode := A_MOV;
  13057. case taicpu(p).opsize Of
  13058. S_BL:
  13059. begin
  13060. DebugMsg(SPeepholeOptimization + 'var13',p);
  13061. taicpu(hp1).changeopsize(S_L);
  13062. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13063. end;
  13064. S_WL:
  13065. begin
  13066. DebugMsg(SPeepholeOptimization + 'var14',p);
  13067. taicpu(hp1).changeopsize(S_L);
  13068. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13069. end;
  13070. S_BW:
  13071. begin
  13072. DebugMsg(SPeepholeOptimization + 'var15',p);
  13073. taicpu(hp1).changeopsize(S_W);
  13074. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13075. end;
  13076. else
  13077. Internalerror(2017050704)
  13078. end;
  13079. Result := True;
  13080. end;
  13081. end;
  13082. end;
  13083. end;
  13084. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13085. var
  13086. hp1, hp2 : tai;
  13087. MaskLength : Cardinal;
  13088. MaskedBits : TCgInt;
  13089. ActiveReg : TRegister;
  13090. begin
  13091. Result:=false;
  13092. { There are no optimisations for reference targets }
  13093. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13094. Exit;
  13095. while GetNextInstruction(p, hp1) and
  13096. (hp1.typ = ait_instruction) do
  13097. begin
  13098. if (taicpu(p).oper[0]^.typ = top_const) then
  13099. begin
  13100. case taicpu(hp1).opcode of
  13101. A_AND:
  13102. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13103. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13104. { the second register must contain the first one, so compare their subreg types }
  13105. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13106. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13107. { change
  13108. and const1, reg
  13109. and const2, reg
  13110. to
  13111. and (const1 and const2), reg
  13112. }
  13113. begin
  13114. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13115. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13116. RemoveCurrentP(p, hp1);
  13117. Result:=true;
  13118. exit;
  13119. end;
  13120. A_CMP:
  13121. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13122. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13123. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13124. { Just check that the condition on the next instruction is compatible }
  13125. GetNextInstruction(hp1, hp2) and
  13126. (hp2.typ = ait_instruction) and
  13127. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13128. then
  13129. { change
  13130. and 2^n, reg
  13131. cmp 2^n, reg
  13132. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13133. to
  13134. and 2^n, reg
  13135. test reg, reg
  13136. j(~c) / set(~c) / cmov(~c)
  13137. }
  13138. begin
  13139. { Keep TEST instruction in, rather than remove it, because
  13140. it may trigger other optimisations such as MovAndTest2Test }
  13141. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13142. taicpu(hp1).opcode := A_TEST;
  13143. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13144. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13145. Result := True;
  13146. Exit;
  13147. end
  13148. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13149. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13150. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13151. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13152. { change
  13153. and $ff/$ff/$ffff, reg
  13154. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13155. dealloc reg
  13156. to
  13157. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13158. }
  13159. begin
  13160. TransferUsedRegs(TmpUsedRegs);
  13161. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13162. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13163. begin
  13164. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13165. case taicpu(p).oper[0]^.val of
  13166. $ff:
  13167. begin
  13168. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13169. taicpu(hp1).opsize:=S_B;
  13170. end;
  13171. $ffff:
  13172. begin
  13173. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13174. taicpu(hp1).opsize:=S_W;
  13175. end;
  13176. $ffffffff:
  13177. begin
  13178. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13179. taicpu(hp1).opsize:=S_L;
  13180. end;
  13181. else
  13182. Internalerror(2023030401);
  13183. end;
  13184. RemoveCurrentP(p);
  13185. Result := True;
  13186. Exit;
  13187. end;
  13188. end;
  13189. A_MOVZX:
  13190. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13191. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13192. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13193. (
  13194. (
  13195. (taicpu(p).opsize=S_W) and
  13196. (taicpu(hp1).opsize=S_BW)
  13197. ) or
  13198. (
  13199. (taicpu(p).opsize=S_L) and
  13200. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13201. )
  13202. {$ifdef x86_64}
  13203. or
  13204. (
  13205. (taicpu(p).opsize=S_Q) and
  13206. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13207. )
  13208. {$endif x86_64}
  13209. ) then
  13210. begin
  13211. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13212. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13213. ) or
  13214. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13215. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13216. then
  13217. begin
  13218. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13219. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13220. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13221. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13222. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13223. }
  13224. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13225. RemoveInstruction(hp1);
  13226. { See if there are other optimisations possible }
  13227. Continue;
  13228. end;
  13229. end;
  13230. A_SHL:
  13231. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13232. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13233. begin
  13234. {$ifopt R+}
  13235. {$define RANGE_WAS_ON}
  13236. {$R-}
  13237. {$endif}
  13238. { get length of potential and mask }
  13239. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13240. { really a mask? }
  13241. {$ifdef RANGE_WAS_ON}
  13242. {$R+}
  13243. {$endif}
  13244. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13245. { unmasked part shifted out? }
  13246. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13247. begin
  13248. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13249. RemoveCurrentP(p, hp1);
  13250. Result:=true;
  13251. exit;
  13252. end;
  13253. end;
  13254. A_SHR:
  13255. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13256. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13257. (taicpu(hp1).oper[0]^.val <= 63) then
  13258. begin
  13259. { Does SHR combined with the AND cover all the bits?
  13260. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13261. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13262. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13263. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13264. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13265. begin
  13266. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13267. RemoveCurrentP(p, hp1);
  13268. Result := True;
  13269. Exit;
  13270. end;
  13271. end;
  13272. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13273. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13274. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13275. begin
  13276. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13277. (
  13278. (
  13279. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13280. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13281. ) or (
  13282. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13283. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13284. {$ifdef x86_64}
  13285. ) or (
  13286. (taicpu(hp1).opsize = S_LQ) and
  13287. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13288. {$endif x86_64}
  13289. )
  13290. ) then
  13291. begin
  13292. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13293. begin
  13294. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13295. RemoveInstruction(hp1);
  13296. { See if there are other optimisations possible }
  13297. Continue;
  13298. end;
  13299. { The super-registers are the same though.
  13300. Note that this change by itself doesn't improve
  13301. code speed, but it opens up other optimisations. }
  13302. {$ifdef x86_64}
  13303. { Convert 64-bit register to 32-bit }
  13304. case taicpu(hp1).opsize of
  13305. S_BQ:
  13306. begin
  13307. taicpu(hp1).opsize := S_BL;
  13308. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13309. end;
  13310. S_WQ:
  13311. begin
  13312. taicpu(hp1).opsize := S_WL;
  13313. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13314. end
  13315. else
  13316. ;
  13317. end;
  13318. {$endif x86_64}
  13319. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13320. taicpu(hp1).opcode := A_MOVZX;
  13321. { See if there are other optimisations possible }
  13322. Continue;
  13323. end;
  13324. end;
  13325. else
  13326. ;
  13327. end;
  13328. end
  13329. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13330. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13331. begin
  13332. {$ifdef x86_64}
  13333. if (taicpu(p).opsize = S_Q) then
  13334. begin
  13335. { Never necessary }
  13336. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13337. RemoveCurrentP(p, hp1);
  13338. Result := True;
  13339. Exit;
  13340. end;
  13341. {$endif x86_64}
  13342. { Forward check to determine necessity of and %reg,%reg }
  13343. TransferUsedRegs(TmpUsedRegs);
  13344. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13345. { Saves on a bunch of dereferences }
  13346. ActiveReg := taicpu(p).oper[1]^.reg;
  13347. case taicpu(hp1).opcode of
  13348. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13349. if (
  13350. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13351. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13352. ) and
  13353. (
  13354. (taicpu(hp1).opcode <> A_MOV) or
  13355. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13356. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13357. ) and
  13358. not (
  13359. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13360. (taicpu(hp1).opcode = A_MOV) and
  13361. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13362. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13363. ) and
  13364. (
  13365. (
  13366. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13367. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13368. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13369. ) or
  13370. (
  13371. {$ifdef x86_64}
  13372. (
  13373. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13374. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13375. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13376. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13377. ) and
  13378. {$endif x86_64}
  13379. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13380. )
  13381. ) then
  13382. begin
  13383. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13384. RemoveCurrentP(p, hp1);
  13385. Result := True;
  13386. Exit;
  13387. end;
  13388. A_ADD,
  13389. A_AND,
  13390. A_BSF,
  13391. A_BSR,
  13392. A_BTC,
  13393. A_BTR,
  13394. A_BTS,
  13395. A_OR,
  13396. A_SUB,
  13397. A_XOR:
  13398. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13399. if (
  13400. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13401. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13402. ) and
  13403. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13404. begin
  13405. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13406. RemoveCurrentP(p, hp1);
  13407. Result := True;
  13408. Exit;
  13409. end;
  13410. A_CMP,
  13411. A_TEST:
  13412. if (
  13413. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13414. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13415. ) and
  13416. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13417. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13418. begin
  13419. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13420. RemoveCurrentP(p, hp1);
  13421. Result := True;
  13422. Exit;
  13423. end;
  13424. A_BSWAP,
  13425. A_NEG,
  13426. A_NOT:
  13427. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13428. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13429. begin
  13430. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13431. RemoveCurrentP(p, hp1);
  13432. Result := True;
  13433. Exit;
  13434. end;
  13435. else
  13436. ;
  13437. end;
  13438. end;
  13439. if (taicpu(hp1).is_jmp) and
  13440. (taicpu(hp1).opcode<>A_JMP) and
  13441. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13442. begin
  13443. { change
  13444. and x, reg
  13445. jxx
  13446. to
  13447. test x, reg
  13448. jxx
  13449. if reg is deallocated before the
  13450. jump, but only if it's a conditional jump (PFV)
  13451. }
  13452. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13453. taicpu(p).opcode := A_TEST;
  13454. Exit;
  13455. end;
  13456. Break;
  13457. end;
  13458. { Lone AND tests }
  13459. if (taicpu(p).oper[0]^.typ = top_const) then
  13460. begin
  13461. {
  13462. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13463. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13464. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13465. }
  13466. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13467. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13468. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13469. begin
  13470. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13471. if taicpu(p).opsize = S_L then
  13472. begin
  13473. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13474. Result := True;
  13475. end;
  13476. end;
  13477. end;
  13478. { Backward check to determine necessity of and %reg,%reg }
  13479. if (taicpu(p).oper[0]^.typ = top_reg) and
  13480. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13481. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13482. GetLastInstruction(p, hp2) and
  13483. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13484. { Check size of adjacent instruction to determine if the AND is
  13485. effectively a null operation }
  13486. (
  13487. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13488. { Note: Don't include S_Q }
  13489. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13490. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13491. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13492. ) then
  13493. begin
  13494. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13495. { If GetNextInstruction returned False, hp1 will be nil }
  13496. RemoveCurrentP(p, hp1);
  13497. Result := True;
  13498. Exit;
  13499. end;
  13500. end;
  13501. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  13502. var
  13503. hp1, hp2: tai;
  13504. NewRef: TReference;
  13505. Distance: Cardinal;
  13506. TempTracking: TAllUsedRegs;
  13507. { This entire nested function is used in an if-statement below, but we
  13508. want to avoid all the used reg transfers and GetNextInstruction calls
  13509. until we really have to check }
  13510. function MemRegisterNotUsedLater: Boolean; inline;
  13511. var
  13512. hp2: tai;
  13513. begin
  13514. TransferUsedRegs(TmpUsedRegs);
  13515. hp2 := p;
  13516. repeat
  13517. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13518. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13519. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13520. end;
  13521. begin
  13522. Result := False;
  13523. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13524. (taicpu(p).oper[1]^.typ = top_reg) then
  13525. begin
  13526. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13527. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13528. (hp1.typ <> ait_instruction) or
  13529. not
  13530. (
  13531. (cs_opt_level3 in current_settings.optimizerswitches) or
  13532. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13533. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13534. ) then
  13535. Exit;
  13536. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13537. addq $x, %rax
  13538. movq %rax, %rdx
  13539. sarq $63, %rdx
  13540. (%rax still in use)
  13541. ...letting OptPass2ADD run its course (and without -Os) will produce:
  13542. leaq $x(%rax),%rdx
  13543. addq $x, %rax
  13544. sarq $63, %rdx
  13545. ...which is okay since it breaks the dependency chain between
  13546. addq and movq, but if OptPass2MOV is called first:
  13547. addq $x, %rax
  13548. cqto
  13549. ...which is better in all ways, taking only 2 cycles to execute
  13550. and much smaller in code size.
  13551. }
  13552. { The extra register tracking is quite strenuous }
  13553. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13554. MatchInstruction(hp1, A_MOV, []) then
  13555. begin
  13556. { Update the register tracking to the MOV instruction }
  13557. CopyUsedRegs(TempTracking);
  13558. hp2 := p;
  13559. repeat
  13560. UpdateUsedRegs(tai(hp2.Next));
  13561. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13562. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13563. OptPass2ADD get called again }
  13564. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13565. begin
  13566. { Reset the tracking to the current instruction }
  13567. RestoreUsedRegs(TempTracking);
  13568. ReleaseUsedRegs(TempTracking);
  13569. Result := True;
  13570. Exit;
  13571. end;
  13572. { Reset the tracking to the current instruction }
  13573. RestoreUsedRegs(TempTracking);
  13574. ReleaseUsedRegs(TempTracking);
  13575. { If OptPass2MOV returned True, we don't need to set Result to
  13576. True if hp1 didn't change because the ADD instruction didn't
  13577. get modified and we'll be evaluating hp1 again when the
  13578. peephole optimizer reaches it }
  13579. end;
  13580. { Change:
  13581. add %reg2,%reg1
  13582. (%reg2 not modified in between)
  13583. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13584. To:
  13585. mov/s/z #(%reg1,%reg2),%reg1
  13586. }
  13587. if (taicpu(p).oper[0]^.typ = top_reg) and
  13588. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13589. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13590. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13591. (
  13592. (
  13593. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13594. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13595. { r/esp cannot be an index }
  13596. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13597. ) or (
  13598. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13599. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13600. )
  13601. ) and (
  13602. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13603. (
  13604. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13605. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13606. MemRegisterNotUsedLater
  13607. )
  13608. ) then
  13609. begin
  13610. if (
  13611. { Instructions are guaranteed to be adjacent on -O2 and under }
  13612. (cs_opt_level3 in current_settings.optimizerswitches) and
  13613. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13614. ) then
  13615. begin
  13616. { If the other register is used in between, move the MOV
  13617. instruction to right after the ADD instruction so a
  13618. saving can still be made }
  13619. Asml.Remove(hp1);
  13620. Asml.InsertAfter(hp1, p);
  13621. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13622. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13623. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13624. RemoveCurrentp(p, hp1);
  13625. end
  13626. else
  13627. begin
  13628. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13629. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13630. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13631. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13632. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13633. { hp1 may not be the immediate next instruction under -O3 }
  13634. RemoveCurrentp(p)
  13635. else
  13636. RemoveCurrentp(p, hp1);
  13637. end;
  13638. Result := True;
  13639. Exit;
  13640. end;
  13641. { Change:
  13642. addl/q $x,%reg1
  13643. movl/q %reg1,%reg2
  13644. To:
  13645. leal/q $x(%reg1),%reg2
  13646. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13647. Breaks the dependency chain.
  13648. }
  13649. if (taicpu(p).oper[0]^.typ = top_const) and
  13650. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13651. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13652. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13653. (
  13654. { Instructions are guaranteed to be adjacent on -O2 and under }
  13655. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13656. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13657. ) then
  13658. begin
  13659. TransferUsedRegs(TmpUsedRegs);
  13660. hp2 := p;
  13661. repeat
  13662. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13663. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13664. if (
  13665. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13666. not (cs_opt_size in current_settings.optimizerswitches) or
  13667. (
  13668. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13669. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13670. )
  13671. ) then
  13672. begin
  13673. { Change the MOV instruction to a LEA instruction, and update the
  13674. first operand }
  13675. reference_reset(NewRef, 1, []);
  13676. NewRef.base := taicpu(p).oper[1]^.reg;
  13677. NewRef.scalefactor := 1;
  13678. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13679. taicpu(hp1).opcode := A_LEA;
  13680. taicpu(hp1).loadref(0, NewRef);
  13681. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13682. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13683. begin
  13684. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13685. { Move what is now the LEA instruction to before the ADD instruction }
  13686. Asml.Remove(hp1);
  13687. Asml.InsertBefore(hp1, p);
  13688. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13689. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13690. p := hp1;
  13691. end
  13692. else
  13693. begin
  13694. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13695. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13696. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13697. { hp1 may not be the immediate next instruction under -O3 }
  13698. RemoveCurrentp(p)
  13699. else
  13700. RemoveCurrentp(p, hp1);
  13701. end;
  13702. Result := True;
  13703. end;
  13704. end;
  13705. end;
  13706. end;
  13707. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13708. var
  13709. SubReg: TSubRegister;
  13710. hp1, hp2: tai;
  13711. CallJmp: Boolean;
  13712. begin
  13713. Result := False;
  13714. CallJmp := False;
  13715. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13716. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13717. with taicpu(p).oper[0]^.ref^ do
  13718. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13719. if (offset = 0) then
  13720. begin
  13721. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13722. begin
  13723. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13724. taicpu(p).opcode := A_ADD;
  13725. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13726. Result := True;
  13727. end
  13728. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13729. begin
  13730. if (base <> NR_NO) then
  13731. begin
  13732. if (scalefactor <= 1) then
  13733. begin
  13734. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13735. taicpu(p).opcode := A_ADD;
  13736. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13737. Result := True;
  13738. end;
  13739. end
  13740. else
  13741. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13742. if (scalefactor in [2, 4, 8]) then
  13743. begin
  13744. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13745. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13746. taicpu(p).opcode := A_SHL;
  13747. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13748. Result := True;
  13749. end;
  13750. end;
  13751. end
  13752. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  13753. lot of latency, so break off the offset if %reg3 is used soon
  13754. afterwards }
  13755. else if not (cs_opt_size in current_settings.optimizerswitches) and
  13756. { If 3-component addresses don't have additional latency, don't
  13757. perform this optimisation }
  13758. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  13759. GetNextInstruction(p, hp1) and
  13760. (
  13761. (
  13762. { Permit jumps and calls since they have a larger degree of overhead }
  13763. (
  13764. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  13765. (
  13766. { ... unless the register specifies the location }
  13767. (taicpu(hp1).ops > 0) and
  13768. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13769. )
  13770. ) and
  13771. (
  13772. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  13773. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13774. )
  13775. )
  13776. or
  13777. (
  13778. { Check up to two instructions ahead }
  13779. GetNextInstruction(hp1, hp2) and
  13780. (
  13781. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  13782. (
  13783. { Same as above }
  13784. (taicpu(hp2).ops > 0) and
  13785. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  13786. )
  13787. ) and
  13788. (
  13789. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  13790. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  13791. )
  13792. )
  13793. ) then
  13794. begin
  13795. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  13796. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  13797. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  13798. offset := 0;
  13799. if Assigned(symbol) or Assigned(relsymbol) then
  13800. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  13801. else
  13802. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  13803. { Inserting before the next instruction rather than after the
  13804. current instruction gives more accurate register tracking }
  13805. asml.InsertBefore(hp2, hp1);
  13806. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  13807. Result := True;
  13808. end;
  13809. end;
  13810. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13811. var
  13812. hp1, hp2: tai;
  13813. NewRef: TReference;
  13814. Distance: Cardinal;
  13815. TempTracking: TAllUsedRegs;
  13816. begin
  13817. Result := False;
  13818. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13819. MatchOpType(taicpu(p),top_const,top_reg) then
  13820. begin
  13821. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13822. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13823. (hp1.typ <> ait_instruction) or
  13824. not
  13825. (
  13826. (cs_opt_level3 in current_settings.optimizerswitches) or
  13827. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13828. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13829. ) then
  13830. Exit;
  13831. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13832. subq $x, %rax
  13833. movq %rax, %rdx
  13834. sarq $63, %rdx
  13835. (%rax still in use)
  13836. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13837. leaq $-x(%rax),%rdx
  13838. movq $x, %rax
  13839. sarq $63, %rdx
  13840. ...which is okay since it breaks the dependency chain between
  13841. subq and movq, but if OptPass2MOV is called first:
  13842. subq $x, %rax
  13843. cqto
  13844. ...which is better in all ways, taking only 2 cycles to execute
  13845. and much smaller in code size.
  13846. }
  13847. { The extra register tracking is quite strenuous }
  13848. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13849. MatchInstruction(hp1, A_MOV, []) then
  13850. begin
  13851. { Update the register tracking to the MOV instruction }
  13852. CopyUsedRegs(TempTracking);
  13853. hp2 := p;
  13854. repeat
  13855. UpdateUsedRegs(tai(hp2.Next));
  13856. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13857. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13858. OptPass2SUB get called again }
  13859. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13860. begin
  13861. { Reset the tracking to the current instruction }
  13862. RestoreUsedRegs(TempTracking);
  13863. ReleaseUsedRegs(TempTracking);
  13864. Result := True;
  13865. Exit;
  13866. end;
  13867. { Reset the tracking to the current instruction }
  13868. RestoreUsedRegs(TempTracking);
  13869. ReleaseUsedRegs(TempTracking);
  13870. { If OptPass2MOV returned True, we don't need to set Result to
  13871. True if hp1 didn't change because the SUB instruction didn't
  13872. get modified and we'll be evaluating hp1 again when the
  13873. peephole optimizer reaches it }
  13874. end;
  13875. { Change:
  13876. subl/q $x,%reg1
  13877. movl/q %reg1,%reg2
  13878. To:
  13879. leal/q $-x(%reg1),%reg2
  13880. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13881. Breaks the dependency chain and potentially permits the removal of
  13882. a CMP instruction if one follows.
  13883. }
  13884. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13885. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13886. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13887. (
  13888. { Instructions are guaranteed to be adjacent on -O2 and under }
  13889. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13890. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13891. ) then
  13892. begin
  13893. TransferUsedRegs(TmpUsedRegs);
  13894. hp2 := p;
  13895. repeat
  13896. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13897. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13898. if (
  13899. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13900. not (cs_opt_size in current_settings.optimizerswitches) or
  13901. (
  13902. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13903. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13904. )
  13905. ) then
  13906. begin
  13907. { Change the MOV instruction to a LEA instruction, and update the
  13908. first operand }
  13909. reference_reset(NewRef, 1, []);
  13910. NewRef.base := taicpu(p).oper[1]^.reg;
  13911. NewRef.scalefactor := 1;
  13912. NewRef.offset := -taicpu(p).oper[0]^.val;
  13913. taicpu(hp1).opcode := A_LEA;
  13914. taicpu(hp1).loadref(0, NewRef);
  13915. TransferUsedRegs(TmpUsedRegs);
  13916. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13917. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13918. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13919. begin
  13920. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13921. { Move what is now the LEA instruction to before the SUB instruction }
  13922. Asml.Remove(hp1);
  13923. Asml.InsertBefore(hp1, p);
  13924. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13925. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13926. p := hp1;
  13927. end
  13928. else
  13929. begin
  13930. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13931. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13932. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13933. { hp1 may not be the immediate next instruction under -O3 }
  13934. RemoveCurrentp(p)
  13935. else
  13936. RemoveCurrentp(p, hp1);
  13937. end;
  13938. Result := True;
  13939. end;
  13940. end;
  13941. end;
  13942. end;
  13943. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13944. begin
  13945. { we can skip all instructions not messing with the stack pointer }
  13946. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13947. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13948. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13949. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13950. ({(taicpu(hp1).ops=0) or }
  13951. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13952. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13953. ) and }
  13954. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13955. )
  13956. ) do
  13957. GetNextInstruction(hp1,hp1);
  13958. Result:=assigned(hp1);
  13959. end;
  13960. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13961. var
  13962. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  13963. begin
  13964. Result:=false;
  13965. hp5:=nil;
  13966. hp6:=nil;
  13967. hp7:=nil;
  13968. hp8:=nil;
  13969. { replace
  13970. leal(q) x(<stackpointer>),<stackpointer>
  13971. <optional .seh_stackalloc ...>
  13972. <optional .seh_endprologue ...>
  13973. call procname
  13974. <optional NOP>
  13975. leal(q) -x(<stackpointer>),<stackpointer>
  13976. <optional VZEROUPPER>
  13977. ret
  13978. by
  13979. jmp procname
  13980. but do it only on level 4 because it destroys stack back traces
  13981. }
  13982. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13983. MatchOpType(taicpu(p),top_ref,top_reg) and
  13984. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13985. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13986. { the -8, -24, -40 are not required, but bail out early if possible,
  13987. higher values are unlikely }
  13988. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13989. (taicpu(p).oper[0]^.ref^.offset=-24) or
  13990. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  13991. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13992. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13993. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13994. GetNextInstruction(p, hp1) and
  13995. { Take a copy of hp1 }
  13996. SetAndTest(hp1, hp4) and
  13997. { trick to skip label }
  13998. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  13999. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14000. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14001. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14002. SkipSimpleInstructions(hp1) and
  14003. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14004. GetNextInstruction(hp1, hp2) and
  14005. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14006. { skip nop instruction on win64 }
  14007. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14008. SetAndTest(hp2,hp6) and
  14009. GetNextInstruction(hp2,hp2) and
  14010. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14011. ) and
  14012. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14013. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14014. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14015. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14016. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14017. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14018. { Segment register will be NR_NO }
  14019. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14020. GetNextInstruction(hp2, hp3) and
  14021. { trick to skip label }
  14022. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14023. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14024. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14025. SetAndTest(hp3,hp5) and
  14026. GetNextInstruction(hp3,hp3) and
  14027. MatchInstruction(hp3,A_RET,[S_NO])
  14028. )
  14029. ) and
  14030. (taicpu(hp3).ops=0) then
  14031. begin
  14032. taicpu(hp1).opcode := A_JMP;
  14033. taicpu(hp1).is_jmp := true;
  14034. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14035. { search for the stackalloc directive and remove it }
  14036. hp7:=tai(p.next);
  14037. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14038. begin
  14039. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14040. begin
  14041. { sanity check }
  14042. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14043. Internalerror(2024012201);
  14044. hp8:=tai(hp7.next);
  14045. RemoveInstruction(tai(hp7));
  14046. hp7:=hp8;
  14047. break;
  14048. end
  14049. else
  14050. hp7:=tai(hp7.next);
  14051. end;
  14052. RemoveCurrentP(p, hp4);
  14053. RemoveInstruction(hp2);
  14054. RemoveInstruction(hp3);
  14055. { if there is a vzeroupper instruction then move it before the jmp }
  14056. if Assigned(hp5) then
  14057. begin
  14058. AsmL.Remove(hp5);
  14059. ASmL.InsertBefore(hp5,hp1)
  14060. end;
  14061. { remove nop on win64 }
  14062. if Assigned(hp6) then
  14063. RemoveInstruction(hp6);
  14064. Result:=true;
  14065. end;
  14066. end;
  14067. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14068. {$ifdef x86_64}
  14069. var
  14070. hp1, hp2, hp3, hp4, hp5: tai;
  14071. {$endif x86_64}
  14072. begin
  14073. Result:=false;
  14074. {$ifdef x86_64}
  14075. hp5:=nil;
  14076. { replace
  14077. push %rax
  14078. call procname
  14079. pop %rcx
  14080. ret
  14081. by
  14082. jmp procname
  14083. but do it only on level 4 because it destroys stack back traces
  14084. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14085. for all supported calling conventions
  14086. }
  14087. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14088. MatchOpType(taicpu(p),top_reg) and
  14089. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14090. GetNextInstruction(p, hp1) and
  14091. { Take a copy of hp1 }
  14092. SetAndTest(hp1, hp4) and
  14093. { trick to skip label }
  14094. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14095. SkipSimpleInstructions(hp1) and
  14096. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14097. GetNextInstruction(hp1, hp2) and
  14098. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14099. MatchOpType(taicpu(hp2),top_reg) and
  14100. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14101. GetNextInstruction(hp2, hp3) and
  14102. { trick to skip label }
  14103. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14104. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14105. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14106. SetAndTest(hp3,hp5) and
  14107. GetNextInstruction(hp3,hp3) and
  14108. MatchInstruction(hp3,A_RET,[S_NO])
  14109. )
  14110. ) and
  14111. (taicpu(hp3).ops=0) then
  14112. begin
  14113. taicpu(hp1).opcode := A_JMP;
  14114. taicpu(hp1).is_jmp := true;
  14115. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14116. RemoveCurrentP(p, hp4);
  14117. RemoveInstruction(hp2);
  14118. RemoveInstruction(hp3);
  14119. if Assigned(hp5) then
  14120. begin
  14121. AsmL.Remove(hp5);
  14122. ASmL.InsertBefore(hp5,hp1)
  14123. end;
  14124. Result:=true;
  14125. end;
  14126. {$endif x86_64}
  14127. end;
  14128. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14129. var
  14130. Value, RegName: string;
  14131. hp1: tai;
  14132. begin
  14133. Result:=false;
  14134. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14135. begin
  14136. case taicpu(p).oper[0]^.val of
  14137. 0:
  14138. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14139. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14140. (
  14141. { See if we can still convert the instruction }
  14142. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14143. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14144. ) then
  14145. begin
  14146. { change "mov $0,%reg" into "xor %reg,%reg" }
  14147. taicpu(p).opcode := A_XOR;
  14148. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14149. Result := True;
  14150. {$ifdef x86_64}
  14151. end
  14152. else if (taicpu(p).opsize = S_Q) then
  14153. begin
  14154. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14155. { The actual optimization }
  14156. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14157. taicpu(p).changeopsize(S_L);
  14158. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14159. Result := True;
  14160. end;
  14161. $1..$FFFFFFFF:
  14162. begin
  14163. { Code size reduction by J. Gareth "Kit" Moreton }
  14164. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14165. case taicpu(p).opsize of
  14166. S_Q:
  14167. begin
  14168. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14169. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14170. { The actual optimization }
  14171. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14172. taicpu(p).changeopsize(S_L);
  14173. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14174. Result := True;
  14175. end;
  14176. else
  14177. { Do nothing };
  14178. end;
  14179. {$endif x86_64}
  14180. end;
  14181. -1:
  14182. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14183. if (cs_opt_size in current_settings.optimizerswitches) and
  14184. (taicpu(p).opsize <> S_B) and
  14185. (
  14186. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14187. (
  14188. { See if we can still convert the instruction }
  14189. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14190. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14191. )
  14192. ) then
  14193. begin
  14194. { change "mov $-1,%reg" into "or $-1,%reg" }
  14195. { NOTES:
  14196. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14197. - This operation creates a false dependency on the register, so only do it when optimising for size
  14198. - 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
  14199. }
  14200. taicpu(p).opcode := A_OR;
  14201. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14202. Result := True;
  14203. end;
  14204. else
  14205. { Do nothing };
  14206. end;
  14207. end;
  14208. end;
  14209. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14210. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14211. begin
  14212. Result := False;
  14213. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14214. Exit;
  14215. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14216. so don't bother optimising }
  14217. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14218. Exit;
  14219. if (taicpu(p).oper[0]^.typ <> top_const) or
  14220. { If the value can fit into an 8-bit signed integer, a smaller
  14221. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14222. falls within this range }
  14223. (
  14224. (taicpu(p).oper[0]^.val > -128) and
  14225. (taicpu(p).oper[0]^.val <= 127)
  14226. ) then
  14227. Exit;
  14228. { If we're optimising for size, this is acceptable }
  14229. if (cs_opt_size in current_settings.optimizerswitches) then
  14230. Exit(True);
  14231. if (taicpu(p).oper[1]^.typ = top_reg) and
  14232. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14233. Exit(True);
  14234. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14235. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14236. Exit(True);
  14237. end;
  14238. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14239. var
  14240. hp1: tai;
  14241. Value: TCGInt;
  14242. begin
  14243. Result := False;
  14244. if MatchOpType(taicpu(p), top_const, top_reg) then
  14245. begin
  14246. { Detect:
  14247. andw x, %ax (0 <= x < $8000)
  14248. ...
  14249. movzwl %ax,%eax
  14250. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14251. }
  14252. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14253. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14254. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14255. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14256. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14257. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14258. begin
  14259. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14260. taicpu(hp1).opcode := A_CWDE;
  14261. taicpu(hp1).clearop(0);
  14262. taicpu(hp1).clearop(1);
  14263. taicpu(hp1).ops := 0;
  14264. { A change was made, but not with p, so don't set Result, but
  14265. notify the compiler that a change was made }
  14266. Include(OptsToCheck, aoc_ForceNewIteration);
  14267. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14268. end;
  14269. end;
  14270. { If "not x" is a power of 2 (popcnt = 1), change:
  14271. and $x, %reg/ref
  14272. To:
  14273. btr lb(x), %reg/ref
  14274. }
  14275. if IsBTXAcceptable(p) and
  14276. (
  14277. { Make sure a TEST doesn't follow that plays with the register }
  14278. not GetNextInstruction(p, hp1) or
  14279. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14280. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14281. ) then
  14282. begin
  14283. {$push}{$R-}{$Q-}
  14284. { Value is a sign-extended 32-bit integer - just correct it
  14285. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14286. checks to see if this operand is an immediate. }
  14287. Value := not taicpu(p).oper[0]^.val;
  14288. {$pop}
  14289. {$ifdef x86_64}
  14290. if taicpu(p).opsize = S_L then
  14291. {$endif x86_64}
  14292. Value := Value and $FFFFFFFF;
  14293. if (PopCnt(QWord(Value)) = 1) then
  14294. begin
  14295. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14296. taicpu(p).opcode := A_BTR;
  14297. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14298. Result := True;
  14299. Exit;
  14300. end;
  14301. end;
  14302. end;
  14303. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14304. begin
  14305. Result := False;
  14306. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14307. Exit;
  14308. { Convert:
  14309. movswl %ax,%eax -> cwtl
  14310. movslq %eax,%rax -> cdqe
  14311. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14312. refer to the same opcode and depends only on the assembler's
  14313. current operand-size attribute. [Kit]
  14314. }
  14315. with taicpu(p) do
  14316. case opsize of
  14317. S_WL:
  14318. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14319. begin
  14320. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14321. opcode := A_CWDE;
  14322. clearop(0);
  14323. clearop(1);
  14324. ops := 0;
  14325. Result := True;
  14326. end;
  14327. {$ifdef x86_64}
  14328. S_LQ:
  14329. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14330. begin
  14331. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14332. opcode := A_CDQE;
  14333. clearop(0);
  14334. clearop(1);
  14335. ops := 0;
  14336. Result := True;
  14337. end;
  14338. {$endif x86_64}
  14339. else
  14340. ;
  14341. end;
  14342. end;
  14343. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14344. var
  14345. hp1, hp2: tai;
  14346. IdentityMask, Shift: TCGInt;
  14347. LimitSize: Topsize;
  14348. DoNotMerge: Boolean;
  14349. begin
  14350. Result := False;
  14351. { All these optimisations work on "shr const,%reg" }
  14352. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14353. Exit;
  14354. DoNotMerge := False;
  14355. Shift := taicpu(p).oper[0]^.val;
  14356. LimitSize := taicpu(p).opsize;
  14357. hp1 := p;
  14358. repeat
  14359. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14360. Break;
  14361. { Detect:
  14362. shr x, %reg
  14363. and y, %reg
  14364. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14365. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14366. }
  14367. case taicpu(hp1).opcode of
  14368. A_AND:
  14369. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14370. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14371. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14372. begin
  14373. { Make sure the FLAGS register isn't in use }
  14374. TransferUsedRegs(TmpUsedRegs);
  14375. hp2 := p;
  14376. repeat
  14377. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14378. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14379. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14380. begin
  14381. { Generate the identity mask }
  14382. case taicpu(p).opsize of
  14383. S_B:
  14384. IdentityMask := $FF shr Shift;
  14385. S_W:
  14386. IdentityMask := $FFFF shr Shift;
  14387. S_L:
  14388. IdentityMask := $FFFFFFFF shr Shift;
  14389. {$ifdef x86_64}
  14390. S_Q:
  14391. { We need to force the operands to be unsigned 64-bit
  14392. integers otherwise the wrong value is generated }
  14393. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14394. {$endif x86_64}
  14395. else
  14396. InternalError(2022081501);
  14397. end;
  14398. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14399. begin
  14400. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14401. { All the possible 1 bits are covered, so we can remove the AND }
  14402. hp2 := tai(hp1.Previous);
  14403. RemoveInstruction(hp1);
  14404. { p wasn't actually changed, so don't set Result to True,
  14405. but a change was nonetheless made elsewhere }
  14406. Include(OptsToCheck, aoc_ForceNewIteration);
  14407. { Do another pass in case other AND or MOVZX instructions
  14408. follow }
  14409. hp1 := hp2;
  14410. Continue;
  14411. end;
  14412. end;
  14413. end;
  14414. A_TEST, A_CMP, A_Jcc:
  14415. { Skip over conditional jumps and relevant comparisons }
  14416. Continue;
  14417. A_MOVZX:
  14418. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14419. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14420. begin
  14421. { Since the original register is being read as is, subsequent
  14422. SHRs must not be merged at this point }
  14423. DoNotMerge := True;
  14424. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14425. begin
  14426. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14427. begin
  14428. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14429. { All the possible 1 bits are covered, so we can remove the AND }
  14430. hp2 := tai(hp1.Previous);
  14431. RemoveInstruction(hp1);
  14432. hp1 := hp2;
  14433. end
  14434. else { Different register target }
  14435. begin
  14436. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14437. taicpu(hp1).opcode := A_MOV;
  14438. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14439. case taicpu(hp1).opsize of
  14440. S_BW:
  14441. taicpu(hp1).opsize := S_W;
  14442. S_BL, S_WL:
  14443. taicpu(hp1).opsize := S_L;
  14444. else
  14445. InternalError(2022081503);
  14446. end;
  14447. end;
  14448. end
  14449. else if (Shift > 0) and
  14450. (taicpu(p).opsize = S_W) and
  14451. (taicpu(hp1).opsize = S_WL) and
  14452. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14453. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14454. begin
  14455. { Detect:
  14456. shr x, %ax (x > 0)
  14457. ...
  14458. movzwl %ax,%eax
  14459. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14460. }
  14461. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14462. taicpu(hp1).opcode := A_CWDE;
  14463. taicpu(hp1).clearop(0);
  14464. taicpu(hp1).clearop(1);
  14465. taicpu(hp1).ops := 0;
  14466. end;
  14467. { Move onto the next instruction }
  14468. Continue;
  14469. end;
  14470. A_SHL, A_SAL, A_SHR:
  14471. if (taicpu(hp1).opsize <= LimitSize) and
  14472. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14473. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14474. begin
  14475. { Make sure the sizes don't exceed the register size limit
  14476. (measured by the shift value falling below the limit) }
  14477. if taicpu(hp1).opsize < LimitSize then
  14478. LimitSize := taicpu(hp1).opsize;
  14479. if taicpu(hp1).opcode = A_SHR then
  14480. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14481. else
  14482. begin
  14483. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14484. DoNotMerge := True;
  14485. end;
  14486. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14487. Break;
  14488. { Since we've established that the combined shift is within
  14489. limits, we can actually combine the adjacent SHR
  14490. instructions even if they're different sizes }
  14491. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14492. begin
  14493. hp2 := tai(hp1.Previous);
  14494. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  14495. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  14496. RemoveInstruction(hp1);
  14497. hp1 := hp2;
  14498. end;
  14499. { Move onto the next instruction }
  14500. Continue;
  14501. end;
  14502. else
  14503. ;
  14504. end;
  14505. Break;
  14506. until False;
  14507. { Detect the following (looking backwards):
  14508. shr %cl,%reg
  14509. shr x, %reg
  14510. Swap the two SHR instructions to minimise a pipeline stall.
  14511. }
  14512. if GetLastInstruction(p, hp1) and
  14513. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  14514. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14515. { First operand will be %cl }
  14516. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  14517. { Just to be sure }
  14518. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  14519. begin
  14520. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  14521. { Moving the entries this way ensures the register tracking remains correct }
  14522. Asml.Remove(p);
  14523. Asml.InsertBefore(p, hp1);
  14524. p := hp1;
  14525. { Don't set Result to True because the current instruction is now
  14526. "shr %cl,%reg" and there's nothing more we can do with it }
  14527. end;
  14528. end;
  14529. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  14530. var
  14531. hp1, hp2: tai;
  14532. Opposite, SecondOpposite: TAsmOp;
  14533. NewCond: TAsmCond;
  14534. begin
  14535. Result := False;
  14536. { Change:
  14537. add/sub 128,(dest)
  14538. To:
  14539. sub/add -128,(dest)
  14540. This generaally takes fewer bytes to encode because -128 can be stored
  14541. in a signed byte, whereas +128 cannot.
  14542. }
  14543. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  14544. begin
  14545. if taicpu(p).opcode = A_ADD then
  14546. Opposite := A_SUB
  14547. else
  14548. Opposite := A_ADD;
  14549. { Be careful if the flags are in use, because the CF flag inverts
  14550. when changing from ADD to SUB and vice versa }
  14551. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14552. GetNextInstruction(p, hp1) then
  14553. begin
  14554. TransferUsedRegs(TmpUsedRegs);
  14555. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  14556. hp2 := hp1;
  14557. { Scan ahead to check if everything's safe }
  14558. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  14559. begin
  14560. if (hp1.typ <> ait_instruction) then
  14561. { Probably unsafe since the flags are still in use }
  14562. Exit;
  14563. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  14564. { Stop searching at an unconditional jump }
  14565. Break;
  14566. if not
  14567. (
  14568. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  14569. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  14570. ) and
  14571. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  14572. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  14573. Exit;
  14574. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14575. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  14576. { Move to the next instruction }
  14577. GetNextInstruction(hp1, hp1);
  14578. end;
  14579. while Assigned(hp2) and (hp2 <> hp1) do
  14580. begin
  14581. NewCond := C_None;
  14582. case taicpu(hp2).condition of
  14583. C_A, C_NBE:
  14584. NewCond := C_BE;
  14585. C_B, C_C, C_NAE:
  14586. NewCond := C_AE;
  14587. C_AE, C_NB, C_NC:
  14588. NewCond := C_B;
  14589. C_BE, C_NA:
  14590. NewCond := C_A;
  14591. else
  14592. { No change needed };
  14593. end;
  14594. if NewCond <> C_None then
  14595. begin
  14596. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  14597. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  14598. taicpu(hp2).condition := NewCond;
  14599. end
  14600. else
  14601. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  14602. begin
  14603. { Because of the flipping of the carry bit, to ensure
  14604. the operation remains equivalent, ADC becomes SBB
  14605. and vice versa, and the constant is not-inverted.
  14606. If multiple ADCs or SBBs appear in a row, each one
  14607. changed causes the carry bit to invert, so they all
  14608. need to be flipped }
  14609. if taicpu(hp2).opcode = A_ADC then
  14610. SecondOpposite := A_SBB
  14611. else
  14612. SecondOpposite := A_ADC;
  14613. if taicpu(hp2).oper[0]^.typ <> top_const then
  14614. { Should have broken out of this optimisation already }
  14615. InternalError(2021112901);
  14616. 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]^) + ' -> ' +
  14617. 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);
  14618. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  14619. taicpu(hp2).opcode := SecondOpposite;
  14620. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  14621. end;
  14622. { Move to the next instruction }
  14623. GetNextInstruction(hp2, hp2);
  14624. end;
  14625. if (hp2 <> hp1) then
  14626. InternalError(2021111501);
  14627. end;
  14628. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  14629. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  14630. taicpu(p).opcode := Opposite;
  14631. taicpu(p).oper[0]^.val := -128;
  14632. { No further optimisations can be made on this instruction, so move
  14633. onto the next one to save time }
  14634. p := tai(p.Next);
  14635. UpdateUsedRegs(p);
  14636. Result := True;
  14637. Exit;
  14638. end;
  14639. { Detect:
  14640. add/sub %reg2,(dest)
  14641. add/sub x, (dest)
  14642. (dest can be a register or a reference)
  14643. Swap the instructions to minimise a pipeline stall. This reverses the
  14644. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  14645. optimisations could be made.
  14646. }
  14647. if (taicpu(p).oper[0]^.typ = top_reg) and
  14648. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  14649. (
  14650. (
  14651. (taicpu(p).oper[1]^.typ = top_reg) and
  14652. { We can try searching further ahead if we're writing to a register }
  14653. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  14654. ) or
  14655. (
  14656. (taicpu(p).oper[1]^.typ = top_ref) and
  14657. GetNextInstruction(p, hp1)
  14658. )
  14659. ) and
  14660. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  14661. (taicpu(hp1).oper[0]^.typ = top_const) and
  14662. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  14663. begin
  14664. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  14665. TransferUsedRegs(TmpUsedRegs);
  14666. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  14667. hp2 := p;
  14668. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  14669. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  14670. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  14671. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14672. begin
  14673. asml.remove(hp1);
  14674. asml.InsertBefore(hp1, p);
  14675. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  14676. Result := True;
  14677. end;
  14678. end;
  14679. end;
  14680. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  14681. var
  14682. hp1: tai;
  14683. begin
  14684. Result:=false;
  14685. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  14686. while GetNextInstruction(p, hp1) and
  14687. TrySwapMovCmp(p, hp1) do
  14688. begin
  14689. if MatchInstruction(hp1, A_MOV, []) then
  14690. begin
  14691. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14692. begin
  14693. { A little hacky, but since CMP doesn't read the flags, only
  14694. modify them, it's safe if they get scrambled by MOV -> XOR }
  14695. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14696. Result := PostPeepholeOptMov(hp1);
  14697. {$ifdef x86_64}
  14698. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14699. { Used to shrink instruction size }
  14700. PostPeepholeOptXor(hp1);
  14701. {$endif x86_64}
  14702. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14703. end
  14704. else
  14705. begin
  14706. Result := PostPeepholeOptMov(hp1);
  14707. {$ifdef x86_64}
  14708. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14709. { Used to shrink instruction size }
  14710. PostPeepholeOptXor(hp1);
  14711. {$endif x86_64}
  14712. end;
  14713. end;
  14714. { Enabling this flag is actually a null operation, but it marks
  14715. the code as 'modified' during this pass }
  14716. Include(OptsToCheck, aoc_ForceNewIteration);
  14717. end;
  14718. { change "cmp $0, %reg" to "test %reg, %reg" }
  14719. if MatchOpType(taicpu(p),top_const,top_reg) and
  14720. (taicpu(p).oper[0]^.val = 0) then
  14721. begin
  14722. taicpu(p).opcode := A_TEST;
  14723. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14724. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14725. Result:=true;
  14726. end;
  14727. end;
  14728. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14729. var
  14730. IsTestConstX, IsValid : Boolean;
  14731. hp1,hp2 : tai;
  14732. begin
  14733. Result:=false;
  14734. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14735. if (taicpu(p).opcode = A_TEST) then
  14736. while GetNextInstruction(p, hp1) and
  14737. TrySwapMovCmp(p, hp1) do
  14738. begin
  14739. if MatchInstruction(hp1, A_MOV, []) then
  14740. begin
  14741. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14742. begin
  14743. { A little hacky, but since TEST doesn't read the flags, only
  14744. modify them, it's safe if they get scrambled by MOV -> XOR }
  14745. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14746. Result := PostPeepholeOptMov(hp1);
  14747. {$ifdef x86_64}
  14748. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14749. { Used to shrink instruction size }
  14750. PostPeepholeOptXor(hp1);
  14751. {$endif x86_64}
  14752. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14753. end
  14754. else
  14755. begin
  14756. Result := PostPeepholeOptMov(hp1);
  14757. {$ifdef x86_64}
  14758. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14759. { Used to shrink instruction size }
  14760. PostPeepholeOptXor(hp1);
  14761. {$endif x86_64}
  14762. end;
  14763. end;
  14764. { Enabling this flag is actually a null operation, but it marks
  14765. the code as 'modified' during this pass }
  14766. Include(OptsToCheck, aoc_ForceNewIteration);
  14767. end;
  14768. { If x is a power of 2 (popcnt = 1), change:
  14769. or $x, %reg/ref
  14770. To:
  14771. bts lb(x), %reg/ref
  14772. }
  14773. if (taicpu(p).opcode = A_OR) and
  14774. IsBTXAcceptable(p) and
  14775. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14776. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14777. (
  14778. { Don't optimise if a test instruction follows }
  14779. not GetNextInstruction(p, hp1) or
  14780. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14781. ) then
  14782. begin
  14783. 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);
  14784. taicpu(p).opcode := A_BTS;
  14785. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14786. Result := True;
  14787. Exit;
  14788. end;
  14789. { If x is a power of 2 (popcnt = 1), change:
  14790. test $x, %reg/ref
  14791. je / sete / cmove (or jne / setne)
  14792. To:
  14793. bt lb(x), %reg/ref
  14794. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14795. }
  14796. if (taicpu(p).opcode = A_TEST) and
  14797. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14798. (taicpu(p).oper[0]^.typ = top_const) and
  14799. (
  14800. (cs_opt_size in current_settings.optimizerswitches) or
  14801. (
  14802. (taicpu(p).oper[1]^.typ = top_reg) and
  14803. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14804. ) or
  14805. (
  14806. (taicpu(p).oper[1]^.typ <> top_reg) and
  14807. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14808. )
  14809. ) and
  14810. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14811. { For sizes less than S_L, the byte size is equal or larger with BT,
  14812. so don't bother optimising }
  14813. (taicpu(p).opsize >= S_L) then
  14814. begin
  14815. IsValid := True;
  14816. { Check the next set of instructions, watching the FLAGS register
  14817. and the conditions used }
  14818. TransferUsedRegs(TmpUsedRegs);
  14819. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14820. hp1 := p;
  14821. hp2 := nil;
  14822. while GetNextInstruction(hp1, hp1) do
  14823. begin
  14824. if not Assigned(hp2) then
  14825. { The first instruction after TEST }
  14826. hp2 := hp1;
  14827. if (hp1.typ <> ait_instruction) then
  14828. begin
  14829. { If the flags are no longer in use, everything is fine }
  14830. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14831. IsValid := False;
  14832. Break;
  14833. end;
  14834. case taicpu(hp1).condition of
  14835. C_None:
  14836. begin
  14837. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14838. { Something is not quite normal, so play safe and don't change }
  14839. IsValid := False;
  14840. Break;
  14841. end;
  14842. C_E, C_Z, C_NE, C_NZ:
  14843. { This is fine };
  14844. else
  14845. begin
  14846. { Unsupported condition }
  14847. IsValid := False;
  14848. Break;
  14849. end;
  14850. end;
  14851. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14852. end;
  14853. if IsValid then
  14854. begin
  14855. while hp2 <> hp1 do
  14856. begin
  14857. case taicpu(hp2).condition of
  14858. C_Z, C_E:
  14859. taicpu(hp2).condition := C_NC;
  14860. C_NZ, C_NE:
  14861. taicpu(hp2).condition := C_C;
  14862. else
  14863. { Should not get this by this point }
  14864. InternalError(2022110701);
  14865. end;
  14866. GetNextInstruction(hp2, hp2);
  14867. end;
  14868. 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);
  14869. taicpu(p).opcode := A_BT;
  14870. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14871. Result := True;
  14872. Exit;
  14873. end;
  14874. end;
  14875. { removes the line marked with (x) from the sequence
  14876. and/or/xor/add/sub/... $x, %y
  14877. test/or %y, %y | test $-1, %y (x)
  14878. j(n)z _Label
  14879. as the first instruction already adjusts the ZF
  14880. %y operand may also be a reference }
  14881. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14882. MatchOperand(taicpu(p).oper[0]^,-1);
  14883. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14884. GetLastInstruction(p, hp1) and
  14885. (tai(hp1).typ = ait_instruction) and
  14886. GetNextInstruction(p,hp2) and
  14887. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14888. case taicpu(hp1).opcode Of
  14889. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14890. { These two instructions set the zero flag if the result is zero }
  14891. A_POPCNT, A_LZCNT:
  14892. begin
  14893. if (
  14894. { With POPCNT, an input of zero will set the zero flag
  14895. because the population count of zero is zero }
  14896. (taicpu(hp1).opcode = A_POPCNT) and
  14897. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14898. (
  14899. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14900. { Faster than going through the second half of the 'or'
  14901. condition below }
  14902. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14903. )
  14904. ) or (
  14905. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14906. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14907. { and in case of carry for A(E)/B(E)/C/NC }
  14908. (
  14909. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14910. (
  14911. (taicpu(hp1).opcode <> A_ADD) and
  14912. (taicpu(hp1).opcode <> A_SUB) and
  14913. (taicpu(hp1).opcode <> A_LZCNT)
  14914. )
  14915. )
  14916. ) then
  14917. begin
  14918. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14919. RemoveCurrentP(p, hp2);
  14920. Result:=true;
  14921. Exit;
  14922. end;
  14923. end;
  14924. A_SHL, A_SAL, A_SHR, A_SAR:
  14925. begin
  14926. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14927. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14928. { therefore, it's only safe to do this optimization for }
  14929. { shifts by a (nonzero) constant }
  14930. (taicpu(hp1).oper[0]^.typ = top_const) and
  14931. (taicpu(hp1).oper[0]^.val <> 0) and
  14932. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14933. { and in case of carry for A(E)/B(E)/C/NC }
  14934. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14935. begin
  14936. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14937. RemoveCurrentP(p, hp2);
  14938. Result:=true;
  14939. Exit;
  14940. end;
  14941. end;
  14942. A_DEC, A_INC, A_NEG:
  14943. begin
  14944. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14945. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14946. { and in case of carry for A(E)/B(E)/C/NC }
  14947. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14948. begin
  14949. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14950. RemoveCurrentP(p, hp2);
  14951. Result:=true;
  14952. Exit;
  14953. end;
  14954. end;
  14955. A_ANDN, A_BZHI:
  14956. begin
  14957. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14958. { Only the zero and sign flags are consistent with what the result is }
  14959. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14960. begin
  14961. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14962. RemoveCurrentP(p, hp2);
  14963. Result:=true;
  14964. Exit;
  14965. end;
  14966. end;
  14967. A_BEXTR:
  14968. begin
  14969. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14970. { Only the zero flag is set }
  14971. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14972. begin
  14973. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14974. RemoveCurrentP(p, hp2);
  14975. Result:=true;
  14976. Exit;
  14977. end;
  14978. end;
  14979. else
  14980. ;
  14981. end; { case }
  14982. { change "test $-1,%reg" into "test %reg,%reg" }
  14983. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14984. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14985. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14986. if MatchInstruction(p, A_OR, []) and
  14987. { Can only match if they're both registers }
  14988. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14989. begin
  14990. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14991. taicpu(p).opcode := A_TEST;
  14992. { No need to set Result to True, as we've done all the optimisations we can }
  14993. end;
  14994. end;
  14995. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14996. var
  14997. hp1,hp3 : tai;
  14998. {$ifndef x86_64}
  14999. hp2 : taicpu;
  15000. {$endif x86_64}
  15001. begin
  15002. Result:=false;
  15003. hp3:=nil;
  15004. {$ifndef x86_64}
  15005. { don't do this on modern CPUs, this really hurts them due to
  15006. broken call/ret pairing }
  15007. if (current_settings.optimizecputype < cpu_Pentium2) and
  15008. not(cs_create_pic in current_settings.moduleswitches) and
  15009. GetNextInstruction(p, hp1) and
  15010. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15011. MatchOpType(taicpu(hp1),top_ref) and
  15012. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15013. begin
  15014. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15015. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15016. InsertLLItem(p.previous, p, hp2);
  15017. taicpu(p).opcode := A_JMP;
  15018. taicpu(p).is_jmp := true;
  15019. RemoveInstruction(hp1);
  15020. Result:=true;
  15021. end
  15022. else
  15023. {$endif x86_64}
  15024. { replace
  15025. call procname
  15026. ret
  15027. by
  15028. jmp procname
  15029. but do it only on level 4 because it destroys stack back traces
  15030. else if the subroutine is marked as no return, remove the ret
  15031. }
  15032. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15033. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15034. GetNextInstruction(p, hp1) and
  15035. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15036. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15037. SetAndTest(hp1,hp3) and
  15038. GetNextInstruction(hp1,hp1) and
  15039. MatchInstruction(hp1,A_RET,[S_NO])
  15040. )
  15041. ) and
  15042. (taicpu(hp1).ops=0) then
  15043. begin
  15044. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15045. { we might destroy stack alignment here if we do not do a call }
  15046. (target_info.stackalign<=sizeof(SizeUInt)) then
  15047. begin
  15048. taicpu(p).opcode := A_JMP;
  15049. taicpu(p).is_jmp := true;
  15050. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15051. end
  15052. else
  15053. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15054. RemoveInstruction(hp1);
  15055. if Assigned(hp3) then
  15056. begin
  15057. AsmL.Remove(hp3);
  15058. AsmL.InsertBefore(hp3,p)
  15059. end;
  15060. Result:=true;
  15061. end;
  15062. end;
  15063. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15064. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15065. begin
  15066. case OpSize of
  15067. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15068. Result := (Val <= $FF) and (Val >= -128);
  15069. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15070. Result := (Val <= $FFFF) and (Val >= -32768);
  15071. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15072. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15073. else
  15074. Result := True;
  15075. end;
  15076. end;
  15077. var
  15078. hp1, hp2 : tai;
  15079. SizeChange: Boolean;
  15080. PreMessage: string;
  15081. begin
  15082. Result := False;
  15083. if (taicpu(p).oper[0]^.typ = top_reg) and
  15084. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15085. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15086. begin
  15087. { Change (using movzbl %al,%eax as an example):
  15088. movzbl %al, %eax movzbl %al, %eax
  15089. cmpl x, %eax testl %eax,%eax
  15090. To:
  15091. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15092. movzbl %al, %eax movzbl %al, %eax
  15093. Smaller instruction and minimises pipeline stall as the CPU
  15094. doesn't have to wait for the register to get zero-extended. [Kit]
  15095. Also allow if the smaller of the two registers is being checked,
  15096. as this still removes the false dependency.
  15097. }
  15098. if
  15099. (
  15100. (
  15101. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15102. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15103. ) or (
  15104. { If MatchOperand returns True, they must both be registers }
  15105. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15106. )
  15107. ) and
  15108. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15109. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15110. begin
  15111. 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);
  15112. asml.Remove(hp1);
  15113. asml.InsertBefore(hp1, p);
  15114. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15115. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15116. begin
  15117. taicpu(hp1).opcode := A_TEST;
  15118. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15119. end;
  15120. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15121. case taicpu(p).opsize of
  15122. S_BW, S_BL:
  15123. begin
  15124. SizeChange := taicpu(hp1).opsize <> S_B;
  15125. taicpu(hp1).changeopsize(S_B);
  15126. end;
  15127. S_WL:
  15128. begin
  15129. SizeChange := taicpu(hp1).opsize <> S_W;
  15130. taicpu(hp1).changeopsize(S_W);
  15131. end
  15132. else
  15133. InternalError(2020112701);
  15134. end;
  15135. UpdateUsedRegs(tai(p.Next));
  15136. { Check if the register is used aferwards - if not, we can
  15137. remove the movzx instruction completely }
  15138. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15139. begin
  15140. { Hp1 is a better position than p for debugging purposes }
  15141. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15142. RemoveCurrentp(p, hp1);
  15143. Result := True;
  15144. end;
  15145. if SizeChange then
  15146. DebugMsg(SPeepholeOptimization + PreMessage +
  15147. 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)
  15148. else
  15149. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15150. Exit;
  15151. end;
  15152. { Change (using movzwl %ax,%eax as an example):
  15153. movzwl %ax, %eax
  15154. movb %al, (dest) (Register is smaller than read register in movz)
  15155. To:
  15156. movb %al, (dest) (Move one back to avoid a false dependency)
  15157. movzwl %ax, %eax
  15158. }
  15159. if (taicpu(hp1).opcode = A_MOV) and
  15160. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15161. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15162. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15163. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15164. begin
  15165. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15166. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15167. asml.Remove(hp1);
  15168. asml.InsertBefore(hp1, p);
  15169. if taicpu(hp1).oper[1]^.typ = top_reg then
  15170. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15171. { Check if the register is used aferwards - if not, we can
  15172. remove the movzx instruction completely }
  15173. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15174. begin
  15175. { Hp1 is a better position than p for debugging purposes }
  15176. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15177. RemoveCurrentp(p, hp1);
  15178. Result := True;
  15179. end;
  15180. Exit;
  15181. end;
  15182. end;
  15183. end;
  15184. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15185. var
  15186. hp1: tai;
  15187. {$ifdef x86_64}
  15188. PreMessage, RegName: string;
  15189. {$endif x86_64}
  15190. begin
  15191. Result := False;
  15192. { If x is a power of 2 (popcnt = 1), change:
  15193. xor $x, %reg/ref
  15194. To:
  15195. btc lb(x), %reg/ref
  15196. }
  15197. if IsBTXAcceptable(p) and
  15198. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15199. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15200. (
  15201. { Don't optimise if a test instruction follows }
  15202. not GetNextInstruction(p, hp1) or
  15203. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15204. ) then
  15205. begin
  15206. 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);
  15207. taicpu(p).opcode := A_BTC;
  15208. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15209. Result := True;
  15210. Exit;
  15211. end;
  15212. {$ifdef x86_64}
  15213. { Code size reduction by J. Gareth "Kit" Moreton }
  15214. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15215. as this removes the REX prefix }
  15216. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15217. Exit;
  15218. if taicpu(p).oper[0]^.typ <> top_reg then
  15219. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15220. InternalError(2018011500);
  15221. case taicpu(p).opsize of
  15222. S_Q:
  15223. begin
  15224. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15225. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15226. { The actual optimization }
  15227. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15228. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15229. taicpu(p).changeopsize(S_L);
  15230. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15231. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15232. end;
  15233. else
  15234. ;
  15235. end;
  15236. {$endif x86_64}
  15237. end;
  15238. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15239. var
  15240. XReg: TRegister;
  15241. begin
  15242. Result := False;
  15243. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15244. Smaller encoding and slightly faster on some platforms (also works for
  15245. ZMM-sized registers) }
  15246. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15247. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15248. begin
  15249. XReg := taicpu(p).oper[0]^.reg;
  15250. if (taicpu(p).oper[1]^.reg = XReg) then
  15251. begin
  15252. taicpu(p).changeopsize(S_XMM);
  15253. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15254. if (cs_opt_size in current_settings.optimizerswitches) then
  15255. begin
  15256. { Change input registers to %xmm0 to reduce size. Note that
  15257. there's a risk of a false dependency doing this, so only
  15258. optimise for size here }
  15259. XReg := NR_XMM0;
  15260. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15261. end
  15262. else
  15263. begin
  15264. setsubreg(XReg, R_SUBMMX);
  15265. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15266. end;
  15267. taicpu(p).oper[0]^.reg := XReg;
  15268. taicpu(p).oper[1]^.reg := XReg;
  15269. Result := True;
  15270. end;
  15271. end;
  15272. end;
  15273. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15274. var
  15275. OperIdx: Integer;
  15276. begin
  15277. for OperIdx := 0 to p.ops - 1 do
  15278. if p.oper[OperIdx]^.typ = top_ref then
  15279. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15280. end;
  15281. end.