aoptx86.pas 574 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411
  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. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  46. potentially allowing further optimisation (although it might need to know if
  47. it crossed a conditional jump. }
  48. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  49. {
  50. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  51. the use of a register by allocs/dealloc, so it can ignore calls.
  52. In the following example, GetNextInstructionUsingReg will return the second movq,
  53. GetNextInstructionUsingRegTrackingUse won't.
  54. movq %rdi,%rax
  55. # Register rdi released
  56. # Register rdi allocated
  57. movq %rax,%rdi
  58. While in this example:
  59. movq %rdi,%rax
  60. call proc
  61. movq %rdi,%rax
  62. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  63. won't.
  64. }
  65. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  66. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  67. private
  68. function SkipSimpleInstructions(var hp1: tai): Boolean;
  69. protected
  70. class function IsMOVZXAcceptable: Boolean; static; inline;
  71. { Attempts to allocate a volatile integer register for use between p and hp,
  72. using AUsedRegs for the current register usage information. Returns NR_NO
  73. if no free register could be found }
  74. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  75. { Attempts to allocate a volatile MM register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  79. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  80. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  81. { checks whether reading the value in reg1 depends on the value of reg2. This
  82. is very similar to SuperRegisterEquals, except it takes into account that
  83. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  84. depend on the value in AH). }
  85. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  86. { Replaces all references to AOldReg in a memory reference to ANewReg }
  87. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  88. { Replaces all references to AOldReg in an operand to ANewReg }
  89. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  90. { Replaces all references to AOldReg in an instruction to ANewReg,
  91. except where the register is being written }
  92. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  94. or writes to a global symbol }
  95. class function IsRefSafe(const ref: PReference): Boolean; static;
  96. { Returns true if the given MOV instruction can be safely converted to CMOV }
  97. class function CanBeCMOV(p : tai) : boolean; static;
  98. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  99. conversion was successful }
  100. function ConvertLEA(const p : taicpu): Boolean;
  101. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  102. procedure DebugMsg(const s : string; p : tai);inline;
  103. class function IsExitCode(p : tai) : boolean; static;
  104. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  105. procedure RemoveLastDeallocForFuncRes(p : tai);
  106. function DoSubAddOpt(var p : tai) : Boolean;
  107. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  108. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  109. function PrePeepholeOptSxx(var p : tai) : boolean;
  110. function PrePeepholeOptIMUL(var p : tai) : boolean;
  111. function PrePeepholeOptAND(var p : tai) : boolean;
  112. function OptPass1Test(var p: tai): boolean;
  113. function OptPass1Add(var p: tai): boolean;
  114. function OptPass1AND(var p : tai) : boolean;
  115. function OptPass1_V_MOVAP(var p : tai) : boolean;
  116. function OptPass1VOP(var p : tai) : boolean;
  117. function OptPass1MOV(var p : tai) : boolean;
  118. function OptPass1Movx(var p : tai) : boolean;
  119. function OptPass1MOVXX(var p : tai) : boolean;
  120. function OptPass1OP(var p : tai) : boolean;
  121. function OptPass1LEA(var p : tai) : boolean;
  122. function OptPass1Sub(var p : tai) : boolean;
  123. function OptPass1SHLSAL(var p : tai) : boolean;
  124. function OptPass1FSTP(var p : tai) : boolean;
  125. function OptPass1FLD(var p : tai) : boolean;
  126. function OptPass1Cmp(var p : tai) : boolean;
  127. function OptPass1PXor(var p : tai) : boolean;
  128. function OptPass1VPXor(var p: tai): boolean;
  129. function OptPass1Imul(var p : tai) : boolean;
  130. function OptPass1Jcc(var p : tai) : boolean;
  131. function OptPass1SHXX(var p: tai): boolean;
  132. function OptPass1VMOVDQ(var p: tai): Boolean;
  133. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  134. function OptPass2Movx(var p : tai): Boolean;
  135. function OptPass2MOV(var p : tai) : boolean;
  136. function OptPass2Imul(var p : tai) : boolean;
  137. function OptPass2Jmp(var p : tai) : boolean;
  138. function OptPass2Jcc(var p : tai) : boolean;
  139. function OptPass2Lea(var p: tai): Boolean;
  140. function OptPass2SUB(var p: tai): Boolean;
  141. function OptPass2ADD(var p : tai): Boolean;
  142. function OptPass2SETcc(var p : tai) : boolean;
  143. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  144. function PostPeepholeOptMov(var p : tai) : Boolean;
  145. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  146. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  147. function PostPeepholeOptXor(var p : tai) : Boolean;
  148. {$endif x86_64}
  149. function PostPeepholeOptAnd(var p : tai) : boolean;
  150. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  151. function PostPeepholeOptCmp(var p : tai) : Boolean;
  152. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  153. function PostPeepholeOptCall(var p : tai) : Boolean;
  154. function PostPeepholeOptLea(var p : tai) : Boolean;
  155. function PostPeepholeOptPush(var p: tai): Boolean;
  156. function PostPeepholeOptShr(var p : tai) : boolean;
  157. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  158. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  159. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  160. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  161. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  162. { Processor-dependent reference optimisation }
  163. class procedure OptimizeRefs(var p: taicpu); static;
  164. end;
  165. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  168. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  169. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  170. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  171. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  172. {$if max_operands>2}
  173. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  174. {$endif max_operands>2}
  175. function RefsEqual(const r1, r2: treference): boolean;
  176. { Note that Result is set to True if the references COULD overlap but the
  177. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  178. might still overlap because %reg2 could be equal to %reg1-4 }
  179. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  180. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  181. { returns true, if ref is a reference using only the registers passed as base and index
  182. and having an offset }
  183. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  184. implementation
  185. uses
  186. cutils,verbose,
  187. systems,
  188. globals,
  189. cpuinfo,
  190. procinfo,
  191. paramgr,
  192. aasmbase,
  193. aoptbase,aoptutils,
  194. symconst,symsym,
  195. cgx86,
  196. itcpugas;
  197. {$ifdef DEBUG_AOPTCPU}
  198. const
  199. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  200. {$else DEBUG_AOPTCPU}
  201. { Empty strings help the optimizer to remove string concatenations that won't
  202. ever appear to the user on release builds. [Kit] }
  203. const
  204. SPeepholeOptimization = '';
  205. {$endif DEBUG_AOPTCPU}
  206. LIST_STEP_SIZE = 4;
  207. type
  208. TJumpTrackingItem = class(TLinkedListItem)
  209. private
  210. FSymbol: TAsmSymbol;
  211. FRefs: LongInt;
  212. public
  213. constructor Create(ASymbol: TAsmSymbol);
  214. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  215. property Symbol: TAsmSymbol read FSymbol;
  216. property Refs: LongInt read FRefs;
  217. end;
  218. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  219. begin
  220. inherited Create;
  221. FSymbol := ASymbol;
  222. FRefs := 0;
  223. end;
  224. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  225. begin
  226. Inc(FRefs);
  227. end;
  228. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  229. begin
  230. result :=
  231. (instr.typ = ait_instruction) and
  232. (taicpu(instr).opcode = op) and
  233. ((opsize = []) or (taicpu(instr).opsize in opsize));
  234. end;
  235. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  236. begin
  237. result :=
  238. (instr.typ = ait_instruction) and
  239. ((taicpu(instr).opcode = op1) or
  240. (taicpu(instr).opcode = op2)
  241. ) and
  242. ((opsize = []) or (taicpu(instr).opsize in opsize));
  243. end;
  244. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  245. begin
  246. result :=
  247. (instr.typ = ait_instruction) and
  248. ((taicpu(instr).opcode = op1) or
  249. (taicpu(instr).opcode = op2) or
  250. (taicpu(instr).opcode = op3)
  251. ) and
  252. ((opsize = []) or (taicpu(instr).opsize in opsize));
  253. end;
  254. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  255. const opsize : topsizes) : boolean;
  256. var
  257. op : TAsmOp;
  258. begin
  259. result:=false;
  260. if (instr.typ <> ait_instruction) or
  261. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  262. exit;
  263. for op in ops do
  264. begin
  265. if taicpu(instr).opcode = op then
  266. begin
  267. result:=true;
  268. exit;
  269. end;
  270. end;
  271. end;
  272. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  273. begin
  274. result := (oper.typ = top_reg) and (oper.reg = reg);
  275. end;
  276. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  277. begin
  278. result := (oper.typ = top_const) and (oper.val = a);
  279. end;
  280. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  281. begin
  282. result := oper1.typ = oper2.typ;
  283. if result then
  284. case oper1.typ of
  285. top_const:
  286. Result:=oper1.val = oper2.val;
  287. top_reg:
  288. Result:=oper1.reg = oper2.reg;
  289. top_ref:
  290. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  291. else
  292. internalerror(2013102801);
  293. end
  294. end;
  295. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  296. begin
  297. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  298. if result then
  299. case oper1.typ of
  300. top_const:
  301. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  302. top_reg:
  303. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  304. top_ref:
  305. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  306. else
  307. internalerror(2020052401);
  308. end
  309. end;
  310. function RefsEqual(const r1, r2: treference): boolean;
  311. begin
  312. RefsEqual :=
  313. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  314. (r1.relsymbol = r2.relsymbol) and
  315. (r1.segment = r2.segment) and (r1.base = r2.base) and
  316. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  317. (r1.offset = r2.offset) and
  318. (r1.volatility + r2.volatility = []);
  319. end;
  320. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  321. begin
  322. if (r1.symbol<>r2.symbol) then
  323. { If the index registers are different, there's a chance one could
  324. be set so it equals the other symbol }
  325. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  326. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  327. (r1.relsymbol = r2.relsymbol) and
  328. (r1.segment = r2.segment) and (r1.base = r2.base) and
  329. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  330. (r1.volatility + r2.volatility = []) then
  331. { In this case, it all depends on the offsets }
  332. Exit(abs(r1.offset - r2.offset) < Range);
  333. { There's a chance things MIGHT overlap, so take no chances }
  334. Result := True;
  335. end;
  336. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  337. begin
  338. Result:=(ref.offset=0) and
  339. (ref.scalefactor in [0,1]) and
  340. (ref.segment=NR_NO) and
  341. (ref.symbol=nil) and
  342. (ref.relsymbol=nil) and
  343. ((base=NR_INVALID) or
  344. (ref.base=base)) and
  345. ((index=NR_INVALID) or
  346. (ref.index=index)) and
  347. (ref.volatility=[]);
  348. end;
  349. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  350. begin
  351. Result:=(ref.scalefactor in [0,1]) and
  352. (ref.segment=NR_NO) and
  353. (ref.symbol=nil) and
  354. (ref.relsymbol=nil) and
  355. ((base=NR_INVALID) or
  356. (ref.base=base)) and
  357. ((index=NR_INVALID) or
  358. (ref.index=index)) and
  359. (ref.volatility=[]);
  360. end;
  361. function InstrReadsFlags(p: tai): boolean;
  362. begin
  363. InstrReadsFlags := true;
  364. case p.typ of
  365. ait_instruction:
  366. if InsProp[taicpu(p).opcode].Ch*
  367. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  368. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  369. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  370. exit;
  371. ait_label:
  372. exit;
  373. else
  374. ;
  375. end;
  376. InstrReadsFlags := false;
  377. end;
  378. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  379. begin
  380. Next:=Current;
  381. repeat
  382. Result:=GetNextInstruction(Next,Next);
  383. until not (Result) or
  384. not(cs_opt_level3 in current_settings.optimizerswitches) or
  385. (Next.typ<>ait_instruction) or
  386. RegInInstruction(reg,Next) or
  387. is_calljmp(taicpu(Next).opcode);
  388. end;
  389. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  390. procedure TrackJump(Symbol: TAsmSymbol);
  391. var
  392. Search: TJumpTrackingItem;
  393. begin
  394. { See if an entry already exists in our jump tracking list
  395. (faster to search backwards due to the higher chance of
  396. matching destinations) }
  397. Search := TJumpTrackingItem(JumpTracking.Last);
  398. while Assigned(Search) do
  399. begin
  400. if Search.Symbol = Symbol then
  401. begin
  402. { Found it - remove it so it can be pushed to the front }
  403. JumpTracking.Remove(Search);
  404. Break;
  405. end;
  406. Search := TJumpTrackingItem(Search.Previous);
  407. end;
  408. if not Assigned(Search) then
  409. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  410. JumpTracking.Concat(Search);
  411. Search.IncRefs;
  412. end;
  413. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  414. var
  415. Search: TJumpTrackingItem;
  416. begin
  417. Result := False;
  418. { See if this label appears in the tracking list }
  419. Search := TJumpTrackingItem(JumpTracking.Last);
  420. while Assigned(Search) do
  421. begin
  422. if Search.Symbol = Symbol then
  423. begin
  424. { Found it - let's see what we can discover }
  425. if Search.Symbol.getrefs = Search.Refs then
  426. begin
  427. { Success - all the references are accounted for }
  428. JumpTracking.Remove(Search);
  429. Search.Free;
  430. { It is logically impossible for CrossJump to be false here
  431. because we must have run into a conditional jump for
  432. this label at some point }
  433. if not CrossJump then
  434. InternalError(2022041710);
  435. if JumpTracking.First = nil then
  436. { Tracking list is now empty - no more cross jumps }
  437. CrossJump := False;
  438. Result := True;
  439. Exit;
  440. end;
  441. { If the references don't match, it's possible to enter
  442. this label through other means, so drop out }
  443. Exit;
  444. end;
  445. Search := TJumpTrackingItem(Search.Previous);
  446. end;
  447. end;
  448. var
  449. Next_Label: tai;
  450. begin
  451. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  452. Next := Current;
  453. repeat
  454. Result := GetNextInstruction(Next,Next);
  455. if not Result then
  456. Break;
  457. if Next.typ = ait_align then
  458. Result := SkipAligns(Next, Next);
  459. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  460. if is_calljmpuncondret(taicpu(Next).opcode) then
  461. begin
  462. if (taicpu(Next).opcode = A_JMP) and
  463. { Remove dead code now to save time }
  464. RemoveDeadCodeAfterJump(taicpu(Next)) then
  465. { A jump was removed, but not the current instruction, and
  466. Result doesn't necessarily translate into an optimisation
  467. routine's Result, so use the "Force New Iteration" flag so
  468. mark a new pass }
  469. Include(OptsToCheck, aoc_ForceNewIteration);
  470. if not Assigned(JumpTracking) then
  471. begin
  472. { Cross-label optimisations often causes other optimisations
  473. to perform worse because they're not given the chance to
  474. optimise locally. In this case, don't do the cross-label
  475. optimisations yet, but flag them as a potential possibility
  476. for the next iteration of Pass 1 }
  477. if not NotFirstIteration then
  478. Include(OptsToCheck, aoc_ForceNewIteration);
  479. end
  480. else if IsJumpToLabel(taicpu(Next)) and
  481. GetNextInstruction(Next, Next_Label) and
  482. SkipAligns(Next_Label, Next_Label) then
  483. begin
  484. { If we have JMP .lbl, and the label after it has all of its
  485. references tracked, then this is probably an if-else style of
  486. block and we can keep tracking. If the label for this jump
  487. then appears later and is fully tracked, then it's the end
  488. of the if-else blocks and the code paths converge (thus
  489. marking the end of the cross-jump) }
  490. if (Next_Label.typ = ait_label) then
  491. begin
  492. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  493. begin
  494. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  495. Next := Next_Label;
  496. { CrossJump gets set to false by LabelAccountedFor if the
  497. list is completely emptied (as it indicates that all
  498. code paths have converged). We could avoid this nuance
  499. by moving the TrackJump call to before the
  500. LabelAccountedFor call, but this is slower in situations
  501. where LabelAccountedFor would return False due to the
  502. creation of a new object that is not used and destroyed
  503. soon after. }
  504. CrossJump := True;
  505. Continue;
  506. end;
  507. end
  508. else if (Next_Label.typ <> ait_marker) then
  509. { We just did a RemoveDeadCodeAfterJump, so either we find
  510. a label, the end of the procedure or some kind of marker}
  511. InternalError(2022041720);
  512. end;
  513. Result := False;
  514. Exit;
  515. end
  516. else
  517. begin
  518. if not Assigned(JumpTracking) then
  519. begin
  520. { Cross-label optimisations often causes other optimisations
  521. to perform worse because they're not given the chance to
  522. optimise locally. In this case, don't do the cross-label
  523. optimisations yet, but flag them as a potential possibility
  524. for the next iteration of Pass 1 }
  525. if not NotFirstIteration then
  526. Include(OptsToCheck, aoc_ForceNewIteration);
  527. end
  528. else if IsJumpToLabel(taicpu(Next)) then
  529. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  530. else
  531. { Conditional jumps should always be a jump to label }
  532. InternalError(2022041701);
  533. CrossJump := True;
  534. Continue;
  535. end;
  536. if Next.typ = ait_label then
  537. begin
  538. if not Assigned(JumpTracking) then
  539. begin
  540. { Cross-label optimisations often causes other optimisations
  541. to perform worse because they're not given the chance to
  542. optimise locally. In this case, don't do the cross-label
  543. optimisations yet, but flag them as a potential possibility
  544. for the next iteration of Pass 1 }
  545. if not NotFirstIteration then
  546. Include(OptsToCheck, aoc_ForceNewIteration);
  547. end
  548. else if LabelAccountedFor(tai_label(Next).labsym) then
  549. Continue;
  550. { If we reach here, we're at a label that hasn't been seen before
  551. (or JumpTracking was nil) }
  552. Break;
  553. end;
  554. until not Result or
  555. not (cs_opt_level3 in current_settings.optimizerswitches) or
  556. not (Next.typ in [ait_label, ait_instruction]) or
  557. RegInInstruction(reg,Next);
  558. end;
  559. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  560. begin
  561. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  562. begin
  563. Result:=GetNextInstruction(Current,Next);
  564. exit;
  565. end;
  566. Next:=tai(Current.Next);
  567. Result:=false;
  568. while assigned(Next) do
  569. begin
  570. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  571. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  572. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  573. exit
  574. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  575. begin
  576. Result:=true;
  577. exit;
  578. end;
  579. Next:=tai(Next.Next);
  580. end;
  581. end;
  582. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  583. begin
  584. Result:=RegReadByInstruction(reg,hp);
  585. end;
  586. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  587. var
  588. p: taicpu;
  589. opcount: longint;
  590. begin
  591. RegReadByInstruction := false;
  592. if hp.typ <> ait_instruction then
  593. exit;
  594. p := taicpu(hp);
  595. case p.opcode of
  596. A_CALL:
  597. regreadbyinstruction := true;
  598. A_IMUL:
  599. case p.ops of
  600. 1:
  601. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  602. (
  603. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  604. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  605. );
  606. 2,3:
  607. regReadByInstruction :=
  608. reginop(reg,p.oper[0]^) or
  609. reginop(reg,p.oper[1]^);
  610. else
  611. InternalError(2019112801);
  612. end;
  613. A_MUL:
  614. begin
  615. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  616. (
  617. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  618. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  619. );
  620. end;
  621. A_IDIV,A_DIV:
  622. begin
  623. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  624. (
  625. (getregtype(reg)=R_INTREGISTER) and
  626. (
  627. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  628. )
  629. );
  630. end;
  631. else
  632. begin
  633. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  634. begin
  635. RegReadByInstruction := false;
  636. exit;
  637. end;
  638. for opcount := 0 to p.ops-1 do
  639. if (p.oper[opCount]^.typ = top_ref) and
  640. RegInRef(reg,p.oper[opcount]^.ref^) then
  641. begin
  642. RegReadByInstruction := true;
  643. exit
  644. end;
  645. { special handling for SSE MOVSD }
  646. if (p.opcode=A_MOVSD) and (p.ops>0) then
  647. begin
  648. if p.ops<>2 then
  649. internalerror(2017042702);
  650. regReadByInstruction := reginop(reg,p.oper[0]^) or
  651. (
  652. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  653. );
  654. exit;
  655. end;
  656. with insprop[p.opcode] do
  657. begin
  658. case getregtype(reg) of
  659. R_INTREGISTER:
  660. begin
  661. case getsupreg(reg) of
  662. RS_EAX:
  663. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  664. begin
  665. RegReadByInstruction := true;
  666. exit
  667. end;
  668. RS_ECX:
  669. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  670. begin
  671. RegReadByInstruction := true;
  672. exit
  673. end;
  674. RS_EDX:
  675. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  676. begin
  677. RegReadByInstruction := true;
  678. exit
  679. end;
  680. RS_EBX:
  681. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  682. begin
  683. RegReadByInstruction := true;
  684. exit
  685. end;
  686. RS_ESP:
  687. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  688. begin
  689. RegReadByInstruction := true;
  690. exit
  691. end;
  692. RS_EBP:
  693. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  694. begin
  695. RegReadByInstruction := true;
  696. exit
  697. end;
  698. RS_ESI:
  699. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  700. begin
  701. RegReadByInstruction := true;
  702. exit
  703. end;
  704. RS_EDI:
  705. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  706. begin
  707. RegReadByInstruction := true;
  708. exit
  709. end;
  710. end;
  711. end;
  712. R_MMREGISTER:
  713. begin
  714. case getsupreg(reg) of
  715. RS_XMM0:
  716. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  717. begin
  718. RegReadByInstruction := true;
  719. exit
  720. end;
  721. end;
  722. end;
  723. else
  724. ;
  725. end;
  726. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  727. begin
  728. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  729. begin
  730. case p.condition of
  731. C_A,C_NBE, { CF=0 and ZF=0 }
  732. C_BE,C_NA: { CF=1 or ZF=1 }
  733. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  734. C_AE,C_NB,C_NC, { CF=0 }
  735. C_B,C_NAE,C_C: { CF=1 }
  736. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  737. C_NE,C_NZ, { ZF=0 }
  738. C_E,C_Z: { ZF=1 }
  739. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  740. C_G,C_NLE, { ZF=0 and SF=OF }
  741. C_LE,C_NG: { ZF=1 or SF<>OF }
  742. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  743. C_GE,C_NL, { SF=OF }
  744. C_L,C_NGE: { SF<>OF }
  745. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  746. C_NO, { OF=0 }
  747. C_O: { OF=1 }
  748. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  749. C_NP,C_PO, { PF=0 }
  750. C_P,C_PE: { PF=1 }
  751. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  752. C_NS, { SF=0 }
  753. C_S: { SF=1 }
  754. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  755. else
  756. internalerror(2017042701);
  757. end;
  758. if RegReadByInstruction then
  759. exit;
  760. end;
  761. case getsubreg(reg) of
  762. R_SUBW,R_SUBD,R_SUBQ:
  763. RegReadByInstruction :=
  764. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  765. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  766. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  767. R_SUBFLAGCARRY:
  768. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  769. R_SUBFLAGPARITY:
  770. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  771. R_SUBFLAGAUXILIARY:
  772. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  773. R_SUBFLAGZERO:
  774. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  775. R_SUBFLAGSIGN:
  776. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  777. R_SUBFLAGOVERFLOW:
  778. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  779. R_SUBFLAGINTERRUPT:
  780. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  781. R_SUBFLAGDIRECTION:
  782. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  783. else
  784. internalerror(2017042601);
  785. end;
  786. exit;
  787. end;
  788. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  789. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  790. (p.oper[0]^.reg=p.oper[1]^.reg) then
  791. exit;
  792. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  793. begin
  794. RegReadByInstruction := true;
  795. exit
  796. end;
  797. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  808. begin
  809. RegReadByInstruction := true;
  810. exit
  811. end;
  812. end;
  813. end;
  814. end;
  815. end;
  816. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  817. begin
  818. result:=false;
  819. if p1.typ<>ait_instruction then
  820. exit;
  821. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  822. exit(true);
  823. if (getregtype(reg)=R_INTREGISTER) and
  824. { change information for xmm movsd are not correct }
  825. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  826. begin
  827. case getsupreg(reg) of
  828. { RS_EAX = RS_RAX on x86-64 }
  829. RS_EAX:
  830. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  831. RS_ECX:
  832. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  833. RS_EDX:
  834. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  835. RS_EBX:
  836. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  837. RS_ESP:
  838. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  839. RS_EBP:
  840. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  841. RS_ESI:
  842. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  843. RS_EDI:
  844. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  845. else
  846. ;
  847. end;
  848. if result then
  849. exit;
  850. end
  851. else if getregtype(reg)=R_MMREGISTER then
  852. begin
  853. case getsupreg(reg) of
  854. RS_XMM0:
  855. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  856. else
  857. ;
  858. end;
  859. if result then
  860. exit;
  861. end
  862. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  863. begin
  864. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  865. exit(true);
  866. case getsubreg(reg) of
  867. R_SUBFLAGCARRY:
  868. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  869. R_SUBFLAGPARITY:
  870. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  871. R_SUBFLAGAUXILIARY:
  872. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  873. R_SUBFLAGZERO:
  874. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  875. R_SUBFLAGSIGN:
  876. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  877. R_SUBFLAGOVERFLOW:
  878. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  879. R_SUBFLAGINTERRUPT:
  880. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. R_SUBFLAGDIRECTION:
  882. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. R_SUBW,R_SUBD,R_SUBQ:
  884. { Everything except the direction bits }
  885. Result:=
  886. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  887. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  888. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  889. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  890. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  891. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  892. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. else
  894. ;
  895. end;
  896. if result then
  897. exit;
  898. end
  899. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  900. exit(true);
  901. Result:=inherited RegInInstruction(Reg, p1);
  902. end;
  903. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  904. const
  905. WriteOps: array[0..3] of set of TInsChange =
  906. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  907. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  908. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  909. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  910. var
  911. OperIdx: Integer;
  912. begin
  913. Result := False;
  914. if p1.typ <> ait_instruction then
  915. exit;
  916. with insprop[taicpu(p1).opcode] do
  917. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  918. begin
  919. case getsubreg(reg) of
  920. R_SUBW,R_SUBD,R_SUBQ:
  921. Result :=
  922. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  923. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  924. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  925. R_SUBFLAGCARRY:
  926. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  927. R_SUBFLAGPARITY:
  928. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  929. R_SUBFLAGAUXILIARY:
  930. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  931. R_SUBFLAGZERO:
  932. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  933. R_SUBFLAGSIGN:
  934. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  935. R_SUBFLAGOVERFLOW:
  936. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  937. R_SUBFLAGINTERRUPT:
  938. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  939. R_SUBFLAGDIRECTION:
  940. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  941. else
  942. internalerror(2017042602);
  943. end;
  944. exit;
  945. end;
  946. case taicpu(p1).opcode of
  947. A_CALL:
  948. { We could potentially set Result to False if the register in
  949. question is non-volatile for the subroutine's calling convention,
  950. but this would require detecting the calling convention in use and
  951. also assuming that the routine doesn't contain malformed assembly
  952. language, for example... so it could only be done under -O4 as it
  953. would be considered a side-effect. [Kit] }
  954. Result := True;
  955. A_MOVSD:
  956. { special handling for SSE MOVSD }
  957. if (taicpu(p1).ops>0) then
  958. begin
  959. if taicpu(p1).ops<>2 then
  960. internalerror(2017042703);
  961. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  962. end;
  963. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  964. so fix it here (FK)
  965. }
  966. A_VMOVSS,
  967. A_VMOVSD:
  968. begin
  969. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  970. exit;
  971. end;
  972. A_IMUL:
  973. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  974. else
  975. ;
  976. end;
  977. if Result then
  978. exit;
  979. with insprop[taicpu(p1).opcode] do
  980. begin
  981. if getregtype(reg)=R_INTREGISTER then
  982. begin
  983. case getsupreg(reg) of
  984. RS_EAX:
  985. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  986. begin
  987. Result := True;
  988. exit
  989. end;
  990. RS_ECX:
  991. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  992. begin
  993. Result := True;
  994. exit
  995. end;
  996. RS_EDX:
  997. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  998. begin
  999. Result := True;
  1000. exit
  1001. end;
  1002. RS_EBX:
  1003. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1004. begin
  1005. Result := True;
  1006. exit
  1007. end;
  1008. RS_ESP:
  1009. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1010. begin
  1011. Result := True;
  1012. exit
  1013. end;
  1014. RS_EBP:
  1015. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1016. begin
  1017. Result := True;
  1018. exit
  1019. end;
  1020. RS_ESI:
  1021. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1022. begin
  1023. Result := True;
  1024. exit
  1025. end;
  1026. RS_EDI:
  1027. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1028. begin
  1029. Result := True;
  1030. exit
  1031. end;
  1032. end;
  1033. end;
  1034. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1035. if (WriteOps[OperIdx]*Ch<>[]) and
  1036. { The register doesn't get modified inside a reference }
  1037. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1038. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1039. begin
  1040. Result := true;
  1041. exit
  1042. end;
  1043. end;
  1044. end;
  1045. {$ifdef DEBUG_AOPTCPU}
  1046. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1047. begin
  1048. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1049. end;
  1050. function debug_tostr(i: tcgint): string; inline;
  1051. begin
  1052. Result := tostr(i);
  1053. end;
  1054. function debug_regname(r: TRegister): string; inline;
  1055. begin
  1056. Result := '%' + std_regname(r);
  1057. end;
  1058. { Debug output function - creates a string representation of an operator }
  1059. function debug_operstr(oper: TOper): string;
  1060. begin
  1061. case oper.typ of
  1062. top_const:
  1063. Result := '$' + debug_tostr(oper.val);
  1064. top_reg:
  1065. Result := debug_regname(oper.reg);
  1066. top_ref:
  1067. begin
  1068. if oper.ref^.offset <> 0 then
  1069. Result := debug_tostr(oper.ref^.offset) + '('
  1070. else
  1071. Result := '(';
  1072. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1073. begin
  1074. Result := Result + debug_regname(oper.ref^.base);
  1075. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1076. Result := Result + ',' + debug_regname(oper.ref^.index);
  1077. end
  1078. else
  1079. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1080. Result := Result + debug_regname(oper.ref^.index);
  1081. if (oper.ref^.scalefactor > 1) then
  1082. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1083. else
  1084. Result := Result + ')';
  1085. end;
  1086. else
  1087. Result := '[UNKNOWN]';
  1088. end;
  1089. end;
  1090. function debug_op2str(opcode: tasmop): string; inline;
  1091. begin
  1092. Result := std_op2str[opcode];
  1093. end;
  1094. function debug_opsize2str(opsize: topsize): string; inline;
  1095. begin
  1096. Result := gas_opsize2str[opsize];
  1097. end;
  1098. {$else DEBUG_AOPTCPU}
  1099. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1100. begin
  1101. end;
  1102. function debug_tostr(i: tcgint): string; inline;
  1103. begin
  1104. Result := '';
  1105. end;
  1106. function debug_regname(r: TRegister): string; inline;
  1107. begin
  1108. Result := '';
  1109. end;
  1110. function debug_operstr(oper: TOper): string; inline;
  1111. begin
  1112. Result := '';
  1113. end;
  1114. function debug_op2str(opcode: tasmop): string; inline;
  1115. begin
  1116. Result := '';
  1117. end;
  1118. function debug_opsize2str(opsize: topsize): string; inline;
  1119. begin
  1120. Result := '';
  1121. end;
  1122. {$endif DEBUG_AOPTCPU}
  1123. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1124. begin
  1125. {$ifdef x86_64}
  1126. { Always fine on x86-64 }
  1127. Result := True;
  1128. {$else x86_64}
  1129. Result :=
  1130. {$ifdef i8086}
  1131. (current_settings.cputype >= cpu_386) and
  1132. {$endif i8086}
  1133. (
  1134. { Always accept if optimising for size }
  1135. (cs_opt_size in current_settings.optimizerswitches) or
  1136. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1137. (current_settings.optimizecputype >= cpu_Pentium2)
  1138. );
  1139. {$endif x86_64}
  1140. end;
  1141. { Attempts to allocate a volatile integer register for use between p and hp,
  1142. using AUsedRegs for the current register usage information. Returns NR_NO
  1143. if no free register could be found }
  1144. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1145. var
  1146. RegSet: TCPURegisterSet;
  1147. CurrentSuperReg: Integer;
  1148. CurrentReg: TRegister;
  1149. Currentp: tai;
  1150. Breakout: Boolean;
  1151. begin
  1152. Result := NR_NO;
  1153. RegSet :=
  1154. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1155. current_procinfo.saved_regs_int;
  1156. for CurrentSuperReg in RegSet do
  1157. begin
  1158. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1159. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1160. {$if defined(i386) or defined(i8086)}
  1161. { If the target size is 8-bit, make sure we can actually encode it }
  1162. and (
  1163. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1164. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1165. )
  1166. {$endif i386 or i8086}
  1167. then
  1168. begin
  1169. Currentp := p;
  1170. Breakout := False;
  1171. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1172. begin
  1173. case Currentp.typ of
  1174. ait_instruction:
  1175. begin
  1176. if RegInInstruction(CurrentReg, Currentp) then
  1177. begin
  1178. Breakout := True;
  1179. Break;
  1180. end;
  1181. { Cannot allocate across an unconditional jump }
  1182. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1183. Exit;
  1184. end;
  1185. ait_marker:
  1186. { Don't try anything more if a marker is hit }
  1187. Exit;
  1188. ait_regalloc:
  1189. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1190. begin
  1191. Breakout := True;
  1192. Break;
  1193. end;
  1194. else
  1195. ;
  1196. end;
  1197. end;
  1198. if Breakout then
  1199. { Try the next register }
  1200. Continue;
  1201. { We have a free register available }
  1202. Result := CurrentReg;
  1203. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1204. Exit;
  1205. end;
  1206. end;
  1207. end;
  1208. { Attempts to allocate a volatile MM register for use between p and hp,
  1209. using AUsedRegs for the current register usage information. Returns NR_NO
  1210. if no free register could be found }
  1211. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1212. var
  1213. RegSet: TCPURegisterSet;
  1214. CurrentSuperReg: Integer;
  1215. CurrentReg: TRegister;
  1216. Currentp: tai;
  1217. Breakout: Boolean;
  1218. begin
  1219. Result := NR_NO;
  1220. RegSet :=
  1221. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1222. current_procinfo.saved_regs_mm;
  1223. for CurrentSuperReg in RegSet do
  1224. begin
  1225. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1226. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1227. begin
  1228. Currentp := p;
  1229. Breakout := False;
  1230. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1231. begin
  1232. case Currentp.typ of
  1233. ait_instruction:
  1234. begin
  1235. if RegInInstruction(CurrentReg, Currentp) then
  1236. begin
  1237. Breakout := True;
  1238. Break;
  1239. end;
  1240. { Cannot allocate across an unconditional jump }
  1241. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1242. Exit;
  1243. end;
  1244. ait_marker:
  1245. { Don't try anything more if a marker is hit }
  1246. Exit;
  1247. ait_regalloc:
  1248. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1249. begin
  1250. Breakout := True;
  1251. Break;
  1252. end;
  1253. else
  1254. ;
  1255. end;
  1256. end;
  1257. if Breakout then
  1258. { Try the next register }
  1259. Continue;
  1260. { We have a free register available }
  1261. Result := CurrentReg;
  1262. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1263. Exit;
  1264. end;
  1265. end;
  1266. end;
  1267. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1268. begin
  1269. if not SuperRegistersEqual(reg1,reg2) then
  1270. exit(false);
  1271. if getregtype(reg1)<>R_INTREGISTER then
  1272. exit(true); {because SuperRegisterEqual is true}
  1273. case getsubreg(reg1) of
  1274. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1275. higher, it preserves the high bits, so the new value depends on
  1276. reg2's previous value. In other words, it is equivalent to doing:
  1277. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1278. R_SUBL:
  1279. exit(getsubreg(reg2)=R_SUBL);
  1280. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1281. higher, it actually does a:
  1282. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1283. R_SUBH:
  1284. exit(getsubreg(reg2)=R_SUBH);
  1285. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1286. bits of reg2:
  1287. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1288. R_SUBW:
  1289. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1290. { a write to R_SUBD always overwrites every other subregister,
  1291. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1292. R_SUBD,
  1293. R_SUBQ:
  1294. exit(true);
  1295. else
  1296. internalerror(2017042801);
  1297. end;
  1298. end;
  1299. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1300. begin
  1301. if not SuperRegistersEqual(reg1,reg2) then
  1302. exit(false);
  1303. if getregtype(reg1)<>R_INTREGISTER then
  1304. exit(true); {because SuperRegisterEqual is true}
  1305. case getsubreg(reg1) of
  1306. R_SUBL:
  1307. exit(getsubreg(reg2)<>R_SUBH);
  1308. R_SUBH:
  1309. exit(getsubreg(reg2)<>R_SUBL);
  1310. R_SUBW,
  1311. R_SUBD,
  1312. R_SUBQ:
  1313. exit(true);
  1314. else
  1315. internalerror(2017042802);
  1316. end;
  1317. end;
  1318. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1319. var
  1320. hp1 : tai;
  1321. l : TCGInt;
  1322. begin
  1323. result:=false;
  1324. { changes the code sequence
  1325. shr/sar const1, x
  1326. shl const2, x
  1327. to
  1328. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1329. if GetNextInstruction(p, hp1) and
  1330. MatchInstruction(hp1,A_SHL,[]) and
  1331. (taicpu(p).oper[0]^.typ = top_const) and
  1332. (taicpu(hp1).oper[0]^.typ = top_const) and
  1333. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1334. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1335. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1336. begin
  1337. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1338. not(cs_opt_size in current_settings.optimizerswitches) then
  1339. begin
  1340. { shr/sar const1, %reg
  1341. shl const2, %reg
  1342. with const1 > const2 }
  1343. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1344. taicpu(hp1).opcode := A_AND;
  1345. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1346. case taicpu(p).opsize Of
  1347. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1348. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1349. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1350. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1351. else
  1352. Internalerror(2017050703)
  1353. end;
  1354. end
  1355. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1356. not(cs_opt_size in current_settings.optimizerswitches) then
  1357. begin
  1358. { shr/sar const1, %reg
  1359. shl const2, %reg
  1360. with const1 < const2 }
  1361. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1362. taicpu(p).opcode := A_AND;
  1363. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1364. case taicpu(p).opsize Of
  1365. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1366. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1367. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1368. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1369. else
  1370. Internalerror(2017050702)
  1371. end;
  1372. end
  1373. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1374. begin
  1375. { shr/sar const1, %reg
  1376. shl const2, %reg
  1377. with const1 = const2 }
  1378. taicpu(p).opcode := A_AND;
  1379. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1380. case taicpu(p).opsize Of
  1381. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1382. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1383. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1384. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1385. else
  1386. Internalerror(2017050701)
  1387. end;
  1388. RemoveInstruction(hp1);
  1389. end;
  1390. end;
  1391. end;
  1392. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1393. var
  1394. opsize : topsize;
  1395. hp1 : tai;
  1396. tmpref : treference;
  1397. ShiftValue : Cardinal;
  1398. BaseValue : TCGInt;
  1399. begin
  1400. result:=false;
  1401. opsize:=taicpu(p).opsize;
  1402. { changes certain "imul const, %reg"'s to lea sequences }
  1403. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1404. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1405. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1406. if (taicpu(p).oper[0]^.val = 1) then
  1407. if (taicpu(p).ops = 2) then
  1408. { remove "imul $1, reg" }
  1409. begin
  1410. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1411. Result := RemoveCurrentP(p);
  1412. end
  1413. else
  1414. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1415. begin
  1416. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1417. InsertLLItem(p.previous, p.next, hp1);
  1418. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1419. p.free;
  1420. p := hp1;
  1421. end
  1422. else if ((taicpu(p).ops <= 2) or
  1423. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1424. not(cs_opt_size in current_settings.optimizerswitches) and
  1425. (not(GetNextInstruction(p, hp1)) or
  1426. not((tai(hp1).typ = ait_instruction) and
  1427. ((taicpu(hp1).opcode=A_Jcc) and
  1428. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1429. begin
  1430. {
  1431. imul X, reg1, reg2 to
  1432. lea (reg1,reg1,Y), reg2
  1433. shl ZZ,reg2
  1434. imul XX, reg1 to
  1435. lea (reg1,reg1,YY), reg1
  1436. shl ZZ,reg2
  1437. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1438. it does not exist as a separate optimization target in FPC though.
  1439. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1440. at most two zeros
  1441. }
  1442. reference_reset(tmpref,1,[]);
  1443. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1444. begin
  1445. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1446. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1447. TmpRef.base := taicpu(p).oper[1]^.reg;
  1448. TmpRef.index := taicpu(p).oper[1]^.reg;
  1449. if not(BaseValue in [3,5,9]) then
  1450. Internalerror(2018110101);
  1451. TmpRef.ScaleFactor := BaseValue-1;
  1452. if (taicpu(p).ops = 2) then
  1453. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1454. else
  1455. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1456. AsmL.InsertAfter(hp1,p);
  1457. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1458. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1459. RemoveCurrentP(p, hp1);
  1460. if ShiftValue>0 then
  1461. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1462. end;
  1463. end;
  1464. end;
  1465. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1466. begin
  1467. Result := False;
  1468. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1469. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1470. begin
  1471. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1472. taicpu(p).opcode := A_MOV;
  1473. Result := True;
  1474. end;
  1475. end;
  1476. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1477. var
  1478. p: taicpu absolute hp; { Implicit typecast }
  1479. i: Integer;
  1480. begin
  1481. Result := False;
  1482. if not assigned(hp) or
  1483. (hp.typ <> ait_instruction) then
  1484. Exit;
  1485. Prefetch(insprop[p.opcode]);
  1486. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1487. with insprop[p.opcode] do
  1488. begin
  1489. case getsubreg(reg) of
  1490. R_SUBW,R_SUBD,R_SUBQ:
  1491. Result:=
  1492. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1493. uncommon flags are checked first }
  1494. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1495. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1496. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1497. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1498. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1499. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1500. R_SUBFLAGCARRY:
  1501. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1502. R_SUBFLAGPARITY:
  1503. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1504. R_SUBFLAGAUXILIARY:
  1505. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1506. R_SUBFLAGZERO:
  1507. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1508. R_SUBFLAGSIGN:
  1509. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1510. R_SUBFLAGOVERFLOW:
  1511. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1512. R_SUBFLAGINTERRUPT:
  1513. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1514. R_SUBFLAGDIRECTION:
  1515. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1516. else
  1517. internalerror(2017050501);
  1518. end;
  1519. exit;
  1520. end;
  1521. { Handle special cases first }
  1522. case p.opcode of
  1523. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1524. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1525. begin
  1526. Result :=
  1527. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1528. (p.oper[1]^.typ = top_reg) and
  1529. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1530. (
  1531. (p.oper[0]^.typ = top_const) or
  1532. (
  1533. (p.oper[0]^.typ = top_reg) and
  1534. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1535. ) or (
  1536. (p.oper[0]^.typ = top_ref) and
  1537. not RegInRef(reg,p.oper[0]^.ref^)
  1538. )
  1539. );
  1540. end;
  1541. A_MUL, A_IMUL:
  1542. Result :=
  1543. (
  1544. (p.ops=3) and { IMUL only }
  1545. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1546. (
  1547. (
  1548. (p.oper[1]^.typ=top_reg) and
  1549. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1550. ) or (
  1551. (p.oper[1]^.typ=top_ref) and
  1552. not RegInRef(reg,p.oper[1]^.ref^)
  1553. )
  1554. )
  1555. ) or (
  1556. (
  1557. (p.ops=1) and
  1558. (
  1559. (
  1560. (
  1561. (p.oper[0]^.typ=top_reg) and
  1562. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1563. )
  1564. ) or (
  1565. (p.oper[0]^.typ=top_ref) and
  1566. not RegInRef(reg,p.oper[0]^.ref^)
  1567. )
  1568. ) and (
  1569. (
  1570. (p.opsize=S_B) and
  1571. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1572. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1573. ) or (
  1574. (p.opsize=S_W) and
  1575. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1576. ) or (
  1577. (p.opsize=S_L) and
  1578. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1579. {$ifdef x86_64}
  1580. ) or (
  1581. (p.opsize=S_Q) and
  1582. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1583. {$endif x86_64}
  1584. )
  1585. )
  1586. )
  1587. );
  1588. A_CBW:
  1589. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1590. {$ifndef x86_64}
  1591. A_LDS:
  1592. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1593. A_LES:
  1594. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1595. {$endif not x86_64}
  1596. A_LFS:
  1597. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1598. A_LGS:
  1599. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1600. A_LSS:
  1601. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1602. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1603. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1604. A_LODSB:
  1605. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1606. A_LODSW:
  1607. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1608. {$ifdef x86_64}
  1609. A_LODSQ:
  1610. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1611. {$endif x86_64}
  1612. A_LODSD:
  1613. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1614. A_FSTSW, A_FNSTSW:
  1615. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1616. else
  1617. begin
  1618. with insprop[p.opcode] do
  1619. begin
  1620. if (
  1621. { xor %reg,%reg etc. is classed as a new value }
  1622. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1623. MatchOpType(p, top_reg, top_reg) and
  1624. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1625. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1626. ) then
  1627. begin
  1628. Result := True;
  1629. Exit;
  1630. end;
  1631. { Make sure the entire register is overwritten }
  1632. if (getregtype(reg) = R_INTREGISTER) then
  1633. begin
  1634. if (p.ops > 0) then
  1635. begin
  1636. if RegInOp(reg, p.oper[0]^) then
  1637. begin
  1638. if (p.oper[0]^.typ = top_ref) then
  1639. begin
  1640. if RegInRef(reg, p.oper[0]^.ref^) then
  1641. begin
  1642. Result := False;
  1643. Exit;
  1644. end;
  1645. end
  1646. else if (p.oper[0]^.typ = top_reg) then
  1647. begin
  1648. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1649. begin
  1650. Result := False;
  1651. Exit;
  1652. end
  1653. else if ([Ch_WOp1]*Ch<>[]) then
  1654. begin
  1655. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1656. Result := True
  1657. else
  1658. begin
  1659. Result := False;
  1660. Exit;
  1661. end;
  1662. end;
  1663. end;
  1664. end;
  1665. if (p.ops > 1) then
  1666. begin
  1667. if RegInOp(reg, p.oper[1]^) then
  1668. begin
  1669. if (p.oper[1]^.typ = top_ref) then
  1670. begin
  1671. if RegInRef(reg, p.oper[1]^.ref^) then
  1672. begin
  1673. Result := False;
  1674. Exit;
  1675. end;
  1676. end
  1677. else if (p.oper[1]^.typ = top_reg) then
  1678. begin
  1679. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1680. begin
  1681. Result := False;
  1682. Exit;
  1683. end
  1684. else if ([Ch_WOp2]*Ch<>[]) then
  1685. begin
  1686. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1687. Result := True
  1688. else
  1689. begin
  1690. Result := False;
  1691. Exit;
  1692. end;
  1693. end;
  1694. end;
  1695. end;
  1696. if (p.ops > 2) then
  1697. begin
  1698. if RegInOp(reg, p.oper[2]^) then
  1699. begin
  1700. if (p.oper[2]^.typ = top_ref) then
  1701. begin
  1702. if RegInRef(reg, p.oper[2]^.ref^) then
  1703. begin
  1704. Result := False;
  1705. Exit;
  1706. end;
  1707. end
  1708. else if (p.oper[2]^.typ = top_reg) then
  1709. begin
  1710. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1711. begin
  1712. Result := False;
  1713. Exit;
  1714. end
  1715. else if ([Ch_WOp3]*Ch<>[]) then
  1716. begin
  1717. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1718. Result := True
  1719. else
  1720. begin
  1721. Result := False;
  1722. Exit;
  1723. end;
  1724. end;
  1725. end;
  1726. end;
  1727. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1728. begin
  1729. if (p.oper[3]^.typ = top_ref) then
  1730. begin
  1731. if RegInRef(reg, p.oper[3]^.ref^) then
  1732. begin
  1733. Result := False;
  1734. Exit;
  1735. end;
  1736. end
  1737. else if (p.oper[3]^.typ = top_reg) then
  1738. begin
  1739. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1740. begin
  1741. Result := False;
  1742. Exit;
  1743. end
  1744. else if ([Ch_WOp4]*Ch<>[]) then
  1745. begin
  1746. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1747. Result := True
  1748. else
  1749. begin
  1750. Result := False;
  1751. Exit;
  1752. end;
  1753. end;
  1754. end;
  1755. end;
  1756. end;
  1757. end;
  1758. end;
  1759. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1760. case getsupreg(reg) of
  1761. RS_EAX:
  1762. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1763. begin
  1764. Result := True;
  1765. Exit;
  1766. end;
  1767. RS_ECX:
  1768. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1769. begin
  1770. Result := True;
  1771. Exit;
  1772. end;
  1773. RS_EDX:
  1774. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1775. begin
  1776. Result := True;
  1777. Exit;
  1778. end;
  1779. RS_EBX:
  1780. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1781. begin
  1782. Result := True;
  1783. Exit;
  1784. end;
  1785. RS_ESP:
  1786. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1787. begin
  1788. Result := True;
  1789. Exit;
  1790. end;
  1791. RS_EBP:
  1792. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1793. begin
  1794. Result := True;
  1795. Exit;
  1796. end;
  1797. RS_ESI:
  1798. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1799. begin
  1800. Result := True;
  1801. Exit;
  1802. end;
  1803. RS_EDI:
  1804. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1805. begin
  1806. Result := True;
  1807. Exit;
  1808. end;
  1809. else
  1810. ;
  1811. end;
  1812. end;
  1813. end;
  1814. end;
  1815. end;
  1816. end;
  1817. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1818. var
  1819. hp2,hp3 : tai;
  1820. begin
  1821. { some x86-64 issue a NOP before the real exit code }
  1822. if MatchInstruction(p,A_NOP,[]) then
  1823. GetNextInstruction(p,p);
  1824. result:=assigned(p) and (p.typ=ait_instruction) and
  1825. ((taicpu(p).opcode = A_RET) or
  1826. ((taicpu(p).opcode=A_LEAVE) and
  1827. GetNextInstruction(p,hp2) and
  1828. MatchInstruction(hp2,A_RET,[S_NO])
  1829. ) or
  1830. (((taicpu(p).opcode=A_LEA) and
  1831. MatchOpType(taicpu(p),top_ref,top_reg) and
  1832. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1833. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1834. ) and
  1835. GetNextInstruction(p,hp2) and
  1836. MatchInstruction(hp2,A_RET,[S_NO])
  1837. ) or
  1838. ((((taicpu(p).opcode=A_MOV) and
  1839. MatchOpType(taicpu(p),top_reg,top_reg) and
  1840. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1841. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1842. ((taicpu(p).opcode=A_LEA) and
  1843. MatchOpType(taicpu(p),top_ref,top_reg) and
  1844. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1845. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1846. )
  1847. ) and
  1848. GetNextInstruction(p,hp2) and
  1849. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1850. MatchOpType(taicpu(hp2),top_reg) and
  1851. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1852. GetNextInstruction(hp2,hp3) and
  1853. MatchInstruction(hp3,A_RET,[S_NO])
  1854. )
  1855. );
  1856. end;
  1857. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1858. begin
  1859. isFoldableArithOp := False;
  1860. case hp1.opcode of
  1861. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1862. isFoldableArithOp :=
  1863. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1864. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1865. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1866. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1867. (taicpu(hp1).oper[1]^.reg = reg);
  1868. A_INC,A_DEC,A_NEG,A_NOT:
  1869. isFoldableArithOp :=
  1870. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1871. (taicpu(hp1).oper[0]^.reg = reg);
  1872. else
  1873. ;
  1874. end;
  1875. end;
  1876. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1877. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1878. var
  1879. hp2: tai;
  1880. begin
  1881. hp2 := p;
  1882. repeat
  1883. hp2 := tai(hp2.previous);
  1884. if assigned(hp2) and
  1885. (hp2.typ = ait_regalloc) and
  1886. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1887. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1888. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1889. begin
  1890. RemoveInstruction(hp2);
  1891. break;
  1892. end;
  1893. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1894. end;
  1895. begin
  1896. case current_procinfo.procdef.returndef.typ of
  1897. arraydef,recorddef,pointerdef,
  1898. stringdef,enumdef,procdef,objectdef,errordef,
  1899. filedef,setdef,procvardef,
  1900. classrefdef,forwarddef:
  1901. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1902. orddef:
  1903. if current_procinfo.procdef.returndef.size <> 0 then
  1904. begin
  1905. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1906. { for int64/qword }
  1907. if current_procinfo.procdef.returndef.size = 8 then
  1908. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1909. end;
  1910. else
  1911. ;
  1912. end;
  1913. end;
  1914. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1915. var
  1916. hp1,hp2 : tai;
  1917. begin
  1918. result:=false;
  1919. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1920. begin
  1921. { vmova* reg1,reg1
  1922. =>
  1923. <nop> }
  1924. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1925. begin
  1926. RemoveCurrentP(p);
  1927. result:=true;
  1928. exit;
  1929. end
  1930. else if GetNextInstruction(p,hp1) then
  1931. begin
  1932. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1933. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1934. begin
  1935. { vmova* reg1,reg2
  1936. vmova* reg2,reg3
  1937. dealloc reg2
  1938. =>
  1939. vmova* reg1,reg3 }
  1940. TransferUsedRegs(TmpUsedRegs);
  1941. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1942. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1943. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1944. begin
  1945. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1946. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1947. RemoveInstruction(hp1);
  1948. result:=true;
  1949. exit;
  1950. end
  1951. { special case:
  1952. vmova* reg1,<op>
  1953. vmova* <op>,reg1
  1954. =>
  1955. vmova* reg1,<op> }
  1956. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1957. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1958. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1959. ) then
  1960. begin
  1961. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1962. RemoveInstruction(hp1);
  1963. result:=true;
  1964. exit;
  1965. end
  1966. end
  1967. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1968. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1969. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1970. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1971. ) and
  1972. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1973. begin
  1974. { vmova* reg1,reg2
  1975. vmovs* reg2,<op>
  1976. dealloc reg2
  1977. =>
  1978. vmovs* reg1,reg3 }
  1979. TransferUsedRegs(TmpUsedRegs);
  1980. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1981. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1982. begin
  1983. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1984. taicpu(p).opcode:=taicpu(hp1).opcode;
  1985. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1986. RemoveInstruction(hp1);
  1987. result:=true;
  1988. exit;
  1989. end
  1990. end;
  1991. end;
  1992. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1993. begin
  1994. if MatchInstruction(hp1,[A_VFMADDPD,
  1995. A_VFMADD132PD,
  1996. A_VFMADD132PS,
  1997. A_VFMADD132SD,
  1998. A_VFMADD132SS,
  1999. A_VFMADD213PD,
  2000. A_VFMADD213PS,
  2001. A_VFMADD213SD,
  2002. A_VFMADD213SS,
  2003. A_VFMADD231PD,
  2004. A_VFMADD231PS,
  2005. A_VFMADD231SD,
  2006. A_VFMADD231SS,
  2007. A_VFMADDSUB132PD,
  2008. A_VFMADDSUB132PS,
  2009. A_VFMADDSUB213PD,
  2010. A_VFMADDSUB213PS,
  2011. A_VFMADDSUB231PD,
  2012. A_VFMADDSUB231PS,
  2013. A_VFMSUB132PD,
  2014. A_VFMSUB132PS,
  2015. A_VFMSUB132SD,
  2016. A_VFMSUB132SS,
  2017. A_VFMSUB213PD,
  2018. A_VFMSUB213PS,
  2019. A_VFMSUB213SD,
  2020. A_VFMSUB213SS,
  2021. A_VFMSUB231PD,
  2022. A_VFMSUB231PS,
  2023. A_VFMSUB231SD,
  2024. A_VFMSUB231SS,
  2025. A_VFMSUBADD132PD,
  2026. A_VFMSUBADD132PS,
  2027. A_VFMSUBADD213PD,
  2028. A_VFMSUBADD213PS,
  2029. A_VFMSUBADD231PD,
  2030. A_VFMSUBADD231PS,
  2031. A_VFNMADD132PD,
  2032. A_VFNMADD132PS,
  2033. A_VFNMADD132SD,
  2034. A_VFNMADD132SS,
  2035. A_VFNMADD213PD,
  2036. A_VFNMADD213PS,
  2037. A_VFNMADD213SD,
  2038. A_VFNMADD213SS,
  2039. A_VFNMADD231PD,
  2040. A_VFNMADD231PS,
  2041. A_VFNMADD231SD,
  2042. A_VFNMADD231SS,
  2043. A_VFNMSUB132PD,
  2044. A_VFNMSUB132PS,
  2045. A_VFNMSUB132SD,
  2046. A_VFNMSUB132SS,
  2047. A_VFNMSUB213PD,
  2048. A_VFNMSUB213PS,
  2049. A_VFNMSUB213SD,
  2050. A_VFNMSUB213SS,
  2051. A_VFNMSUB231PD,
  2052. A_VFNMSUB231PS,
  2053. A_VFNMSUB231SD,
  2054. A_VFNMSUB231SS],[S_NO]) and
  2055. { we mix single and double opperations here because we assume that the compiler
  2056. generates vmovapd only after double operations and vmovaps only after single operations }
  2057. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2058. GetNextInstruction(hp1,hp2) and
  2059. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2060. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2061. begin
  2062. TransferUsedRegs(TmpUsedRegs);
  2063. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2064. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2065. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2066. begin
  2067. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2068. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  2069. RemoveInstruction(hp2);
  2070. end;
  2071. end
  2072. else if (hp1.typ = ait_instruction) and
  2073. GetNextInstruction(hp1, hp2) and
  2074. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2075. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2076. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2077. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2078. (((taicpu(p).opcode=A_MOVAPS) and
  2079. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2080. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2081. ((taicpu(p).opcode=A_MOVAPD) and
  2082. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2083. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2084. ) then
  2085. { change
  2086. movapX reg,reg2
  2087. addsX/subsX/... reg3, reg2
  2088. movapX reg2,reg
  2089. to
  2090. addsX/subsX/... reg3,reg
  2091. }
  2092. begin
  2093. TransferUsedRegs(TmpUsedRegs);
  2094. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2095. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2096. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2097. begin
  2098. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2099. debug_op2str(taicpu(p).opcode)+' '+
  2100. debug_op2str(taicpu(hp1).opcode)+' '+
  2101. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2102. { we cannot eliminate the first move if
  2103. the operations uses the same register for source and dest }
  2104. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2105. RemoveCurrentP(p, nil);
  2106. p:=hp1;
  2107. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2108. RemoveInstruction(hp2);
  2109. result:=true;
  2110. end;
  2111. end
  2112. else if (hp1.typ = ait_instruction) and
  2113. (((taicpu(p).opcode=A_VMOVAPD) and
  2114. (taicpu(hp1).opcode=A_VCOMISD)) or
  2115. ((taicpu(p).opcode=A_VMOVAPS) and
  2116. ((taicpu(hp1).opcode=A_VCOMISS))
  2117. )
  2118. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2119. { change
  2120. movapX reg,reg1
  2121. vcomisX reg1,reg1
  2122. to
  2123. vcomisX reg,reg
  2124. }
  2125. begin
  2126. TransferUsedRegs(TmpUsedRegs);
  2127. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2128. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2129. begin
  2130. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2131. debug_op2str(taicpu(p).opcode)+' '+
  2132. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2133. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2134. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2135. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2136. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2137. RemoveCurrentP(p, nil);
  2138. result:=true;
  2139. exit;
  2140. end;
  2141. end
  2142. end;
  2143. end;
  2144. end;
  2145. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2146. var
  2147. hp1 : tai;
  2148. begin
  2149. result:=false;
  2150. { replace
  2151. V<Op>X %mreg1,%mreg2,%mreg3
  2152. VMovX %mreg3,%mreg4
  2153. dealloc %mreg3
  2154. by
  2155. V<Op>X %mreg1,%mreg2,%mreg4
  2156. ?
  2157. }
  2158. if GetNextInstruction(p,hp1) and
  2159. { we mix single and double operations here because we assume that the compiler
  2160. generates vmovapd only after double operations and vmovaps only after single operations }
  2161. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2162. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2163. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2164. begin
  2165. TransferUsedRegs(TmpUsedRegs);
  2166. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2167. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2168. begin
  2169. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2170. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2171. RemoveInstruction(hp1);
  2172. result:=true;
  2173. end;
  2174. end;
  2175. end;
  2176. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2177. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2178. begin
  2179. Result := False;
  2180. { For safety reasons, only check for exact register matches }
  2181. { Check base register }
  2182. if (ref.base = AOldReg) then
  2183. begin
  2184. ref.base := ANewReg;
  2185. Result := True;
  2186. end;
  2187. { Check index register }
  2188. if (ref.index = AOldReg) then
  2189. begin
  2190. ref.index := ANewReg;
  2191. Result := True;
  2192. end;
  2193. end;
  2194. { Replaces all references to AOldReg in an operand to ANewReg }
  2195. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2196. var
  2197. OldSupReg, NewSupReg: TSuperRegister;
  2198. OldSubReg, NewSubReg: TSubRegister;
  2199. OldRegType: TRegisterType;
  2200. ThisOper: POper;
  2201. begin
  2202. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2203. Result := False;
  2204. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2205. InternalError(2020011801);
  2206. OldSupReg := getsupreg(AOldReg);
  2207. OldSubReg := getsubreg(AOldReg);
  2208. OldRegType := getregtype(AOldReg);
  2209. NewSupReg := getsupreg(ANewReg);
  2210. NewSubReg := getsubreg(ANewReg);
  2211. if OldRegType <> getregtype(ANewReg) then
  2212. InternalError(2020011802);
  2213. if OldSubReg <> NewSubReg then
  2214. InternalError(2020011803);
  2215. case ThisOper^.typ of
  2216. top_reg:
  2217. if (
  2218. (ThisOper^.reg = AOldReg) or
  2219. (
  2220. (OldRegType = R_INTREGISTER) and
  2221. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2222. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2223. (
  2224. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2225. {$ifndef x86_64}
  2226. and (
  2227. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2228. don't have an 8-bit representation }
  2229. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2230. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2231. )
  2232. {$endif x86_64}
  2233. )
  2234. )
  2235. ) then
  2236. begin
  2237. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2238. Result := True;
  2239. end;
  2240. top_ref:
  2241. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2242. Result := True;
  2243. else
  2244. ;
  2245. end;
  2246. end;
  2247. { Replaces all references to AOldReg in an instruction to ANewReg }
  2248. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2249. const
  2250. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2251. var
  2252. OperIdx: Integer;
  2253. begin
  2254. Result := False;
  2255. for OperIdx := 0 to p.ops - 1 do
  2256. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2257. begin
  2258. { The shift and rotate instructions can only use CL }
  2259. if not (
  2260. (OperIdx = 0) and
  2261. { This second condition just helps to avoid unnecessarily
  2262. calling MatchInstruction for 10 different opcodes }
  2263. (p.oper[0]^.reg = NR_CL) and
  2264. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2265. ) then
  2266. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2267. end
  2268. else if p.oper[OperIdx]^.typ = top_ref then
  2269. { It's okay to replace registers in references that get written to }
  2270. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2271. end;
  2272. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2273. begin
  2274. with ref^ do
  2275. Result :=
  2276. (index = NR_NO) and
  2277. (
  2278. {$ifdef x86_64}
  2279. (
  2280. (base = NR_RIP) and
  2281. (refaddr in [addr_pic, addr_pic_no_got])
  2282. ) or
  2283. {$endif x86_64}
  2284. (base = NR_STACK_POINTER_REG) or
  2285. (base = current_procinfo.framepointer)
  2286. );
  2287. end;
  2288. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2289. var
  2290. l: asizeint;
  2291. begin
  2292. Result := False;
  2293. { Should have been checked previously }
  2294. if p.opcode <> A_LEA then
  2295. InternalError(2020072501);
  2296. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2297. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2298. not(cs_opt_size in current_settings.optimizerswitches) then
  2299. exit;
  2300. with p.oper[0]^.ref^ do
  2301. begin
  2302. if (base <> p.oper[1]^.reg) or
  2303. (index <> NR_NO) or
  2304. assigned(symbol) then
  2305. exit;
  2306. l:=offset;
  2307. if (l=1) and UseIncDec then
  2308. begin
  2309. p.opcode:=A_INC;
  2310. p.loadreg(0,p.oper[1]^.reg);
  2311. p.ops:=1;
  2312. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2313. end
  2314. else if (l=-1) and UseIncDec then
  2315. begin
  2316. p.opcode:=A_DEC;
  2317. p.loadreg(0,p.oper[1]^.reg);
  2318. p.ops:=1;
  2319. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2320. end
  2321. else
  2322. begin
  2323. if (l<0) and (l<>-2147483648) then
  2324. begin
  2325. p.opcode:=A_SUB;
  2326. p.loadConst(0,-l);
  2327. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2328. end
  2329. else
  2330. begin
  2331. p.opcode:=A_ADD;
  2332. p.loadConst(0,l);
  2333. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2334. end;
  2335. end;
  2336. end;
  2337. Result := True;
  2338. end;
  2339. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2340. var
  2341. CurrentReg, ReplaceReg: TRegister;
  2342. begin
  2343. Result := False;
  2344. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2345. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2346. case hp.opcode of
  2347. A_FSTSW, A_FNSTSW,
  2348. A_IN, A_INS, A_OUT, A_OUTS,
  2349. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2350. { These routines have explicit operands, but they are restricted in
  2351. what they can be (e.g. IN and OUT can only read from AL, AX or
  2352. EAX. }
  2353. Exit;
  2354. A_IMUL:
  2355. begin
  2356. { The 1-operand version writes to implicit registers
  2357. The 2-operand version reads from the first operator, and reads
  2358. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2359. the 3-operand version reads from a register that it doesn't write to
  2360. }
  2361. case hp.ops of
  2362. 1:
  2363. if (
  2364. (
  2365. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2366. ) or
  2367. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2368. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2369. begin
  2370. Result := True;
  2371. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2372. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2373. end;
  2374. 2:
  2375. { Only modify the first parameter }
  2376. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2377. begin
  2378. Result := True;
  2379. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2380. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2381. end;
  2382. 3:
  2383. { Only modify the second parameter }
  2384. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2385. begin
  2386. Result := True;
  2387. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2388. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2389. end;
  2390. else
  2391. InternalError(2020012901);
  2392. end;
  2393. end;
  2394. else
  2395. if (hp.ops > 0) and
  2396. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2397. begin
  2398. Result := True;
  2399. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2400. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2401. end;
  2402. end;
  2403. end;
  2404. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2405. var
  2406. hp1, hp2, hp3: tai;
  2407. DoOptimisation, TempBool: Boolean;
  2408. {$ifdef x86_64}
  2409. NewConst: TCGInt;
  2410. {$endif x86_64}
  2411. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2412. begin
  2413. if taicpu(hp1).opcode = signed_movop then
  2414. begin
  2415. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2416. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2417. end
  2418. else
  2419. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2420. end;
  2421. function TryConstMerge(var p1, p2: tai): Boolean;
  2422. var
  2423. ThisRef: TReference;
  2424. begin
  2425. Result := False;
  2426. ThisRef := taicpu(p2).oper[1]^.ref^;
  2427. { Only permit writes to the stack, since we can guarantee alignment with that }
  2428. if (ThisRef.index = NR_NO) and
  2429. (
  2430. (ThisRef.base = NR_STACK_POINTER_REG) or
  2431. (ThisRef.base = current_procinfo.framepointer)
  2432. ) then
  2433. begin
  2434. case taicpu(p).opsize of
  2435. S_B:
  2436. begin
  2437. { Word writes must be on a 2-byte boundary }
  2438. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2439. begin
  2440. { Reduce offset of second reference to see if it is sequential with the first }
  2441. Dec(ThisRef.offset, 1);
  2442. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2443. begin
  2444. { Make sure the constants aren't represented as a
  2445. negative number, as these won't merge properly }
  2446. taicpu(p1).opsize := S_W;
  2447. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2448. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2449. RemoveInstruction(p2);
  2450. Result := True;
  2451. end;
  2452. end;
  2453. end;
  2454. S_W:
  2455. begin
  2456. { Longword writes must be on a 4-byte boundary }
  2457. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2458. begin
  2459. { Reduce offset of second reference to see if it is sequential with the first }
  2460. Dec(ThisRef.offset, 2);
  2461. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2462. begin
  2463. { Make sure the constants aren't represented as a
  2464. negative number, as these won't merge properly }
  2465. taicpu(p1).opsize := S_L;
  2466. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2467. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2468. RemoveInstruction(p2);
  2469. Result := True;
  2470. end;
  2471. end;
  2472. end;
  2473. {$ifdef x86_64}
  2474. S_L:
  2475. begin
  2476. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2477. see if the constants can be encoded this way. }
  2478. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2479. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2480. { Quadword writes must be on an 8-byte boundary }
  2481. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2482. begin
  2483. { Reduce offset of second reference to see if it is sequential with the first }
  2484. Dec(ThisRef.offset, 4);
  2485. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2486. begin
  2487. { Make sure the constants aren't represented as a
  2488. negative number, as these won't merge properly }
  2489. taicpu(p1).opsize := S_Q;
  2490. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2491. taicpu(p1).oper[0]^.val := NewConst;
  2492. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2493. RemoveInstruction(p2);
  2494. Result := True;
  2495. end;
  2496. end;
  2497. end;
  2498. {$endif x86_64}
  2499. else
  2500. ;
  2501. end;
  2502. end;
  2503. end;
  2504. var
  2505. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2506. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2507. NewSize: topsize;
  2508. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2509. SourceRef, TargetRef: TReference;
  2510. MovAligned, MovUnaligned: TAsmOp;
  2511. ThisRef: TReference;
  2512. JumpTracking: TLinkedList;
  2513. begin
  2514. Result:=false;
  2515. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2516. { remove mov reg1,reg1? }
  2517. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2518. then
  2519. begin
  2520. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2521. { take care of the register (de)allocs following p }
  2522. RemoveCurrentP(p, hp1);
  2523. Result:=true;
  2524. exit;
  2525. end;
  2526. { All the next optimisations require a next instruction }
  2527. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2528. Exit;
  2529. { Prevent compiler warnings }
  2530. p_TargetReg := NR_NO;
  2531. if taicpu(p).oper[1]^.typ = top_reg then
  2532. begin
  2533. { Saves on a large number of dereferences }
  2534. p_TargetReg := taicpu(p).oper[1]^.reg;
  2535. { Look for:
  2536. mov %reg1,%reg2
  2537. ??? %reg2,r/m
  2538. Change to:
  2539. mov %reg1,%reg2
  2540. ??? %reg1,r/m
  2541. }
  2542. if taicpu(p).oper[0]^.typ = top_reg then
  2543. begin
  2544. if RegReadByInstruction(p_TargetReg, hp1) and
  2545. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2546. begin
  2547. { A change has occurred, just not in p }
  2548. Result := True;
  2549. TransferUsedRegs(TmpUsedRegs);
  2550. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2551. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2552. { Just in case something didn't get modified (e.g. an
  2553. implicit register) }
  2554. not RegReadByInstruction(p_TargetReg, hp1) then
  2555. begin
  2556. { We can remove the original MOV }
  2557. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2558. RemoveCurrentp(p, hp1);
  2559. { UsedRegs got updated by RemoveCurrentp }
  2560. Result := True;
  2561. Exit;
  2562. end;
  2563. { If we know a MOV instruction has become a null operation, we might as well
  2564. get rid of it now to save time. }
  2565. if (taicpu(hp1).opcode = A_MOV) and
  2566. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2567. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2568. { Just being a register is enough to confirm it's a null operation }
  2569. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2570. begin
  2571. Result := True;
  2572. { Speed-up to reduce a pipeline stall... if we had something like...
  2573. movl %eax,%edx
  2574. movw %dx,%ax
  2575. ... the second instruction would change to movw %ax,%ax, but
  2576. given that it is now %ax that's active rather than %eax,
  2577. penalties might occur due to a partial register write, so instead,
  2578. change it to a MOVZX instruction when optimising for speed.
  2579. }
  2580. if not (cs_opt_size in current_settings.optimizerswitches) and
  2581. IsMOVZXAcceptable and
  2582. (taicpu(hp1).opsize < taicpu(p).opsize)
  2583. {$ifdef x86_64}
  2584. { operations already implicitly set the upper 64 bits to zero }
  2585. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2586. {$endif x86_64}
  2587. then
  2588. begin
  2589. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2590. case taicpu(p).opsize of
  2591. S_W:
  2592. if taicpu(hp1).opsize = S_B then
  2593. taicpu(hp1).opsize := S_BL
  2594. else
  2595. InternalError(2020012911);
  2596. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2597. case taicpu(hp1).opsize of
  2598. S_B:
  2599. taicpu(hp1).opsize := S_BL;
  2600. S_W:
  2601. taicpu(hp1).opsize := S_WL;
  2602. else
  2603. InternalError(2020012912);
  2604. end;
  2605. else
  2606. InternalError(2020012910);
  2607. end;
  2608. taicpu(hp1).opcode := A_MOVZX;
  2609. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2610. end
  2611. else
  2612. begin
  2613. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2614. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2615. RemoveInstruction(hp1);
  2616. { The instruction after what was hp1 is now the immediate next instruction,
  2617. so we can continue to make optimisations if it's present }
  2618. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2619. Exit;
  2620. hp1 := hp2;
  2621. end;
  2622. end;
  2623. end;
  2624. end;
  2625. end;
  2626. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2627. overwrites the original destination register. e.g.
  2628. movl ###,%reg2d
  2629. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2630. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2631. }
  2632. if (taicpu(p).oper[1]^.typ = top_reg) and
  2633. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2634. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2635. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2636. begin
  2637. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2638. begin
  2639. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2640. case taicpu(p).oper[0]^.typ of
  2641. top_const:
  2642. { We have something like:
  2643. movb $x, %regb
  2644. movzbl %regb,%regd
  2645. Change to:
  2646. movl $x, %regd
  2647. }
  2648. begin
  2649. case taicpu(hp1).opsize of
  2650. S_BW:
  2651. begin
  2652. convert_mov_value(A_MOVSX, $FF);
  2653. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2654. taicpu(p).opsize := S_W;
  2655. end;
  2656. S_BL:
  2657. begin
  2658. convert_mov_value(A_MOVSX, $FF);
  2659. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2660. taicpu(p).opsize := S_L;
  2661. end;
  2662. S_WL:
  2663. begin
  2664. convert_mov_value(A_MOVSX, $FFFF);
  2665. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2666. taicpu(p).opsize := S_L;
  2667. end;
  2668. {$ifdef x86_64}
  2669. S_BQ:
  2670. begin
  2671. convert_mov_value(A_MOVSX, $FF);
  2672. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2673. taicpu(p).opsize := S_Q;
  2674. end;
  2675. S_WQ:
  2676. begin
  2677. convert_mov_value(A_MOVSX, $FFFF);
  2678. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2679. taicpu(p).opsize := S_Q;
  2680. end;
  2681. S_LQ:
  2682. begin
  2683. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2684. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2685. taicpu(p).opsize := S_Q;
  2686. end;
  2687. {$endif x86_64}
  2688. else
  2689. { If hp1 was a MOV instruction, it should have been
  2690. optimised already }
  2691. InternalError(2020021001);
  2692. end;
  2693. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2694. RemoveInstruction(hp1);
  2695. Result := True;
  2696. Exit;
  2697. end;
  2698. top_ref:
  2699. begin
  2700. { We have something like:
  2701. movb mem, %regb
  2702. movzbl %regb,%regd
  2703. Change to:
  2704. movzbl mem, %regd
  2705. }
  2706. ThisRef := taicpu(p).oper[0]^.ref^;
  2707. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2708. begin
  2709. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2710. taicpu(hp1).loadref(0, ThisRef);
  2711. { Make sure any registers in the references are properly tracked }
  2712. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2713. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2714. if (ThisRef.index <> NR_NO) then
  2715. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2716. RemoveCurrentP(p, hp1);
  2717. Result := True;
  2718. Exit;
  2719. end;
  2720. end;
  2721. else
  2722. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2723. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2724. Exit;
  2725. end;
  2726. end
  2727. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2728. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2729. optimised }
  2730. else
  2731. begin
  2732. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2733. RemoveCurrentP(p, hp1);
  2734. Result := True;
  2735. Exit;
  2736. end;
  2737. end;
  2738. if (taicpu(hp1).opcode = A_AND) and
  2739. (taicpu(p).oper[1]^.typ = top_reg) and
  2740. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2741. begin
  2742. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2743. begin
  2744. case taicpu(p).opsize of
  2745. S_L:
  2746. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2747. begin
  2748. { Optimize out:
  2749. mov x, %reg
  2750. and ffffffffh, %reg
  2751. }
  2752. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2753. RemoveInstruction(hp1);
  2754. Result:=true;
  2755. exit;
  2756. end;
  2757. S_Q: { TODO: Confirm if this is even possible }
  2758. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2759. begin
  2760. { Optimize out:
  2761. mov x, %reg
  2762. and ffffffffffffffffh, %reg
  2763. }
  2764. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2765. RemoveInstruction(hp1);
  2766. Result:=true;
  2767. exit;
  2768. end;
  2769. else
  2770. ;
  2771. end;
  2772. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2773. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2774. GetNextInstruction(hp1,hp2) and
  2775. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2776. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2777. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2778. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2779. GetNextInstruction(hp2,hp3) and
  2780. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2781. (taicpu(hp3).condition in [C_E,C_NE]) then
  2782. begin
  2783. TransferUsedRegs(TmpUsedRegs);
  2784. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2785. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2786. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2787. begin
  2788. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2789. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2790. taicpu(hp1).opcode:=A_TEST;
  2791. RemoveInstruction(hp2);
  2792. RemoveCurrentP(p, hp1);
  2793. Result:=true;
  2794. exit;
  2795. end;
  2796. end;
  2797. end
  2798. else if IsMOVZXAcceptable and
  2799. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2800. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2801. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2802. then
  2803. begin
  2804. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2805. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2806. case taicpu(p).opsize of
  2807. S_B:
  2808. if (taicpu(hp1).oper[0]^.val = $ff) then
  2809. begin
  2810. { Convert:
  2811. movb x, %regl movb x, %regl
  2812. andw ffh, %regw andl ffh, %regd
  2813. To:
  2814. movzbw x, %regd movzbl x, %regd
  2815. (Identical registers, just different sizes)
  2816. }
  2817. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2818. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2819. case taicpu(hp1).opsize of
  2820. S_W: NewSize := S_BW;
  2821. S_L: NewSize := S_BL;
  2822. {$ifdef x86_64}
  2823. S_Q: NewSize := S_BQ;
  2824. {$endif x86_64}
  2825. else
  2826. InternalError(2018011510);
  2827. end;
  2828. end
  2829. else
  2830. NewSize := S_NO;
  2831. S_W:
  2832. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2833. begin
  2834. { Convert:
  2835. movw x, %regw
  2836. andl ffffh, %regd
  2837. To:
  2838. movzwl x, %regd
  2839. (Identical registers, just different sizes)
  2840. }
  2841. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2842. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2843. case taicpu(hp1).opsize of
  2844. S_L: NewSize := S_WL;
  2845. {$ifdef x86_64}
  2846. S_Q: NewSize := S_WQ;
  2847. {$endif x86_64}
  2848. else
  2849. InternalError(2018011511);
  2850. end;
  2851. end
  2852. else
  2853. NewSize := S_NO;
  2854. else
  2855. NewSize := S_NO;
  2856. end;
  2857. if NewSize <> S_NO then
  2858. begin
  2859. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2860. { The actual optimization }
  2861. taicpu(p).opcode := A_MOVZX;
  2862. taicpu(p).changeopsize(NewSize);
  2863. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2864. { Safeguard if "and" is followed by a conditional command }
  2865. TransferUsedRegs(TmpUsedRegs);
  2866. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2867. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2868. begin
  2869. { At this point, the "and" command is effectively equivalent to
  2870. "test %reg,%reg". This will be handled separately by the
  2871. Peephole Optimizer. [Kit] }
  2872. DebugMsg(SPeepholeOptimization + PreMessage +
  2873. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2874. end
  2875. else
  2876. begin
  2877. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2878. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2879. RemoveInstruction(hp1);
  2880. end;
  2881. Result := True;
  2882. Exit;
  2883. end;
  2884. end;
  2885. end;
  2886. if (taicpu(hp1).opcode = A_OR) and
  2887. (taicpu(p).oper[1]^.typ = top_reg) and
  2888. MatchOperand(taicpu(p).oper[0]^, 0) and
  2889. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2890. begin
  2891. { mov 0, %reg
  2892. or ###,%reg
  2893. Change to (only if the flags are not used):
  2894. mov ###,%reg
  2895. }
  2896. TransferUsedRegs(TmpUsedRegs);
  2897. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2898. DoOptimisation := True;
  2899. { Even if the flags are used, we might be able to do the optimisation
  2900. if the conditions are predictable }
  2901. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2902. begin
  2903. { Only perform if ### = %reg (the same register) or equal to 0,
  2904. so %reg is guaranteed to still have a value of zero }
  2905. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2906. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2907. begin
  2908. hp2 := hp1;
  2909. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2910. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2911. GetNextInstruction(hp2, hp3) do
  2912. begin
  2913. { Don't continue modifying if the flags state is getting changed }
  2914. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2915. Break;
  2916. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2917. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2918. begin
  2919. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2920. begin
  2921. { Condition is always true }
  2922. case taicpu(hp3).opcode of
  2923. A_Jcc:
  2924. begin
  2925. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2926. { Check for jump shortcuts before we destroy the condition }
  2927. DoJumpOptimizations(hp3, TempBool);
  2928. MakeUnconditional(taicpu(hp3));
  2929. Result := True;
  2930. end;
  2931. A_CMOVcc:
  2932. begin
  2933. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2934. taicpu(hp3).opcode := A_MOV;
  2935. taicpu(hp3).condition := C_None;
  2936. Result := True;
  2937. end;
  2938. A_SETcc:
  2939. begin
  2940. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2941. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2942. taicpu(hp3).opcode := A_MOV;
  2943. taicpu(hp3).ops := 2;
  2944. taicpu(hp3).condition := C_None;
  2945. taicpu(hp3).opsize := S_B;
  2946. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2947. taicpu(hp3).loadconst(0, 1);
  2948. Result := True;
  2949. end;
  2950. else
  2951. InternalError(2021090701);
  2952. end;
  2953. end
  2954. 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
  2955. begin
  2956. { Condition is always false }
  2957. case taicpu(hp3).opcode of
  2958. A_Jcc:
  2959. begin
  2960. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2961. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2962. RemoveInstruction(hp3);
  2963. Result := True;
  2964. { Since hp3 was deleted, hp2 must not be updated }
  2965. Continue;
  2966. end;
  2967. A_CMOVcc:
  2968. begin
  2969. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2970. RemoveInstruction(hp3);
  2971. Result := True;
  2972. { Since hp3 was deleted, hp2 must not be updated }
  2973. Continue;
  2974. end;
  2975. A_SETcc:
  2976. begin
  2977. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2978. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2979. taicpu(hp3).opcode := A_MOV;
  2980. taicpu(hp3).ops := 2;
  2981. taicpu(hp3).condition := C_None;
  2982. taicpu(hp3).opsize := S_B;
  2983. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2984. taicpu(hp3).loadconst(0, 0);
  2985. Result := True;
  2986. end;
  2987. else
  2988. InternalError(2021090702);
  2989. end;
  2990. end
  2991. else
  2992. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2993. DoOptimisation := False;
  2994. end;
  2995. hp2 := hp3;
  2996. end;
  2997. { Flags are still in use - don't optimise }
  2998. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2999. DoOptimisation := False;
  3000. end
  3001. else
  3002. DoOptimisation := False;
  3003. end;
  3004. if DoOptimisation then
  3005. begin
  3006. {$ifdef x86_64}
  3007. { OR only supports 32-bit sign-extended constants for 64-bit
  3008. instructions, so compensate for this if the constant is
  3009. encoded as a value greater than or equal to 2^31 }
  3010. if (taicpu(hp1).opsize = S_Q) and
  3011. (taicpu(hp1).oper[0]^.typ = top_const) and
  3012. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3013. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3014. {$endif x86_64}
  3015. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3016. taicpu(hp1).opcode := A_MOV;
  3017. RemoveCurrentP(p, hp1);
  3018. Result := True;
  3019. Exit;
  3020. end;
  3021. end;
  3022. { Next instruction is also a MOV ? }
  3023. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3024. begin
  3025. if MatchOpType(taicpu(p), top_const, top_ref) and
  3026. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3027. TryConstMerge(p, hp1) then
  3028. begin
  3029. Result := True;
  3030. { In case we have four byte writes in a row, check for 2 more
  3031. right now so we don't have to wait for another iteration of
  3032. pass 1
  3033. }
  3034. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3035. case taicpu(p).opsize of
  3036. S_W:
  3037. begin
  3038. if GetNextInstruction(p, hp1) and
  3039. MatchInstruction(hp1, A_MOV, [S_B]) and
  3040. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3041. GetNextInstruction(hp1, hp2) and
  3042. MatchInstruction(hp2, A_MOV, [S_B]) and
  3043. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3044. { Try to merge the two bytes }
  3045. TryConstMerge(hp1, hp2) then
  3046. { Now try to merge the two words (hp2 will get deleted) }
  3047. TryConstMerge(p, hp1);
  3048. end;
  3049. S_L:
  3050. begin
  3051. { Though this only really benefits x86_64 and not i386, it
  3052. gets a potential optimisation done faster and hence
  3053. reduces the number of times OptPass1MOV is entered }
  3054. if GetNextInstruction(p, hp1) and
  3055. MatchInstruction(hp1, A_MOV, [S_W]) and
  3056. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3057. GetNextInstruction(hp1, hp2) and
  3058. MatchInstruction(hp2, A_MOV, [S_W]) and
  3059. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3060. { Try to merge the two words }
  3061. TryConstMerge(hp1, hp2) then
  3062. { This will always fail on i386, so don't bother
  3063. calling it unless we're doing x86_64 }
  3064. {$ifdef x86_64}
  3065. { Now try to merge the two longwords (hp2 will get deleted) }
  3066. TryConstMerge(p, hp1)
  3067. {$endif x86_64}
  3068. ;
  3069. end;
  3070. else
  3071. ;
  3072. end;
  3073. Exit;
  3074. end;
  3075. if (taicpu(p).oper[1]^.typ = top_reg) and
  3076. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3077. begin
  3078. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3079. TransferUsedRegs(TmpUsedRegs);
  3080. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3081. { we have
  3082. mov x, %treg
  3083. mov %treg, y
  3084. }
  3085. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3086. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3087. { we've got
  3088. mov x, %treg
  3089. mov %treg, y
  3090. with %treg is not used after }
  3091. case taicpu(p).oper[0]^.typ Of
  3092. { top_reg is covered by DeepMOVOpt }
  3093. top_const:
  3094. begin
  3095. { change
  3096. mov const, %treg
  3097. mov %treg, y
  3098. to
  3099. mov const, y
  3100. }
  3101. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3102. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3103. begin
  3104. if taicpu(hp1).oper[1]^.typ=top_reg then
  3105. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3106. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3107. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3108. RemoveInstruction(hp1);
  3109. Result:=true;
  3110. Exit;
  3111. end;
  3112. end;
  3113. top_ref:
  3114. case taicpu(hp1).oper[1]^.typ of
  3115. top_reg:
  3116. begin
  3117. { change
  3118. mov mem, %treg
  3119. mov %treg, %reg
  3120. to
  3121. mov mem, %reg"
  3122. }
  3123. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3124. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3125. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3126. RemoveInstruction(hp1);
  3127. Result:=true;
  3128. Exit;
  3129. end;
  3130. top_ref:
  3131. begin
  3132. {$ifdef x86_64}
  3133. { Look for the following to simplify:
  3134. mov x(mem1), %reg
  3135. mov %reg, y(mem2)
  3136. mov x+8(mem1), %reg
  3137. mov %reg, y+8(mem2)
  3138. Change to:
  3139. movdqu x(mem1), %xmmreg
  3140. movdqu %xmmreg, y(mem2)
  3141. ...but only as long as the memory blocks don't overlap
  3142. }
  3143. SourceRef := taicpu(p).oper[0]^.ref^;
  3144. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3145. if (taicpu(p).opsize = S_Q) and
  3146. GetNextInstruction(hp1, hp2) and
  3147. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3148. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3149. begin
  3150. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3151. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3152. Inc(SourceRef.offset, 8);
  3153. if UseAVX then
  3154. begin
  3155. MovAligned := A_VMOVDQA;
  3156. MovUnaligned := A_VMOVDQU;
  3157. end
  3158. else
  3159. begin
  3160. MovAligned := A_MOVDQA;
  3161. MovUnaligned := A_MOVDQU;
  3162. end;
  3163. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3164. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3165. begin
  3166. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3167. Inc(TargetRef.offset, 8);
  3168. if GetNextInstruction(hp2, hp3) and
  3169. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3170. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3171. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3172. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3173. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3174. begin
  3175. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3176. if NewMMReg <> NR_NO then
  3177. begin
  3178. { Remember that the offsets are 8 ahead }
  3179. if ((SourceRef.offset mod 16) = 8) and
  3180. (
  3181. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3182. (SourceRef.base = current_procinfo.framepointer) or
  3183. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3184. ) then
  3185. taicpu(p).opcode := MovAligned
  3186. else
  3187. taicpu(p).opcode := MovUnaligned;
  3188. taicpu(p).opsize := S_XMM;
  3189. taicpu(p).oper[1]^.reg := NewMMReg;
  3190. if ((TargetRef.offset mod 16) = 8) and
  3191. (
  3192. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3193. (TargetRef.base = current_procinfo.framepointer) or
  3194. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3195. ) then
  3196. taicpu(hp1).opcode := MovAligned
  3197. else
  3198. taicpu(hp1).opcode := MovUnaligned;
  3199. taicpu(hp1).opsize := S_XMM;
  3200. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3201. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3202. RemoveInstruction(hp2);
  3203. RemoveInstruction(hp3);
  3204. Result := True;
  3205. Exit;
  3206. end;
  3207. end;
  3208. end
  3209. else
  3210. begin
  3211. { See if the next references are 8 less rather than 8 greater }
  3212. Dec(SourceRef.offset, 16); { -8 the other way }
  3213. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3214. begin
  3215. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3216. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3217. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3218. GetNextInstruction(hp2, hp3) and
  3219. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3220. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3221. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3222. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3223. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3224. begin
  3225. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3226. if NewMMReg <> NR_NO then
  3227. begin
  3228. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3229. if ((SourceRef.offset mod 16) = 0) and
  3230. (
  3231. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3232. (SourceRef.base = current_procinfo.framepointer) or
  3233. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3234. ) then
  3235. taicpu(hp2).opcode := MovAligned
  3236. else
  3237. taicpu(hp2).opcode := MovUnaligned;
  3238. taicpu(hp2).opsize := S_XMM;
  3239. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3240. if ((TargetRef.offset mod 16) = 0) and
  3241. (
  3242. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3243. (TargetRef.base = current_procinfo.framepointer) or
  3244. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3245. ) then
  3246. taicpu(hp3).opcode := MovAligned
  3247. else
  3248. taicpu(hp3).opcode := MovUnaligned;
  3249. taicpu(hp3).opsize := S_XMM;
  3250. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3251. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3252. RemoveInstruction(hp1);
  3253. RemoveCurrentP(p, hp2);
  3254. Result := True;
  3255. Exit;
  3256. end;
  3257. end;
  3258. end;
  3259. end;
  3260. end;
  3261. {$endif x86_64}
  3262. end;
  3263. else
  3264. { The write target should be a reg or a ref }
  3265. InternalError(2021091601);
  3266. end;
  3267. else
  3268. ;
  3269. end
  3270. else
  3271. { %treg is used afterwards, but all eventualities
  3272. other than the first MOV instruction being a constant
  3273. are covered by DeepMOVOpt, so only check for that }
  3274. if (taicpu(p).oper[0]^.typ = top_const) and
  3275. (
  3276. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3277. not (cs_opt_size in current_settings.optimizerswitches) or
  3278. (taicpu(hp1).opsize = S_B)
  3279. ) and
  3280. (
  3281. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3282. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3283. ) then
  3284. begin
  3285. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3286. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3287. end;
  3288. end;
  3289. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3290. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3291. { mov reg1, mem1 or mov mem1, reg1
  3292. mov mem2, reg2 mov reg2, mem2}
  3293. begin
  3294. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3295. { mov reg1, mem1 or mov mem1, reg1
  3296. mov mem2, reg1 mov reg2, mem1}
  3297. begin
  3298. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3299. { Removes the second statement from
  3300. mov reg1, mem1/reg2
  3301. mov mem1/reg2, reg1 }
  3302. begin
  3303. if taicpu(p).oper[0]^.typ=top_reg then
  3304. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3305. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3306. RemoveInstruction(hp1);
  3307. Result:=true;
  3308. exit;
  3309. end
  3310. else
  3311. begin
  3312. TransferUsedRegs(TmpUsedRegs);
  3313. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3314. if (taicpu(p).oper[1]^.typ = top_ref) and
  3315. { mov reg1, mem1
  3316. mov mem2, reg1 }
  3317. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3318. GetNextInstruction(hp1, hp2) and
  3319. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3320. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3321. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3322. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3323. { change to
  3324. mov reg1, mem1 mov reg1, mem1
  3325. mov mem2, reg1 cmp reg1, mem2
  3326. cmp mem1, reg1
  3327. }
  3328. begin
  3329. RemoveInstruction(hp2);
  3330. taicpu(hp1).opcode := A_CMP;
  3331. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3332. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3333. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3334. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3335. end;
  3336. end;
  3337. end
  3338. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3339. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3340. begin
  3341. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3342. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3343. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3344. end
  3345. else
  3346. begin
  3347. TransferUsedRegs(TmpUsedRegs);
  3348. if GetNextInstruction(hp1, hp2) and
  3349. MatchOpType(taicpu(p),top_ref,top_reg) and
  3350. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3351. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3352. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3353. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3354. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3355. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3356. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3357. { mov mem1, %reg1
  3358. mov %reg1, mem2
  3359. mov mem2, reg2
  3360. to:
  3361. mov mem1, reg2
  3362. mov reg2, mem2}
  3363. begin
  3364. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3365. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3366. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3367. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3368. RemoveInstruction(hp2);
  3369. Result := True;
  3370. end
  3371. {$ifdef i386}
  3372. { this is enabled for i386 only, as the rules to create the reg sets below
  3373. are too complicated for x86-64, so this makes this code too error prone
  3374. on x86-64
  3375. }
  3376. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3377. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3378. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3379. { mov mem1, reg1 mov mem1, reg1
  3380. mov reg1, mem2 mov reg1, mem2
  3381. mov mem2, reg2 mov mem2, reg1
  3382. to: to:
  3383. mov mem1, reg1 mov mem1, reg1
  3384. mov mem1, reg2 mov reg1, mem2
  3385. mov reg1, mem2
  3386. or (if mem1 depends on reg1
  3387. and/or if mem2 depends on reg2)
  3388. to:
  3389. mov mem1, reg1
  3390. mov reg1, mem2
  3391. mov reg1, reg2
  3392. }
  3393. begin
  3394. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3395. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3396. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3397. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3398. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3399. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3400. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3401. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3402. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3403. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3404. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3405. end
  3406. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3407. begin
  3408. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3409. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3410. end
  3411. else
  3412. begin
  3413. RemoveInstruction(hp2);
  3414. end
  3415. {$endif i386}
  3416. ;
  3417. end;
  3418. end
  3419. { movl [mem1],reg1
  3420. movl [mem1],reg2
  3421. to
  3422. movl [mem1],reg1
  3423. movl reg1,reg2
  3424. }
  3425. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3426. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3427. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3428. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3429. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3430. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3431. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3432. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3433. begin
  3434. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3435. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3436. end;
  3437. { movl const1,[mem1]
  3438. movl [mem1],reg1
  3439. to
  3440. movl const1,reg1
  3441. movl reg1,[mem1]
  3442. }
  3443. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3444. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3445. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3446. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3447. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3448. begin
  3449. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3450. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3451. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3452. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3453. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3454. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3455. Result:=true;
  3456. exit;
  3457. end;
  3458. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3459. { Change:
  3460. movl %reg1,%reg2
  3461. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3462. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3463. To:
  3464. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3465. movl x(%reg1),%reg1
  3466. movl %reg1,%regX
  3467. }
  3468. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3469. begin
  3470. p_SourceReg := taicpu(p).oper[0]^.reg;
  3471. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3472. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3473. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3474. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3475. GetNextInstruction(hp1, hp2) and
  3476. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3477. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3478. begin
  3479. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3480. if RegInRef(p_TargetReg, SourceRef) and
  3481. { If %reg1 also appears in the second reference, then it will
  3482. not refer to the same memory block as the first reference }
  3483. not RegInRef(p_SourceReg, SourceRef) then
  3484. begin
  3485. { Check to see if the references match if %reg2 is changed to %reg1 }
  3486. if SourceRef.base = p_TargetReg then
  3487. SourceRef.base := p_SourceReg;
  3488. if SourceRef.index = p_TargetReg then
  3489. SourceRef.index := p_SourceReg;
  3490. { RefsEqual also checks to ensure both references are non-volatile }
  3491. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3492. begin
  3493. taicpu(hp2).loadreg(0, p_SourceReg);
  3494. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3495. Result := True;
  3496. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3497. begin
  3498. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3499. RemoveCurrentP(p, hp1);
  3500. Exit;
  3501. end
  3502. else
  3503. begin
  3504. { Check to see if %reg2 is no longer in use }
  3505. TransferUsedRegs(TmpUsedRegs);
  3506. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3507. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3508. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3509. begin
  3510. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3511. RemoveCurrentP(p, hp1);
  3512. Exit;
  3513. end;
  3514. end;
  3515. { If we reach this point, p and hp1 weren't actually modified,
  3516. so we can do a bit more work on this pass }
  3517. end;
  3518. end;
  3519. end;
  3520. end;
  3521. end;
  3522. { search further than the next instruction for a mov (as long as it's not a jump) }
  3523. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3524. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3525. (taicpu(p).oper[1]^.typ = top_reg) and
  3526. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3527. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3528. begin
  3529. { we work with hp2 here, so hp1 can be still used later on when
  3530. checking for GetNextInstruction_p }
  3531. hp3 := hp1;
  3532. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3533. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3534. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3535. TransferUsedRegs(TmpUsedRegs);
  3536. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3537. if NotFirstIteration then
  3538. JumpTracking := TLinkedList.Create
  3539. else
  3540. JumpTracking := nil;
  3541. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3542. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3543. (hp2.typ=ait_instruction) do
  3544. begin
  3545. case taicpu(hp2).opcode of
  3546. A_POP:
  3547. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3548. begin
  3549. if not CrossJump and
  3550. not RegUsedBetween(p_TargetReg, p, hp2) then
  3551. begin
  3552. { We can remove the original MOV since the register
  3553. wasn't used between it and its popping from the stack }
  3554. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3555. RemoveCurrentp(p, hp1);
  3556. Result := True;
  3557. JumpTracking.Free;
  3558. Exit;
  3559. end;
  3560. { Can't go any further }
  3561. Break;
  3562. end;
  3563. A_MOV:
  3564. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3565. ((taicpu(p).oper[0]^.typ=top_const) or
  3566. ((taicpu(p).oper[0]^.typ=top_reg) and
  3567. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3568. )
  3569. ) then
  3570. begin
  3571. { we have
  3572. mov x, %treg
  3573. mov %treg, y
  3574. }
  3575. { We don't need to call UpdateUsedRegs for every instruction between
  3576. p and hp2 because the register we're concerned about will not
  3577. become deallocated (otherwise GetNextInstructionUsingReg would
  3578. have stopped at an earlier instruction). [Kit] }
  3579. TempRegUsed :=
  3580. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3581. RegReadByInstruction(p_TargetReg, hp3) or
  3582. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3583. case taicpu(p).oper[0]^.typ Of
  3584. top_reg:
  3585. begin
  3586. { change
  3587. mov %reg, %treg
  3588. mov %treg, y
  3589. to
  3590. mov %reg, y
  3591. }
  3592. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3593. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3594. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3595. begin
  3596. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3597. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3598. if TempRegUsed then
  3599. begin
  3600. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3601. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3602. { Set the start of the next GetNextInstructionUsingRegCond search
  3603. to start at the entry right before hp2 (which is about to be removed) }
  3604. hp3 := tai(hp2.Previous);
  3605. RemoveInstruction(hp2);
  3606. { See if there's more we can optimise }
  3607. Continue;
  3608. end
  3609. else
  3610. begin
  3611. RemoveInstruction(hp2);
  3612. { We can remove the original MOV too }
  3613. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3614. RemoveCurrentP(p, hp1);
  3615. Result:=true;
  3616. JumpTracking.Free;
  3617. Exit;
  3618. end;
  3619. end
  3620. else
  3621. begin
  3622. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3623. taicpu(hp2).loadReg(0, p_SourceReg);
  3624. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3625. { Check to see if the register also appears in the reference }
  3626. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3627. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3628. { Don't remove the first instruction if the temporary register is in use }
  3629. if not TempRegUsed and
  3630. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3631. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3632. begin
  3633. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3634. RemoveCurrentP(p, hp1);
  3635. Result:=true;
  3636. JumpTracking.Free;
  3637. Exit;
  3638. end;
  3639. { No need to set Result to True here. If there's another instruction later
  3640. on that can be optimised, it will be detected when the main Pass 1 loop
  3641. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3642. end;
  3643. end;
  3644. top_const:
  3645. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3646. begin
  3647. { change
  3648. mov const, %treg
  3649. mov %treg, y
  3650. to
  3651. mov const, y
  3652. }
  3653. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3654. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3655. begin
  3656. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3657. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3658. if TempRegUsed then
  3659. begin
  3660. { Don't remove the first instruction if the temporary register is in use }
  3661. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3662. { No need to set Result to True. If there's another instruction later on
  3663. that can be optimised, it will be detected when the main Pass 1 loop
  3664. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3665. end
  3666. else
  3667. begin
  3668. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3669. RemoveCurrentP(p, hp1);
  3670. Result:=true;
  3671. Exit;
  3672. end;
  3673. end;
  3674. end;
  3675. else
  3676. Internalerror(2019103001);
  3677. end;
  3678. end
  3679. else
  3680. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3681. begin
  3682. if not CrossJump and
  3683. not RegUsedBetween(p_TargetReg, p, hp2) and
  3684. not RegReadByInstruction(p_TargetReg, hp2) then
  3685. begin
  3686. { Register is not used before it is overwritten }
  3687. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3688. RemoveCurrentp(p, hp1);
  3689. Result := True;
  3690. Exit;
  3691. end;
  3692. if (taicpu(p).oper[0]^.typ = top_const) and
  3693. (taicpu(hp2).oper[0]^.typ = top_const) then
  3694. begin
  3695. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3696. begin
  3697. { Same value - register hasn't changed }
  3698. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3699. RemoveInstruction(hp2);
  3700. Result := True;
  3701. { See if there's more we can optimise }
  3702. Continue;
  3703. end;
  3704. end;
  3705. end;
  3706. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3707. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3708. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3709. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3710. begin
  3711. {
  3712. Change from:
  3713. mov ###, %reg
  3714. ...
  3715. movs/z %reg,%reg (Same register, just different sizes)
  3716. To:
  3717. movs/z ###, %reg (Longer version)
  3718. ...
  3719. (remove)
  3720. }
  3721. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3722. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3723. { Keep the first instruction as mov if ### is a constant }
  3724. if taicpu(p).oper[0]^.typ = top_const then
  3725. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3726. else
  3727. begin
  3728. taicpu(p).opcode := taicpu(hp2).opcode;
  3729. taicpu(p).opsize := taicpu(hp2).opsize;
  3730. end;
  3731. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3732. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3733. RemoveInstruction(hp2);
  3734. Result := True;
  3735. JumpTracking.Free;
  3736. Exit;
  3737. end;
  3738. else
  3739. { Move down to the MatchOpType if-block below };
  3740. end;
  3741. { Also catches MOV/S/Z instructions that aren't modified }
  3742. if taicpu(p).oper[0]^.typ = top_reg then
  3743. begin
  3744. p_SourceReg := taicpu(p).oper[0]^.reg;
  3745. if
  3746. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3747. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3748. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3749. begin
  3750. Result := True;
  3751. { Just in case something didn't get modified (e.g. an
  3752. implicit register). Also, if it does read from this
  3753. register, then there's no longer an advantage to
  3754. changing the register on subsequent instructions.}
  3755. if not RegReadByInstruction(p_TargetReg, hp2) then
  3756. begin
  3757. { If a conditional jump was crossed, do not delete
  3758. the original MOV no matter what }
  3759. if not CrossJump and
  3760. { RegEndOfLife returns True if the register is
  3761. deallocated before the next instruction or has
  3762. been loaded with a new value }
  3763. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3764. begin
  3765. { We can remove the original MOV }
  3766. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3767. RemoveCurrentp(p, hp1);
  3768. JumpTracking.Free;
  3769. Result := True;
  3770. Exit;
  3771. end;
  3772. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3773. begin
  3774. { See if there's more we can optimise }
  3775. hp3 := hp2;
  3776. Continue;
  3777. end;
  3778. end;
  3779. end;
  3780. end;
  3781. { Break out of the while loop under normal circumstances }
  3782. Break;
  3783. end;
  3784. JumpTracking.Free;
  3785. end;
  3786. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3787. (taicpu(p).oper[1]^.typ = top_reg) and
  3788. (taicpu(p).opsize = S_L) and
  3789. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3790. (hp2.typ = ait_instruction) and
  3791. (taicpu(hp2).opcode = A_AND) and
  3792. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3793. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3794. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3795. ) then
  3796. begin
  3797. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3798. begin
  3799. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3800. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3801. begin
  3802. { Optimize out:
  3803. mov x, %reg
  3804. and ffffffffh, %reg
  3805. }
  3806. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3807. RemoveInstruction(hp2);
  3808. Result:=true;
  3809. exit;
  3810. end;
  3811. end;
  3812. end;
  3813. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3814. x >= RetOffset) as it doesn't do anything (it writes either to a
  3815. parameter or to the temporary storage room for the function
  3816. result)
  3817. }
  3818. if IsExitCode(hp1) and
  3819. (taicpu(p).oper[1]^.typ = top_ref) and
  3820. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3821. (
  3822. (
  3823. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3824. not (
  3825. assigned(current_procinfo.procdef.funcretsym) and
  3826. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3827. )
  3828. ) or
  3829. { Also discard writes to the stack that are below the base pointer,
  3830. as this is temporary storage rather than a function result on the
  3831. stack, say. }
  3832. (
  3833. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3834. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3835. )
  3836. ) then
  3837. begin
  3838. RemoveCurrentp(p, hp1);
  3839. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3840. RemoveLastDeallocForFuncRes(p);
  3841. Result:=true;
  3842. exit;
  3843. end;
  3844. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3845. begin
  3846. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3847. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3848. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3849. begin
  3850. { change
  3851. mov reg1, mem1
  3852. test/cmp x, mem1
  3853. to
  3854. mov reg1, mem1
  3855. test/cmp x, reg1
  3856. }
  3857. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3858. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3859. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3860. Result := True;
  3861. Exit;
  3862. end;
  3863. if DoMovCmpMemOpt(p, hp1, True) then
  3864. begin
  3865. Result := True;
  3866. Exit;
  3867. end;
  3868. end;
  3869. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3870. { If the flags register is in use, don't change the instruction to an
  3871. ADD otherwise this will scramble the flags. [Kit] }
  3872. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3873. begin
  3874. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3875. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3876. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3877. ) or
  3878. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3879. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3880. )
  3881. ) then
  3882. { mov reg1,ref
  3883. lea reg2,[reg1,reg2]
  3884. to
  3885. add reg2,ref}
  3886. begin
  3887. TransferUsedRegs(TmpUsedRegs);
  3888. { reg1 may not be used afterwards }
  3889. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3890. begin
  3891. Taicpu(hp1).opcode:=A_ADD;
  3892. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3893. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3894. RemoveCurrentp(p, hp1);
  3895. result:=true;
  3896. exit;
  3897. end;
  3898. end;
  3899. { If the LEA instruction can be converted into an arithmetic instruction,
  3900. it may be possible to then fold it in the next optimisation, otherwise
  3901. there's nothing more that can be optimised here. }
  3902. if not ConvertLEA(taicpu(hp1)) then
  3903. Exit;
  3904. end;
  3905. if (taicpu(p).oper[1]^.typ = top_reg) and
  3906. (hp1.typ = ait_instruction) and
  3907. GetNextInstruction(hp1, hp2) and
  3908. MatchInstruction(hp2,A_MOV,[]) and
  3909. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3910. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3911. (
  3912. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3913. {$ifdef x86_64}
  3914. or
  3915. (
  3916. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3917. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3918. )
  3919. {$endif x86_64}
  3920. ) then
  3921. begin
  3922. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3923. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3924. { change movsX/movzX reg/ref, reg2
  3925. add/sub/or/... reg3/$const, reg2
  3926. mov reg2 reg/ref
  3927. dealloc reg2
  3928. to
  3929. add/sub/or/... reg3/$const, reg/ref }
  3930. begin
  3931. TransferUsedRegs(TmpUsedRegs);
  3932. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3933. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3934. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3935. begin
  3936. { by example:
  3937. movswl %si,%eax movswl %si,%eax p
  3938. decl %eax addl %edx,%eax hp1
  3939. movw %ax,%si movw %ax,%si hp2
  3940. ->
  3941. movswl %si,%eax movswl %si,%eax p
  3942. decw %eax addw %edx,%eax hp1
  3943. movw %ax,%si movw %ax,%si hp2
  3944. }
  3945. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3946. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3947. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3948. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3949. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3950. {
  3951. ->
  3952. movswl %si,%eax movswl %si,%eax p
  3953. decw %si addw %dx,%si hp1
  3954. movw %ax,%si movw %ax,%si hp2
  3955. }
  3956. case taicpu(hp1).ops of
  3957. 1:
  3958. begin
  3959. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3960. if taicpu(hp1).oper[0]^.typ=top_reg then
  3961. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3962. end;
  3963. 2:
  3964. begin
  3965. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3966. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3967. (taicpu(hp1).opcode<>A_SHL) and
  3968. (taicpu(hp1).opcode<>A_SHR) and
  3969. (taicpu(hp1).opcode<>A_SAR) then
  3970. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3971. end;
  3972. else
  3973. internalerror(2008042701);
  3974. end;
  3975. {
  3976. ->
  3977. decw %si addw %dx,%si p
  3978. }
  3979. RemoveInstruction(hp2);
  3980. RemoveCurrentP(p, hp1);
  3981. Result:=True;
  3982. Exit;
  3983. end;
  3984. end;
  3985. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3986. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3987. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3988. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3989. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3990. )
  3991. {$ifdef i386}
  3992. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3993. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3994. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3995. {$endif i386}
  3996. then
  3997. { change movsX/movzX reg/ref, reg2
  3998. add/sub/or/... regX/$const, reg2
  3999. mov reg2, reg3
  4000. dealloc reg2
  4001. to
  4002. movsX/movzX reg/ref, reg3
  4003. add/sub/or/... reg3/$const, reg3
  4004. }
  4005. begin
  4006. TransferUsedRegs(TmpUsedRegs);
  4007. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4008. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4009. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4010. begin
  4011. { by example:
  4012. movswl %si,%eax movswl %si,%eax p
  4013. decl %eax addl %edx,%eax hp1
  4014. movw %ax,%si movw %ax,%si hp2
  4015. ->
  4016. movswl %si,%eax movswl %si,%eax p
  4017. decw %eax addw %edx,%eax hp1
  4018. movw %ax,%si movw %ax,%si hp2
  4019. }
  4020. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4021. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4022. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4023. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4024. { limit size of constants as well to avoid assembler errors, but
  4025. check opsize to avoid overflow when left shifting the 1 }
  4026. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4027. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4028. {$ifdef x86_64}
  4029. { Be careful of, for example:
  4030. movl %reg1,%reg2
  4031. addl %reg3,%reg2
  4032. movq %reg2,%reg4
  4033. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4034. }
  4035. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4036. begin
  4037. taicpu(hp2).changeopsize(S_L);
  4038. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4039. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4040. end;
  4041. {$endif x86_64}
  4042. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4043. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4044. if taicpu(p).oper[0]^.typ=top_reg then
  4045. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4046. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4047. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4048. {
  4049. ->
  4050. movswl %si,%eax movswl %si,%eax p
  4051. decw %si addw %dx,%si hp1
  4052. movw %ax,%si movw %ax,%si hp2
  4053. }
  4054. case taicpu(hp1).ops of
  4055. 1:
  4056. begin
  4057. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4058. if taicpu(hp1).oper[0]^.typ=top_reg then
  4059. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4060. end;
  4061. 2:
  4062. begin
  4063. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4064. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4065. (taicpu(hp1).opcode<>A_SHL) and
  4066. (taicpu(hp1).opcode<>A_SHR) and
  4067. (taicpu(hp1).opcode<>A_SAR) then
  4068. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4069. end;
  4070. else
  4071. internalerror(2018111801);
  4072. end;
  4073. {
  4074. ->
  4075. decw %si addw %dx,%si p
  4076. }
  4077. RemoveInstruction(hp2);
  4078. end;
  4079. end;
  4080. end;
  4081. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4082. GetNextInstruction(hp1, hp2) and
  4083. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4084. MatchOperand(Taicpu(p).oper[0]^,0) and
  4085. (Taicpu(p).oper[1]^.typ = top_reg) and
  4086. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4087. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4088. { mov reg1,0
  4089. bts reg1,operand1 --> mov reg1,operand2
  4090. or reg1,operand2 bts reg1,operand1}
  4091. begin
  4092. Taicpu(hp2).opcode:=A_MOV;
  4093. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4094. asml.remove(hp1);
  4095. insertllitem(hp2,hp2.next,hp1);
  4096. RemoveCurrentp(p, hp1);
  4097. Result:=true;
  4098. exit;
  4099. end;
  4100. {
  4101. mov ref,reg0
  4102. <op> reg0,reg1
  4103. dealloc reg0
  4104. to
  4105. <op> ref,reg1
  4106. }
  4107. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4108. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4109. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4110. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4111. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4112. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4113. begin
  4114. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4115. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4116. RemoveCurrentp(p, hp1);
  4117. Result:=true;
  4118. exit;
  4119. end;
  4120. {$ifdef x86_64}
  4121. { Convert:
  4122. movq x(ref),%reg64
  4123. shrq y,%reg64
  4124. To:
  4125. movl x+4(ref),%reg32
  4126. shrl y-32,%reg32 (Remove if y = 32)
  4127. }
  4128. if (taicpu(p).opsize = S_Q) and
  4129. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4130. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  4131. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  4132. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4133. (taicpu(hp1).oper[0]^.val >= 32) and
  4134. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4135. begin
  4136. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4137. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4138. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4139. { Convert to 32-bit }
  4140. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4141. taicpu(p).opsize := S_L;
  4142. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4143. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4144. if (taicpu(hp1).oper[0]^.val = 32) then
  4145. begin
  4146. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4147. RemoveInstruction(hp1);
  4148. end
  4149. else
  4150. begin
  4151. { This will potentially open up more arithmetic operations since
  4152. the peephole optimizer now has a big hint that only the lower
  4153. 32 bits are currently in use (and opcodes are smaller in size) }
  4154. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4155. taicpu(hp1).opsize := S_L;
  4156. Dec(taicpu(hp1).oper[0]^.val, 32);
  4157. DebugMsg(SPeepholeOptimization + PreMessage +
  4158. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4159. end;
  4160. Result := True;
  4161. Exit;
  4162. end;
  4163. {$endif x86_64}
  4164. { Backward optimisation. If we have:
  4165. func. %reg1,%reg2
  4166. mov %reg2,%reg3
  4167. (dealloc %reg2)
  4168. Change to:
  4169. func. %reg1,%reg3 (see comment below for what a valid func. is)
  4170. }
  4171. if MatchOpType(taicpu(p), top_reg, top_reg) then
  4172. begin
  4173. p_SourceReg := taicpu(p).oper[0]^.reg;
  4174. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4175. TransferUsedRegs(TmpUsedRegs);
  4176. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  4177. GetLastInstruction(p, hp2) and
  4178. (hp2.typ = ait_instruction) and
  4179. { Have to make sure it's an instruction that only reads from
  4180. operand 1 and only writes (not reads or modifies) from operand 2;
  4181. in essence, a one-operand pure function such as BSR or POPCNT }
  4182. (taicpu(hp2).ops = 2) and
  4183. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  4184. (taicpu(hp2).oper[1]^.typ = top_reg) and
  4185. (taicpu(hp2).oper[1]^.reg = p_SourceReg) then
  4186. begin
  4187. case taicpu(hp2).opcode of
  4188. A_FSTSW, A_FNSTSW,
  4189. A_IN, A_INS, A_OUT, A_OUTS,
  4190. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  4191. { These routines have explicit operands, but they are restricted in
  4192. what they can be (e.g. IN and OUT can only read from AL, AX or
  4193. EAX. }
  4194. ;
  4195. else
  4196. begin
  4197. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  4198. taicpu(hp2).oper[1]^.reg := p_TargetReg;
  4199. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  4200. RemoveCurrentp(p, hp1);
  4201. Result := True;
  4202. Exit;
  4203. end;
  4204. end;
  4205. end;
  4206. end;
  4207. end;
  4208. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4209. var
  4210. hp1 : tai;
  4211. begin
  4212. Result:=false;
  4213. if taicpu(p).ops <> 2 then
  4214. exit;
  4215. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4216. GetNextInstruction(p,hp1) then
  4217. begin
  4218. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4219. (taicpu(hp1).ops = 2) then
  4220. begin
  4221. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4222. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4223. { movXX reg1, mem1 or movXX mem1, reg1
  4224. movXX mem2, reg2 movXX reg2, mem2}
  4225. begin
  4226. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4227. { movXX reg1, mem1 or movXX mem1, reg1
  4228. movXX mem2, reg1 movXX reg2, mem1}
  4229. begin
  4230. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4231. begin
  4232. { Removes the second statement from
  4233. movXX reg1, mem1/reg2
  4234. movXX mem1/reg2, reg1
  4235. }
  4236. if taicpu(p).oper[0]^.typ=top_reg then
  4237. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4238. { Removes the second statement from
  4239. movXX mem1/reg1, reg2
  4240. movXX reg2, mem1/reg1
  4241. }
  4242. if (taicpu(p).oper[1]^.typ=top_reg) and
  4243. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4244. begin
  4245. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4246. RemoveInstruction(hp1);
  4247. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4248. Result:=true;
  4249. exit;
  4250. end
  4251. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4252. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4253. begin
  4254. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4255. RemoveInstruction(hp1);
  4256. Result:=true;
  4257. exit;
  4258. end;
  4259. end
  4260. end;
  4261. end;
  4262. end;
  4263. end;
  4264. end;
  4265. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4266. var
  4267. hp1 : tai;
  4268. begin
  4269. result:=false;
  4270. { replace
  4271. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4272. MovX %mreg2,%mreg1
  4273. dealloc %mreg2
  4274. by
  4275. <Op>X %mreg2,%mreg1
  4276. ?
  4277. }
  4278. if GetNextInstruction(p,hp1) and
  4279. { we mix single and double opperations here because we assume that the compiler
  4280. generates vmovapd only after double operations and vmovaps only after single operations }
  4281. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4282. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4283. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4284. (taicpu(p).oper[0]^.typ=top_reg) then
  4285. begin
  4286. TransferUsedRegs(TmpUsedRegs);
  4287. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4288. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4289. begin
  4290. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4291. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4292. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4293. RemoveInstruction(hp1);
  4294. result:=true;
  4295. end;
  4296. end;
  4297. end;
  4298. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4299. var
  4300. hp1, p_label, p_dist, hp1_dist: tai;
  4301. JumpLabel, JumpLabel_dist: TAsmLabel;
  4302. FirstValue, SecondValue: TCGInt;
  4303. begin
  4304. Result := False;
  4305. if (taicpu(p).oper[0]^.typ = top_const) and
  4306. (taicpu(p).oper[0]^.val <> -1) then
  4307. begin
  4308. { Convert unsigned maximum constants to -1 to aid optimisation }
  4309. case taicpu(p).opsize of
  4310. S_B:
  4311. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4312. begin
  4313. taicpu(p).oper[0]^.val := -1;
  4314. Result := True;
  4315. Exit;
  4316. end;
  4317. S_W:
  4318. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4319. begin
  4320. taicpu(p).oper[0]^.val := -1;
  4321. Result := True;
  4322. Exit;
  4323. end;
  4324. S_L:
  4325. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4326. begin
  4327. taicpu(p).oper[0]^.val := -1;
  4328. Result := True;
  4329. Exit;
  4330. end;
  4331. {$ifdef x86_64}
  4332. S_Q:
  4333. { Storing anything greater than $7FFFFFFF is not possible so do
  4334. nothing };
  4335. {$endif x86_64}
  4336. else
  4337. InternalError(2021121001);
  4338. end;
  4339. end;
  4340. if GetNextInstruction(p, hp1) and
  4341. TrySwapMovCmp(p, hp1) then
  4342. begin
  4343. Result := True;
  4344. Exit;
  4345. end;
  4346. { Search for:
  4347. test $x,(reg/ref)
  4348. jne @lbl1
  4349. test $y,(reg/ref) (same register or reference)
  4350. jne @lbl1
  4351. Change to:
  4352. test $(x or y),(reg/ref)
  4353. jne @lbl1
  4354. (Note, this doesn't work with je instead of jne)
  4355. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4356. Also search for:
  4357. test $x,(reg/ref)
  4358. je @lbl1
  4359. test $y,(reg/ref)
  4360. je/jne @lbl2
  4361. If (x or y) = x, then the second jump is deterministic
  4362. }
  4363. if (
  4364. (
  4365. (taicpu(p).oper[0]^.typ = top_const) or
  4366. (
  4367. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4368. (taicpu(p).oper[0]^.typ = top_reg) and
  4369. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4370. )
  4371. ) and
  4372. MatchInstruction(hp1, A_JCC, [])
  4373. ) then
  4374. begin
  4375. if (taicpu(p).oper[0]^.typ = top_reg) and
  4376. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4377. FirstValue := -1
  4378. else
  4379. FirstValue := taicpu(p).oper[0]^.val;
  4380. { If we have several test/jne's in a row, it might be the case that
  4381. the second label doesn't go to the same location, but the one
  4382. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4383. so accommodate for this with a while loop.
  4384. }
  4385. hp1_dist := hp1;
  4386. if GetNextInstruction(hp1, p_dist) and
  4387. (p_dist.typ = ait_instruction) and
  4388. (
  4389. (
  4390. (taicpu(p_dist).opcode = A_TEST) and
  4391. (
  4392. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4393. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4394. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4395. )
  4396. ) or
  4397. (
  4398. { cmp 0,%reg = test %reg,%reg }
  4399. (taicpu(p_dist).opcode = A_CMP) and
  4400. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4401. )
  4402. ) and
  4403. { Make sure the destination operands are actually the same }
  4404. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4405. GetNextInstruction(p_dist, hp1_dist) and
  4406. MatchInstruction(hp1_dist, A_JCC, []) then
  4407. begin
  4408. if
  4409. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4410. (
  4411. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4412. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4413. ) then
  4414. SecondValue := -1
  4415. else
  4416. SecondValue := taicpu(p_dist).oper[0]^.val;
  4417. { If both of the TEST constants are identical, delete the second
  4418. TEST that is unnecessary. }
  4419. if (FirstValue = SecondValue) then
  4420. begin
  4421. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4422. RemoveInstruction(p_dist);
  4423. { Don't let the flags register become deallocated and reallocated between the jumps }
  4424. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4425. Result := True;
  4426. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4427. begin
  4428. { Since the second jump's condition is a subset of the first, we
  4429. know it will never branch because the first jump dominates it.
  4430. Get it out of the way now rather than wait for the jump
  4431. optimisations for a speed boost. }
  4432. if IsJumpToLabel(taicpu(hp1_dist)) then
  4433. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4434. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4435. RemoveInstruction(hp1_dist);
  4436. end
  4437. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4438. begin
  4439. { If the inverse of the first condition is a subset of the second,
  4440. the second one will definitely branch if the first one doesn't }
  4441. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4442. MakeUnconditional(taicpu(hp1_dist));
  4443. RemoveDeadCodeAfterJump(hp1_dist);
  4444. end;
  4445. Exit;
  4446. end;
  4447. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4448. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4449. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4450. then the second jump will never branch, so it can also be
  4451. removed regardless of where it goes }
  4452. (
  4453. (FirstValue = -1) or
  4454. (SecondValue = -1) or
  4455. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4456. ) then
  4457. begin
  4458. { Same jump location... can be a register since nothing's changed }
  4459. { If any of the entries are equivalent to test %reg,%reg, then the
  4460. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4461. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4462. if IsJumpToLabel(taicpu(hp1_dist)) then
  4463. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4464. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4465. RemoveInstruction(hp1_dist);
  4466. { Only remove the second test if no jumps or other conditional instructions follow }
  4467. TransferUsedRegs(TmpUsedRegs);
  4468. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4469. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4470. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4471. RemoveInstruction(p_dist);
  4472. Result := True;
  4473. Exit;
  4474. end;
  4475. end;
  4476. end;
  4477. { Search for:
  4478. test %reg,%reg
  4479. j(c1) @lbl1
  4480. ...
  4481. @lbl:
  4482. test %reg,%reg (same register)
  4483. j(c2) @lbl2
  4484. If c2 is a subset of c1, change to:
  4485. test %reg,%reg
  4486. j(c1) @lbl2
  4487. (@lbl1 may become a dead label as a result)
  4488. }
  4489. if (taicpu(p).oper[1]^.typ = top_reg) and
  4490. (taicpu(p).oper[0]^.typ = top_reg) and
  4491. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4492. MatchInstruction(hp1, A_JCC, []) and
  4493. IsJumpToLabel(taicpu(hp1)) then
  4494. begin
  4495. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4496. p_label := nil;
  4497. if Assigned(JumpLabel) then
  4498. p_label := getlabelwithsym(JumpLabel);
  4499. if Assigned(p_label) and
  4500. GetNextInstruction(p_label, p_dist) and
  4501. MatchInstruction(p_dist, A_TEST, []) and
  4502. { It's fine if the second test uses smaller sub-registers }
  4503. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4504. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4505. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4506. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4507. GetNextInstruction(p_dist, hp1_dist) and
  4508. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4509. begin
  4510. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4511. if JumpLabel = JumpLabel_dist then
  4512. { This is an infinite loop }
  4513. Exit;
  4514. { Best optimisation when the first condition is a subset (or equal) of the second }
  4515. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4516. begin
  4517. { Any registers used here will already be allocated }
  4518. if Assigned(JumpLabel_dist) then
  4519. JumpLabel_dist.IncRefs;
  4520. if Assigned(JumpLabel) then
  4521. JumpLabel.DecRefs;
  4522. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4523. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4524. Result := True;
  4525. Exit;
  4526. end;
  4527. end;
  4528. end;
  4529. end;
  4530. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4531. var
  4532. hp1, hp2: tai;
  4533. ActiveReg: TRegister;
  4534. OldOffset: asizeint;
  4535. ThisConst: TCGInt;
  4536. function RegDeallocated: Boolean;
  4537. begin
  4538. TransferUsedRegs(TmpUsedRegs);
  4539. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4540. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4541. end;
  4542. begin
  4543. result:=false;
  4544. hp1 := nil;
  4545. { replace
  4546. addX const,%reg1
  4547. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4548. dealloc %reg1
  4549. by
  4550. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4551. }
  4552. if MatchOpType(taicpu(p),top_const,top_reg) then
  4553. begin
  4554. ActiveReg := taicpu(p).oper[1]^.reg;
  4555. { Ensures the entire register was updated }
  4556. if (taicpu(p).opsize >= S_L) and
  4557. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4558. MatchInstruction(hp1,A_LEA,[]) and
  4559. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4560. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4561. (
  4562. { Cover the case where the register in the reference is also the destination register }
  4563. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4564. (
  4565. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4566. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4567. RegDeallocated
  4568. )
  4569. ) then
  4570. begin
  4571. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4572. {$push}
  4573. {$R-}{$Q-}
  4574. { Explicitly disable overflow checking for these offset calculation
  4575. as those do not matter for the final result }
  4576. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4577. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4578. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4579. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4580. {$pop}
  4581. {$ifdef x86_64}
  4582. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4583. begin
  4584. { Overflow; abort }
  4585. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4586. end
  4587. else
  4588. {$endif x86_64}
  4589. begin
  4590. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4591. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4592. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4593. RemoveCurrentP(p, hp1)
  4594. else
  4595. RemoveCurrentP(p);
  4596. result:=true;
  4597. Exit;
  4598. end;
  4599. end;
  4600. if (
  4601. { Save calling GetNextInstructionUsingReg again }
  4602. Assigned(hp1) or
  4603. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4604. ) and
  4605. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4606. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4607. begin
  4608. if taicpu(hp1).oper[0]^.typ = top_const then
  4609. begin
  4610. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4611. if taicpu(hp1).opcode = A_ADD then
  4612. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4613. else
  4614. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4615. Result := True;
  4616. { Handle any overflows }
  4617. case taicpu(p).opsize of
  4618. S_B:
  4619. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4620. S_W:
  4621. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4622. S_L:
  4623. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4624. {$ifdef x86_64}
  4625. S_Q:
  4626. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4627. { Overflow; abort }
  4628. Result := False
  4629. else
  4630. taicpu(p).oper[0]^.val := ThisConst;
  4631. {$endif x86_64}
  4632. else
  4633. InternalError(2021102610);
  4634. end;
  4635. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4636. if Result then
  4637. begin
  4638. if (taicpu(p).oper[0]^.val < 0) and
  4639. (
  4640. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4641. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4642. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4643. ) then
  4644. begin
  4645. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4646. taicpu(p).opcode := A_SUB;
  4647. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4648. end
  4649. else
  4650. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4651. RemoveInstruction(hp1);
  4652. end;
  4653. end
  4654. else
  4655. begin
  4656. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4657. TransferUsedRegs(TmpUsedRegs);
  4658. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4659. hp2 := p;
  4660. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4661. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4662. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4663. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4664. begin
  4665. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4666. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4667. Asml.Remove(p);
  4668. Asml.InsertAfter(p, hp1);
  4669. p := hp1;
  4670. Result := True;
  4671. end;
  4672. end;
  4673. end;
  4674. end;
  4675. end;
  4676. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4677. var
  4678. hp1: tai;
  4679. ref: Integer;
  4680. saveref: treference;
  4681. Multiple: TCGInt;
  4682. Adjacent: Boolean;
  4683. begin
  4684. Result:=false;
  4685. { play save and throw an error if LEA uses a seg register prefix,
  4686. this is most likely an error somewhere else }
  4687. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4688. internalerror(2022022001);
  4689. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4690. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4691. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4692. (
  4693. { do not mess with leas accessing the stack pointer
  4694. unless it's a null operation }
  4695. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4696. (
  4697. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4698. (taicpu(p).oper[0]^.ref^.offset = 0)
  4699. )
  4700. ) and
  4701. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4702. begin
  4703. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4704. begin
  4705. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4706. begin
  4707. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4708. taicpu(p).oper[1]^.reg);
  4709. InsertLLItem(p.previous,p.next, hp1);
  4710. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4711. p.free;
  4712. p:=hp1;
  4713. end
  4714. else
  4715. begin
  4716. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4717. RemoveCurrentP(p);
  4718. end;
  4719. Result:=true;
  4720. exit;
  4721. end
  4722. else if (
  4723. { continue to use lea to adjust the stack pointer,
  4724. it is the recommended way, but only if not optimizing for size }
  4725. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4726. (cs_opt_size in current_settings.optimizerswitches)
  4727. ) and
  4728. { If the flags register is in use, don't change the instruction
  4729. to an ADD otherwise this will scramble the flags. [Kit] }
  4730. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4731. ConvertLEA(taicpu(p)) then
  4732. begin
  4733. Result:=true;
  4734. exit;
  4735. end;
  4736. end;
  4737. { Don't optimise if the stack or frame pointer is the destination register }
  4738. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  4739. Exit;
  4740. if GetNextInstruction(p,hp1) and
  4741. (hp1.typ=ait_instruction) then
  4742. begin
  4743. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4744. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4745. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  4746. begin
  4747. TransferUsedRegs(TmpUsedRegs);
  4748. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4749. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4750. begin
  4751. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4752. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4753. RemoveInstruction(hp1);
  4754. result:=true;
  4755. exit;
  4756. end;
  4757. end;
  4758. { changes
  4759. lea <ref1>, reg1
  4760. <op> ...,<ref. with reg1>,...
  4761. to
  4762. <op> ...,<ref1>,... }
  4763. { find a reference which uses reg1 }
  4764. 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
  4765. ref:=0
  4766. 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
  4767. ref:=1
  4768. else
  4769. ref:=-1;
  4770. if (ref<>-1) and
  4771. { reg1 must be either the base or the index }
  4772. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4773. begin
  4774. { reg1 can be removed from the reference }
  4775. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4776. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4777. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4778. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4779. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4780. else
  4781. Internalerror(2019111201);
  4782. { check if the can insert all data of the lea into the second instruction }
  4783. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4784. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4785. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4786. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4787. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4788. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4789. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4790. {$ifdef x86_64}
  4791. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4792. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4793. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4794. )
  4795. {$endif x86_64}
  4796. then
  4797. begin
  4798. { reg1 might not used by the second instruction after it is remove from the reference }
  4799. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4800. begin
  4801. TransferUsedRegs(TmpUsedRegs);
  4802. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4803. { reg1 is not updated so it might not be used afterwards }
  4804. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4805. begin
  4806. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4807. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4808. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4809. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4810. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4811. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4812. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4813. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4814. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4815. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4816. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4817. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4818. RemoveCurrentP(p, hp1);
  4819. result:=true;
  4820. exit;
  4821. end
  4822. end;
  4823. end;
  4824. { recover }
  4825. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4826. end;
  4827. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  4828. if Adjacent or
  4829. { Check further ahead (up to 2 instructions ahead for -O2) }
  4830. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  4831. begin
  4832. { Check common LEA/LEA conditions }
  4833. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4834. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4835. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4836. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4837. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4838. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4839. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4840. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4841. (
  4842. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  4843. calling it (since it calls GetNextInstruction) }
  4844. Adjacent or
  4845. (
  4846. (
  4847. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4848. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4849. ) and (
  4850. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4851. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4852. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4853. )
  4854. )
  4855. ) then
  4856. begin
  4857. { changes
  4858. lea (regX,scale), reg1
  4859. lea offset(reg1,reg1), reg1
  4860. to
  4861. lea offset(regX,scale*2), reg1
  4862. and
  4863. lea (regX,scale1), reg1
  4864. lea offset(reg1,scale2), reg1
  4865. to
  4866. lea offset(regX,scale1*scale2), reg1
  4867. ... so long as the final scale does not exceed 8
  4868. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4869. }
  4870. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  4871. (taicpu(p).oper[0]^.ref^.offset = 0) and
  4872. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4873. (
  4874. (
  4875. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4876. ) or (
  4877. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4878. (
  4879. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4880. (
  4881. { RegUsedBetween always returns False if p and hp1 are adjacent }
  4882. Adjacent or
  4883. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4884. )
  4885. )
  4886. )
  4887. ) and (
  4888. (
  4889. { lea (reg1,scale2), reg1 variant }
  4890. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4891. (
  4892. (
  4893. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4894. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4895. ) or (
  4896. { lea (regX,regX), reg1 variant }
  4897. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4898. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4899. )
  4900. )
  4901. ) or (
  4902. { lea (reg1,reg1), reg1 variant }
  4903. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4904. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4905. )
  4906. ) then
  4907. begin
  4908. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4909. { Make everything homogeneous to make calculations easier }
  4910. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4911. begin
  4912. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4913. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4914. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4915. else
  4916. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4917. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4918. end;
  4919. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4920. begin
  4921. { Just to prevent miscalculations }
  4922. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4923. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4924. else
  4925. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4926. end
  4927. else
  4928. begin
  4929. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4930. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4931. end;
  4932. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4933. RemoveCurrentP(p);
  4934. result:=true;
  4935. exit;
  4936. end
  4937. { changes
  4938. lea offset1(regX), reg1
  4939. lea offset2(reg1), reg1
  4940. to
  4941. lea offset1+offset2(regX), reg1 }
  4942. else if
  4943. (
  4944. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4945. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4946. ) or (
  4947. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4948. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4949. (
  4950. (
  4951. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4952. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4953. ) or (
  4954. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4955. (
  4956. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4957. (
  4958. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4959. (
  4960. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4961. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4962. )
  4963. )
  4964. )
  4965. )
  4966. )
  4967. ) then
  4968. begin
  4969. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4970. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4971. begin
  4972. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4973. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4974. { if the register is used as index and base, we have to increase for base as well
  4975. and adapt base }
  4976. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4977. begin
  4978. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4979. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4980. end;
  4981. end
  4982. else
  4983. begin
  4984. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4985. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4986. end;
  4987. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4988. begin
  4989. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4990. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4991. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4992. end;
  4993. RemoveCurrentP(p);
  4994. result:=true;
  4995. exit;
  4996. end;
  4997. end;
  4998. { Change:
  4999. leal/q $x(%reg1),%reg2
  5000. ...
  5001. shll/q $y,%reg2
  5002. To:
  5003. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5004. }
  5005. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5006. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5007. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5008. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5009. (taicpu(hp1).oper[0]^.val <= 3) then
  5010. begin
  5011. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5012. TransferUsedRegs(TmpUsedRegs);
  5013. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5014. if
  5015. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5016. (this works even if scalefactor is zero) }
  5017. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5018. { Ensure offset doesn't go out of bounds }
  5019. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5020. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5021. (
  5022. (
  5023. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5024. (
  5025. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5026. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5027. (
  5028. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5029. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5030. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5031. )
  5032. )
  5033. ) or (
  5034. (
  5035. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5036. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5037. ) and
  5038. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5039. )
  5040. ) then
  5041. begin
  5042. repeat
  5043. with taicpu(p).oper[0]^.ref^ do
  5044. begin
  5045. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5046. if index = base then
  5047. begin
  5048. if Multiple > 4 then
  5049. { Optimisation will no longer work because resultant
  5050. scale factor will exceed 8 }
  5051. Break;
  5052. base := NR_NO;
  5053. scalefactor := 2;
  5054. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5055. end
  5056. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5057. begin
  5058. { Scale factor only works on the index register }
  5059. index := base;
  5060. base := NR_NO;
  5061. end;
  5062. { For safety }
  5063. if scalefactor <= 1 then
  5064. begin
  5065. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5066. scalefactor := Multiple;
  5067. end
  5068. else
  5069. begin
  5070. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5071. scalefactor := scalefactor * Multiple;
  5072. end;
  5073. offset := offset * Multiple;
  5074. end;
  5075. RemoveInstruction(hp1);
  5076. Result := True;
  5077. Exit;
  5078. { This repeat..until loop exists for the benefit of Break }
  5079. until True;
  5080. end;
  5081. end;
  5082. end;
  5083. end;
  5084. end;
  5085. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  5086. var
  5087. hp1 : tai;
  5088. begin
  5089. DoSubAddOpt := False;
  5090. if taicpu(p).oper[0]^.typ <> top_const then
  5091. { Should have been confirmed before calling }
  5092. InternalError(2021102601);
  5093. if GetLastInstruction(p, hp1) and
  5094. (hp1.typ = ait_instruction) and
  5095. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5096. case taicpu(hp1).opcode Of
  5097. A_DEC:
  5098. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5099. begin
  5100. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  5101. RemoveInstruction(hp1);
  5102. end;
  5103. A_SUB:
  5104. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5105. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5106. begin
  5107. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  5108. RemoveInstruction(hp1);
  5109. end;
  5110. A_ADD:
  5111. begin
  5112. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5113. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5114. begin
  5115. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  5116. RemoveInstruction(hp1);
  5117. if (taicpu(p).oper[0]^.val = 0) then
  5118. begin
  5119. hp1 := tai(p.next);
  5120. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5121. if not GetLastInstruction(hp1, p) then
  5122. p := hp1;
  5123. DoSubAddOpt := True;
  5124. end
  5125. end;
  5126. end;
  5127. else
  5128. ;
  5129. end;
  5130. end;
  5131. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5132. begin
  5133. Result := False;
  5134. if UpdateTmpUsedRegs then
  5135. TransferUsedRegs(TmpUsedRegs);
  5136. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5137. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5138. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5139. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5140. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5141. (
  5142. (
  5143. (taicpu(hp1).opcode = A_TEST)
  5144. ) or (
  5145. (taicpu(hp1).opcode = A_CMP) and
  5146. { A sanity check more than anything }
  5147. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5148. )
  5149. ) then
  5150. begin
  5151. { change
  5152. mov mem, %reg
  5153. cmp/test x, %reg / test %reg,%reg
  5154. (reg deallocated)
  5155. to
  5156. cmp/test x, mem / cmp 0, mem
  5157. }
  5158. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5159. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5160. begin
  5161. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5162. if (taicpu(hp1).opcode = A_TEST) and
  5163. (
  5164. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5165. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5166. ) then
  5167. begin
  5168. taicpu(hp1).opcode := A_CMP;
  5169. taicpu(hp1).loadconst(0, 0);
  5170. end;
  5171. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5172. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5173. RemoveCurrentP(p, hp1);
  5174. Result := True;
  5175. Exit;
  5176. end;
  5177. end;
  5178. end;
  5179. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5180. var
  5181. hp2, hp3, hp4, hp5, hp6: tai;
  5182. ThisReg: TRegister;
  5183. JumpLoc: TAsmLabel;
  5184. begin
  5185. Result := False;
  5186. {
  5187. Convert:
  5188. j<c> .L1
  5189. .L2:
  5190. mov 1,reg
  5191. jmp .L3 (or ret, although it might not be a RET yet)
  5192. .L1:
  5193. mov 0,reg
  5194. jmp .L3 (or ret)
  5195. ( As long as .L3 <> .L1 or .L2)
  5196. To:
  5197. mov 0,reg
  5198. set<not(c)> reg
  5199. jmp .L3 (or ret)
  5200. .L2:
  5201. mov 1,reg
  5202. jmp .L3 (or ret)
  5203. .L1:
  5204. mov 0,reg
  5205. jmp .L3 (or ret)
  5206. }
  5207. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5208. Exit;
  5209. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5210. if GetNextInstruction(hp_label, hp2) and
  5211. MatchInstruction(hp2,A_MOV,[]) and
  5212. (taicpu(hp2).oper[0]^.typ = top_const) and
  5213. (
  5214. (
  5215. (taicpu(hp2).oper[1]^.typ = top_reg)
  5216. {$ifdef i386}
  5217. { Under i386, ESI, EDI, EBP and ESP
  5218. don't have an 8-bit representation }
  5219. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5220. {$endif i386}
  5221. ) or (
  5222. {$ifdef i386}
  5223. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5224. {$endif i386}
  5225. (taicpu(hp2).opsize = S_B)
  5226. )
  5227. ) and
  5228. GetNextInstruction(hp2, hp3) and
  5229. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5230. (
  5231. (taicpu(hp3).opcode=A_RET) or
  5232. (
  5233. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5234. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5235. )
  5236. ) and
  5237. GetNextInstruction(hp3, hp4) and
  5238. SkipAligns(hp4, hp4) and
  5239. (hp4.typ=ait_label) and
  5240. (tai_label(hp4).labsym=JumpLoc) and
  5241. (
  5242. not (cs_opt_size in current_settings.optimizerswitches) or
  5243. { If the initial jump is the label's only reference, then it will
  5244. become a dead label if the other conditions are met and hence
  5245. remove at least 2 instructions, including a jump }
  5246. (JumpLoc.getrefs = 1)
  5247. ) and
  5248. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5249. that will be optimised out }
  5250. GetNextInstruction(hp4, hp5) and
  5251. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5252. (taicpu(hp5).oper[0]^.typ = top_const) and
  5253. (
  5254. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5255. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5256. ) and
  5257. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5258. GetNextInstruction(hp5,hp6) and
  5259. (
  5260. (hp6.typ<>ait_label) or
  5261. SkipLabels(hp6, hp6)
  5262. ) and
  5263. (hp6.typ=ait_instruction) then
  5264. begin
  5265. { First, let's look at the two jumps that are hp3 and hp6 }
  5266. if not
  5267. (
  5268. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5269. (
  5270. (taicpu(hp6).opcode=A_RET) or
  5271. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5272. )
  5273. ) then
  5274. { If condition is False, then the JMP/RET instructions matched conventionally }
  5275. begin
  5276. { See if one of the jumps can be instantly converted into a RET }
  5277. if (taicpu(hp3).opcode=A_JMP) then
  5278. begin
  5279. { Reuse hp5 }
  5280. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5281. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5282. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5283. Exit;
  5284. if MatchInstruction(hp5, A_RET, []) then
  5285. begin
  5286. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5287. ConvertJumpToRET(hp3, hp5);
  5288. Result := True;
  5289. end
  5290. else
  5291. Exit;
  5292. end;
  5293. if (taicpu(hp6).opcode=A_JMP) then
  5294. begin
  5295. { Reuse hp5 }
  5296. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5297. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5298. Exit;
  5299. if MatchInstruction(hp5, A_RET, []) then
  5300. begin
  5301. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5302. ConvertJumpToRET(hp6, hp5);
  5303. Result := True;
  5304. end
  5305. else
  5306. Exit;
  5307. end;
  5308. if not
  5309. (
  5310. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5311. (
  5312. (taicpu(hp6).opcode=A_RET) or
  5313. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5314. )
  5315. ) then
  5316. { Still doesn't match }
  5317. Exit;
  5318. end;
  5319. if (taicpu(hp2).oper[0]^.val = 1) then
  5320. begin
  5321. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5322. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5323. end
  5324. else
  5325. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5326. if taicpu(hp2).opsize=S_B then
  5327. begin
  5328. if taicpu(hp2).oper[1]^.typ = top_reg then
  5329. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5330. else
  5331. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5332. hp2 := p;
  5333. end
  5334. else
  5335. begin
  5336. { Will be a register because the size can't be S_B otherwise }
  5337. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5338. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5339. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5340. { Inserting it right before p will guarantee that the flags are also tracked }
  5341. Asml.InsertBefore(hp2, p);
  5342. end;
  5343. taicpu(hp4).condition:=taicpu(p).condition;
  5344. asml.InsertBefore(hp4, hp2);
  5345. JumpLoc.decrefs;
  5346. if taicpu(hp3).opcode = A_JMP then
  5347. begin
  5348. MakeUnconditional(taicpu(p));
  5349. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5350. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5351. end
  5352. else
  5353. begin
  5354. taicpu(p).condition := C_None;
  5355. taicpu(p).opcode := A_RET;
  5356. taicpu(p).clearop(0);
  5357. taicpu(p).ops := 0;
  5358. end;
  5359. if (JumpLoc.getrefs = 0) then
  5360. RemoveDeadCodeAfterJump(hp3);
  5361. Result:=true;
  5362. exit;
  5363. end;
  5364. end;
  5365. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5366. var
  5367. hp1, hp2: tai;
  5368. ActiveReg: TRegister;
  5369. OldOffset: asizeint;
  5370. ThisConst: TCGInt;
  5371. function RegDeallocated: Boolean;
  5372. begin
  5373. TransferUsedRegs(TmpUsedRegs);
  5374. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5375. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5376. end;
  5377. begin
  5378. Result:=false;
  5379. hp1 := nil;
  5380. { replace
  5381. subX const,%reg1
  5382. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5383. dealloc %reg1
  5384. by
  5385. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5386. }
  5387. if MatchOpType(taicpu(p),top_const,top_reg) then
  5388. begin
  5389. ActiveReg := taicpu(p).oper[1]^.reg;
  5390. { Ensures the entire register was updated }
  5391. if (taicpu(p).opsize >= S_L) and
  5392. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5393. MatchInstruction(hp1,A_LEA,[]) and
  5394. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5395. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5396. (
  5397. { Cover the case where the register in the reference is also the destination register }
  5398. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5399. (
  5400. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5401. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5402. RegDeallocated
  5403. )
  5404. ) then
  5405. begin
  5406. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5407. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5408. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5409. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5410. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5411. {$ifdef x86_64}
  5412. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5413. begin
  5414. { Overflow; abort }
  5415. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5416. end
  5417. else
  5418. {$endif x86_64}
  5419. begin
  5420. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5421. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5422. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5423. RemoveCurrentP(p, hp1)
  5424. else
  5425. RemoveCurrentP(p);
  5426. result:=true;
  5427. Exit;
  5428. end;
  5429. end;
  5430. if (
  5431. { Save calling GetNextInstructionUsingReg again }
  5432. Assigned(hp1) or
  5433. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5434. ) and
  5435. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5436. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5437. begin
  5438. if taicpu(hp1).oper[0]^.typ = top_const then
  5439. begin
  5440. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5441. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5442. Result := True;
  5443. { Handle any overflows }
  5444. case taicpu(p).opsize of
  5445. S_B:
  5446. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5447. S_W:
  5448. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5449. S_L:
  5450. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5451. {$ifdef x86_64}
  5452. S_Q:
  5453. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5454. { Overflow; abort }
  5455. Result := False
  5456. else
  5457. taicpu(p).oper[0]^.val := ThisConst;
  5458. {$endif x86_64}
  5459. else
  5460. InternalError(2021102610);
  5461. end;
  5462. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5463. if Result then
  5464. begin
  5465. if (taicpu(p).oper[0]^.val < 0) and
  5466. (
  5467. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5468. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5469. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5470. ) then
  5471. begin
  5472. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5473. taicpu(p).opcode := A_SUB;
  5474. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5475. end
  5476. else
  5477. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5478. RemoveInstruction(hp1);
  5479. end;
  5480. end
  5481. else
  5482. begin
  5483. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5484. TransferUsedRegs(TmpUsedRegs);
  5485. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5486. hp2 := p;
  5487. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5488. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5489. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5490. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5491. begin
  5492. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5493. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5494. Asml.Remove(p);
  5495. Asml.InsertAfter(p, hp1);
  5496. p := hp1;
  5497. Result := True;
  5498. Exit;
  5499. end;
  5500. end;
  5501. end;
  5502. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5503. { * change "sub/add const1, reg" or "dec reg" followed by
  5504. "sub const2, reg" to one "sub ..., reg" }
  5505. {$ifdef i386}
  5506. if (taicpu(p).oper[0]^.val = 2) and
  5507. (ActiveReg = NR_ESP) and
  5508. { Don't do the sub/push optimization if the sub }
  5509. { comes from setting up the stack frame (JM) }
  5510. (not(GetLastInstruction(p,hp1)) or
  5511. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5512. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5513. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5514. begin
  5515. hp1 := tai(p.next);
  5516. while Assigned(hp1) and
  5517. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5518. not RegReadByInstruction(NR_ESP,hp1) and
  5519. not RegModifiedByInstruction(NR_ESP,hp1) do
  5520. hp1 := tai(hp1.next);
  5521. if Assigned(hp1) and
  5522. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5523. begin
  5524. taicpu(hp1).changeopsize(S_L);
  5525. if taicpu(hp1).oper[0]^.typ=top_reg then
  5526. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5527. hp1 := tai(p.next);
  5528. RemoveCurrentp(p, hp1);
  5529. Result:=true;
  5530. exit;
  5531. end;
  5532. end;
  5533. {$endif i386}
  5534. if DoSubAddOpt(p) then
  5535. Result:=true;
  5536. end;
  5537. end;
  5538. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5539. var
  5540. TmpBool1,TmpBool2 : Boolean;
  5541. tmpref : treference;
  5542. hp1,hp2: tai;
  5543. mask: tcgint;
  5544. begin
  5545. Result:=false;
  5546. { All these optimisations work on "shl/sal const,%reg" }
  5547. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5548. Exit;
  5549. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5550. (taicpu(p).oper[0]^.val <= 3) then
  5551. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5552. begin
  5553. { should we check the next instruction? }
  5554. TmpBool1 := True;
  5555. { have we found an add/sub which could be
  5556. integrated in the lea? }
  5557. TmpBool2 := False;
  5558. reference_reset(tmpref,2,[]);
  5559. TmpRef.index := taicpu(p).oper[1]^.reg;
  5560. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5561. while TmpBool1 and
  5562. GetNextInstruction(p, hp1) and
  5563. (tai(hp1).typ = ait_instruction) and
  5564. ((((taicpu(hp1).opcode = A_ADD) or
  5565. (taicpu(hp1).opcode = A_SUB)) and
  5566. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5567. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5568. (((taicpu(hp1).opcode = A_INC) or
  5569. (taicpu(hp1).opcode = A_DEC)) and
  5570. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5571. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5572. ((taicpu(hp1).opcode = A_LEA) and
  5573. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5574. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5575. (not GetNextInstruction(hp1,hp2) or
  5576. not instrReadsFlags(hp2)) Do
  5577. begin
  5578. TmpBool1 := False;
  5579. if taicpu(hp1).opcode=A_LEA then
  5580. begin
  5581. if (TmpRef.base = NR_NO) and
  5582. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5583. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5584. { Segment register isn't a concern here }
  5585. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5586. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5587. begin
  5588. TmpBool1 := True;
  5589. TmpBool2 := True;
  5590. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5591. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5592. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5593. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5594. RemoveInstruction(hp1);
  5595. end
  5596. end
  5597. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5598. begin
  5599. TmpBool1 := True;
  5600. TmpBool2 := True;
  5601. case taicpu(hp1).opcode of
  5602. A_ADD:
  5603. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5604. A_SUB:
  5605. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5606. else
  5607. internalerror(2019050536);
  5608. end;
  5609. RemoveInstruction(hp1);
  5610. end
  5611. else
  5612. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5613. (((taicpu(hp1).opcode = A_ADD) and
  5614. (TmpRef.base = NR_NO)) or
  5615. (taicpu(hp1).opcode = A_INC) or
  5616. (taicpu(hp1).opcode = A_DEC)) then
  5617. begin
  5618. TmpBool1 := True;
  5619. TmpBool2 := True;
  5620. case taicpu(hp1).opcode of
  5621. A_ADD:
  5622. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5623. A_INC:
  5624. inc(TmpRef.offset);
  5625. A_DEC:
  5626. dec(TmpRef.offset);
  5627. else
  5628. internalerror(2019050535);
  5629. end;
  5630. RemoveInstruction(hp1);
  5631. end;
  5632. end;
  5633. if TmpBool2
  5634. {$ifndef x86_64}
  5635. or
  5636. ((current_settings.optimizecputype < cpu_Pentium2) and
  5637. (taicpu(p).oper[0]^.val <= 3) and
  5638. not(cs_opt_size in current_settings.optimizerswitches))
  5639. {$endif x86_64}
  5640. then
  5641. begin
  5642. if not(TmpBool2) and
  5643. (taicpu(p).oper[0]^.val=1) then
  5644. begin
  5645. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5646. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5647. end
  5648. else
  5649. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5650. taicpu(p).oper[1]^.reg);
  5651. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5652. InsertLLItem(p.previous, p.next, hp1);
  5653. p.free;
  5654. p := hp1;
  5655. end;
  5656. end
  5657. {$ifndef x86_64}
  5658. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5659. begin
  5660. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5661. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5662. (unlike shl, which is only Tairable in the U pipe) }
  5663. if taicpu(p).oper[0]^.val=1 then
  5664. begin
  5665. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5666. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5667. InsertLLItem(p.previous, p.next, hp1);
  5668. p.free;
  5669. p := hp1;
  5670. end
  5671. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5672. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5673. else if (taicpu(p).opsize = S_L) and
  5674. (taicpu(p).oper[0]^.val<= 3) then
  5675. begin
  5676. reference_reset(tmpref,2,[]);
  5677. TmpRef.index := taicpu(p).oper[1]^.reg;
  5678. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5679. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5680. InsertLLItem(p.previous, p.next, hp1);
  5681. p.free;
  5682. p := hp1;
  5683. end;
  5684. end
  5685. {$endif x86_64}
  5686. else if
  5687. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5688. (
  5689. (
  5690. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5691. SetAndTest(hp1, hp2)
  5692. {$ifdef x86_64}
  5693. ) or
  5694. (
  5695. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5696. GetNextInstruction(hp1, hp2) and
  5697. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5698. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5699. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5700. {$endif x86_64}
  5701. )
  5702. ) and
  5703. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5704. begin
  5705. { Change:
  5706. shl x, %reg1
  5707. mov -(1<<x), %reg2
  5708. and %reg2, %reg1
  5709. Or:
  5710. shl x, %reg1
  5711. and -(1<<x), %reg1
  5712. To just:
  5713. shl x, %reg1
  5714. Since the and operation only zeroes bits that are already zero from the shl operation
  5715. }
  5716. case taicpu(p).oper[0]^.val of
  5717. 8:
  5718. mask:=$FFFFFFFFFFFFFF00;
  5719. 16:
  5720. mask:=$FFFFFFFFFFFF0000;
  5721. 32:
  5722. mask:=$FFFFFFFF00000000;
  5723. 63:
  5724. { Constant pre-calculated to prevent overflow errors with Int64 }
  5725. mask:=$8000000000000000;
  5726. else
  5727. begin
  5728. if taicpu(p).oper[0]^.val >= 64 then
  5729. { Shouldn't happen realistically, since the register
  5730. is guaranteed to be set to zero at this point }
  5731. mask := 0
  5732. else
  5733. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5734. end;
  5735. end;
  5736. if taicpu(hp1).oper[0]^.val = mask then
  5737. begin
  5738. { Everything checks out, perform the optimisation, as long as
  5739. the FLAGS register isn't being used}
  5740. TransferUsedRegs(TmpUsedRegs);
  5741. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5742. {$ifdef x86_64}
  5743. if (hp1 <> hp2) then
  5744. begin
  5745. { "shl/mov/and" version }
  5746. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5747. { Don't do the optimisation if the FLAGS register is in use }
  5748. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5749. begin
  5750. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5751. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5752. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5753. begin
  5754. RemoveInstruction(hp1);
  5755. Result := True;
  5756. end;
  5757. { Only set Result to True if the 'mov' instruction was removed }
  5758. RemoveInstruction(hp2);
  5759. end;
  5760. end
  5761. else
  5762. {$endif x86_64}
  5763. begin
  5764. { "shl/and" version }
  5765. { Don't do the optimisation if the FLAGS register is in use }
  5766. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5767. begin
  5768. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5769. RemoveInstruction(hp1);
  5770. Result := True;
  5771. end;
  5772. end;
  5773. Exit;
  5774. end
  5775. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5776. begin
  5777. { Even if the mask doesn't allow for its removal, we might be
  5778. able to optimise the mask for the "shl/and" version, which
  5779. may permit other peephole optimisations }
  5780. {$ifdef DEBUG_AOPTCPU}
  5781. mask := taicpu(hp1).oper[0]^.val and mask;
  5782. if taicpu(hp1).oper[0]^.val <> mask then
  5783. begin
  5784. DebugMsg(
  5785. SPeepholeOptimization +
  5786. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5787. ' to $' + debug_tostr(mask) +
  5788. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5789. taicpu(hp1).oper[0]^.val := mask;
  5790. end;
  5791. {$else DEBUG_AOPTCPU}
  5792. { If debugging is off, just set the operand even if it's the same }
  5793. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5794. {$endif DEBUG_AOPTCPU}
  5795. end;
  5796. end;
  5797. {
  5798. change
  5799. shl/sal const,reg
  5800. <op> ...(...,reg,1),...
  5801. into
  5802. <op> ...(...,reg,1 shl const),...
  5803. if const in 1..3
  5804. }
  5805. if MatchOpType(taicpu(p), top_const, top_reg) and
  5806. (taicpu(p).oper[0]^.val in [1..3]) and
  5807. GetNextInstruction(p, hp1) and
  5808. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5809. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5810. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5811. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5812. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5813. begin
  5814. TransferUsedRegs(TmpUsedRegs);
  5815. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5816. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5817. begin
  5818. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5819. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5820. RemoveCurrentP(p);
  5821. Result:=true;
  5822. end;
  5823. end;
  5824. end;
  5825. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5826. var
  5827. CurrentRef: TReference;
  5828. FullReg: TRegister;
  5829. hp1, hp2: tai;
  5830. begin
  5831. Result := False;
  5832. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5833. Exit;
  5834. { We assume you've checked if the operand is actually a reference by
  5835. this point. If it isn't, you'll most likely get an access violation }
  5836. CurrentRef := first_mov.oper[1]^.ref^;
  5837. { Memory must be aligned }
  5838. if (CurrentRef.offset mod 4) <> 0 then
  5839. Exit;
  5840. Inc(CurrentRef.offset);
  5841. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5842. if MatchOperand(second_mov.oper[0]^, 0) and
  5843. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5844. GetNextInstruction(second_mov, hp1) and
  5845. (hp1.typ = ait_instruction) and
  5846. (taicpu(hp1).opcode = A_MOV) and
  5847. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5848. (taicpu(hp1).oper[0]^.val = 0) then
  5849. begin
  5850. Inc(CurrentRef.offset);
  5851. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5852. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5853. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5854. begin
  5855. case taicpu(hp1).opsize of
  5856. S_B:
  5857. if GetNextInstruction(hp1, hp2) and
  5858. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5859. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5860. (taicpu(hp2).oper[0]^.val = 0) then
  5861. begin
  5862. Inc(CurrentRef.offset);
  5863. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5864. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5865. (taicpu(hp2).opsize = S_B) then
  5866. begin
  5867. RemoveInstruction(hp1);
  5868. RemoveInstruction(hp2);
  5869. first_mov.opsize := S_L;
  5870. if first_mov.oper[0]^.typ = top_reg then
  5871. begin
  5872. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5873. { Reuse second_mov as a MOVZX instruction }
  5874. second_mov.opcode := A_MOVZX;
  5875. second_mov.opsize := S_BL;
  5876. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5877. second_mov.loadreg(1, FullReg);
  5878. first_mov.oper[0]^.reg := FullReg;
  5879. asml.Remove(second_mov);
  5880. asml.InsertBefore(second_mov, first_mov);
  5881. end
  5882. else
  5883. { It's a value }
  5884. begin
  5885. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5886. RemoveInstruction(second_mov);
  5887. end;
  5888. Result := True;
  5889. Exit;
  5890. end;
  5891. end;
  5892. S_W:
  5893. begin
  5894. RemoveInstruction(hp1);
  5895. first_mov.opsize := S_L;
  5896. if first_mov.oper[0]^.typ = top_reg then
  5897. begin
  5898. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5899. { Reuse second_mov as a MOVZX instruction }
  5900. second_mov.opcode := A_MOVZX;
  5901. second_mov.opsize := S_BL;
  5902. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5903. second_mov.loadreg(1, FullReg);
  5904. first_mov.oper[0]^.reg := FullReg;
  5905. asml.Remove(second_mov);
  5906. asml.InsertBefore(second_mov, first_mov);
  5907. end
  5908. else
  5909. { It's a value }
  5910. begin
  5911. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5912. RemoveInstruction(second_mov);
  5913. end;
  5914. Result := True;
  5915. Exit;
  5916. end;
  5917. else
  5918. ;
  5919. end;
  5920. end;
  5921. end;
  5922. end;
  5923. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5924. { returns true if a "continue" should be done after this optimization }
  5925. var
  5926. hp1, hp2: tai;
  5927. begin
  5928. Result := false;
  5929. if MatchOpType(taicpu(p),top_ref) and
  5930. GetNextInstruction(p, hp1) and
  5931. (hp1.typ = ait_instruction) and
  5932. (((taicpu(hp1).opcode = A_FLD) and
  5933. (taicpu(p).opcode = A_FSTP)) or
  5934. ((taicpu(p).opcode = A_FISTP) and
  5935. (taicpu(hp1).opcode = A_FILD))) and
  5936. MatchOpType(taicpu(hp1),top_ref) and
  5937. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5938. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5939. begin
  5940. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5941. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5942. GetNextInstruction(hp1, hp2) and
  5943. (hp2.typ = ait_instruction) and
  5944. IsExitCode(hp2) and
  5945. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5946. not(assigned(current_procinfo.procdef.funcretsym) and
  5947. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5948. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5949. begin
  5950. RemoveInstruction(hp1);
  5951. RemoveCurrentP(p, hp2);
  5952. RemoveLastDeallocForFuncRes(p);
  5953. Result := true;
  5954. end
  5955. else
  5956. { we can do this only in fast math mode as fstp is rounding ...
  5957. ... still disabled as it breaks the compiler and/or rtl }
  5958. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5959. { ... or if another fstp equal to the first one follows }
  5960. (GetNextInstruction(hp1,hp2) and
  5961. (hp2.typ = ait_instruction) and
  5962. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5963. (taicpu(p).opsize=taicpu(hp2).opsize))
  5964. ) and
  5965. { fst can't store an extended/comp value }
  5966. (taicpu(p).opsize <> S_FX) and
  5967. (taicpu(p).opsize <> S_IQ) then
  5968. begin
  5969. if (taicpu(p).opcode = A_FSTP) then
  5970. taicpu(p).opcode := A_FST
  5971. else
  5972. taicpu(p).opcode := A_FIST;
  5973. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5974. RemoveInstruction(hp1);
  5975. end;
  5976. end;
  5977. end;
  5978. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5979. var
  5980. hp1, hp2: tai;
  5981. begin
  5982. result:=false;
  5983. if MatchOpType(taicpu(p),top_reg) and
  5984. GetNextInstruction(p, hp1) and
  5985. (hp1.typ = Ait_Instruction) and
  5986. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5987. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5988. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5989. { change to
  5990. fld reg fxxx reg,st
  5991. fxxxp st, st1 (hp1)
  5992. Remark: non commutative operations must be reversed!
  5993. }
  5994. begin
  5995. case taicpu(hp1).opcode Of
  5996. A_FMULP,A_FADDP,
  5997. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5998. begin
  5999. case taicpu(hp1).opcode Of
  6000. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6001. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6002. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6003. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6004. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6005. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6006. else
  6007. internalerror(2019050534);
  6008. end;
  6009. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6010. taicpu(hp1).oper[1]^.reg := NR_ST;
  6011. RemoveCurrentP(p, hp1);
  6012. Result:=true;
  6013. exit;
  6014. end;
  6015. else
  6016. ;
  6017. end;
  6018. end
  6019. else
  6020. if MatchOpType(taicpu(p),top_ref) and
  6021. GetNextInstruction(p, hp2) and
  6022. (hp2.typ = Ait_Instruction) and
  6023. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6024. (taicpu(p).opsize in [S_FS, S_FL]) and
  6025. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6026. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6027. if GetLastInstruction(p, hp1) and
  6028. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6029. MatchOpType(taicpu(hp1),top_ref) and
  6030. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6031. if ((taicpu(hp2).opcode = A_FMULP) or
  6032. (taicpu(hp2).opcode = A_FADDP)) then
  6033. { change to
  6034. fld/fst mem1 (hp1) fld/fst mem1
  6035. fld mem1 (p) fadd/
  6036. faddp/ fmul st, st
  6037. fmulp st, st1 (hp2) }
  6038. begin
  6039. RemoveCurrentP(p, hp1);
  6040. if (taicpu(hp2).opcode = A_FADDP) then
  6041. taicpu(hp2).opcode := A_FADD
  6042. else
  6043. taicpu(hp2).opcode := A_FMUL;
  6044. taicpu(hp2).oper[1]^.reg := NR_ST;
  6045. end
  6046. else
  6047. { change to
  6048. fld/fst mem1 (hp1) fld/fst mem1
  6049. fld mem1 (p) fld st}
  6050. begin
  6051. taicpu(p).changeopsize(S_FL);
  6052. taicpu(p).loadreg(0,NR_ST);
  6053. end
  6054. else
  6055. begin
  6056. case taicpu(hp2).opcode Of
  6057. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6058. { change to
  6059. fld/fst mem1 (hp1) fld/fst mem1
  6060. fld mem2 (p) fxxx mem2
  6061. fxxxp st, st1 (hp2) }
  6062. begin
  6063. case taicpu(hp2).opcode Of
  6064. A_FADDP: taicpu(p).opcode := A_FADD;
  6065. A_FMULP: taicpu(p).opcode := A_FMUL;
  6066. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6067. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6068. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6069. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6070. else
  6071. internalerror(2019050533);
  6072. end;
  6073. RemoveInstruction(hp2);
  6074. end
  6075. else
  6076. ;
  6077. end
  6078. end
  6079. end;
  6080. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6081. begin
  6082. Result := condition_in(cond1, cond2) or
  6083. { Not strictly subsets due to the actual flags checked, but because we're
  6084. comparing integers, E is a subset of AE and GE and their aliases }
  6085. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6086. end;
  6087. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6088. var
  6089. v: TCGInt;
  6090. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6091. FirstMatch: Boolean;
  6092. NewReg: TRegister;
  6093. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6094. begin
  6095. Result:=false;
  6096. { All these optimisations need a next instruction }
  6097. if not GetNextInstruction(p, hp1) then
  6098. Exit;
  6099. { Search for:
  6100. cmp ###,###
  6101. j(c1) @lbl1
  6102. ...
  6103. @lbl:
  6104. cmp ###.### (same comparison as above)
  6105. j(c2) @lbl2
  6106. If c1 is a subset of c2, change to:
  6107. cmp ###,###
  6108. j(c2) @lbl2
  6109. (@lbl1 may become a dead label as a result)
  6110. }
  6111. { Also handle cases where there are multiple jumps in a row }
  6112. p_jump := hp1;
  6113. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6114. begin
  6115. if IsJumpToLabel(taicpu(p_jump)) then
  6116. begin
  6117. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6118. p_label := nil;
  6119. if Assigned(JumpLabel) then
  6120. p_label := getlabelwithsym(JumpLabel);
  6121. if Assigned(p_label) and
  6122. GetNextInstruction(p_label, p_dist) and
  6123. MatchInstruction(p_dist, A_CMP, []) and
  6124. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6125. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6126. GetNextInstruction(p_dist, hp1_dist) and
  6127. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6128. begin
  6129. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6130. if JumpLabel = JumpLabel_dist then
  6131. { This is an infinite loop }
  6132. Exit;
  6133. { Best optimisation when the first condition is a subset (or equal) of the second }
  6134. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6135. begin
  6136. { Any registers used here will already be allocated }
  6137. if Assigned(JumpLabel_dist) then
  6138. JumpLabel_dist.IncRefs;
  6139. if Assigned(JumpLabel) then
  6140. JumpLabel.DecRefs;
  6141. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6142. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  6143. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  6144. Result := True;
  6145. { Don't exit yet. Since p and p_jump haven't actually been
  6146. removed, we can check for more on this iteration }
  6147. end
  6148. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6149. GetNextInstruction(hp1_dist, hp1_label) and
  6150. SkipAligns(hp1_label, hp1_label) and
  6151. (hp1_label.typ = ait_label) then
  6152. begin
  6153. JumpLabel_far := tai_label(hp1_label).labsym;
  6154. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6155. { This is an infinite loop }
  6156. Exit;
  6157. if Assigned(JumpLabel_far) then
  6158. begin
  6159. { In this situation, if the first jump branches, the second one will never,
  6160. branch so change the destination label to after the second jump }
  6161. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6162. if Assigned(JumpLabel) then
  6163. JumpLabel.DecRefs;
  6164. JumpLabel_far.IncRefs;
  6165. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6166. Result := True;
  6167. { Don't exit yet. Since p and p_jump haven't actually been
  6168. removed, we can check for more on this iteration }
  6169. Continue;
  6170. end;
  6171. end;
  6172. end;
  6173. end;
  6174. { Search for:
  6175. cmp ###,###
  6176. j(c1) @lbl1
  6177. cmp ###,### (same as first)
  6178. Remove second cmp
  6179. }
  6180. if GetNextInstruction(p_jump, hp2) and
  6181. (
  6182. (
  6183. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6184. (
  6185. (
  6186. MatchOpType(taicpu(p), top_const, top_reg) and
  6187. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6188. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6189. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6190. ) or (
  6191. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6192. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6193. )
  6194. )
  6195. ) or (
  6196. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6197. MatchOperand(taicpu(p).oper[0]^, 0) and
  6198. (taicpu(p).oper[1]^.typ = top_reg) and
  6199. MatchInstruction(hp2, A_TEST, []) and
  6200. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6201. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6202. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6203. )
  6204. ) then
  6205. begin
  6206. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6207. RemoveInstruction(hp2);
  6208. Result := True;
  6209. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6210. end;
  6211. GetNextInstruction(p_jump, p_jump);
  6212. end;
  6213. {
  6214. Try to optimise the following:
  6215. cmp $x,### ($x and $y can be registers or constants)
  6216. je @lbl1 (only reference)
  6217. cmp $y,### (### are identical)
  6218. @Lbl:
  6219. sete %reg1
  6220. Change to:
  6221. cmp $x,###
  6222. sete %reg2 (allocate new %reg2)
  6223. cmp $y,###
  6224. sete %reg1
  6225. orb %reg2,%reg1
  6226. (dealloc %reg2)
  6227. This adds an instruction (so don't perform under -Os), but it removes
  6228. a conditional branch.
  6229. }
  6230. if not (cs_opt_size in current_settings.optimizerswitches) and
  6231. (
  6232. (hp1 = p_jump) or
  6233. GetNextInstruction(p, hp1)
  6234. ) and
  6235. MatchInstruction(hp1, A_Jcc, []) and
  6236. IsJumpToLabel(taicpu(hp1)) and
  6237. (taicpu(hp1).condition in [C_E, C_Z]) and
  6238. GetNextInstruction(hp1, hp2) and
  6239. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6240. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6241. { The first operand of CMP instructions can only be a register or
  6242. immediate anyway, so no need to check }
  6243. GetNextInstruction(hp2, p_label) and
  6244. (
  6245. (p_label.typ = ait_label) or
  6246. (
  6247. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6248. to potentially cut down on the iterations of Pass 1 }
  6249. MatchInstruction(p_label, A_Jcc, []) and
  6250. IsJumpToLabel(taicpu(p_label)) and
  6251. { Use p_dist to hold the jump briefly }
  6252. SetAndTest(p_label, p_dist) and
  6253. GetNextInstruction(p_dist, p_label) and
  6254. (p_label.typ = ait_label) and
  6255. (tai_label(p_label).labsym.getrefs >= 2) and
  6256. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6257. { We might as well collapse the jump now }
  6258. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6259. )
  6260. ) and
  6261. (tai_label(p_label).labsym.getrefs = 1) and
  6262. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6263. GetNextInstruction(p_label, p_dist) and
  6264. MatchInstruction(p_dist, A_SETcc, []) and
  6265. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6266. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6267. { Get the instruction after the SETcc instruction so we can
  6268. allocate a new register over the entire range }
  6269. GetNextInstruction(p_dist, hp1_dist) then
  6270. begin
  6271. TransferUsedRegs(TmpUsedRegs);
  6272. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6273. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6274. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6275. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6276. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6277. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6278. begin
  6279. { Register can appear in p if it's not used afterwards, so only
  6280. allocate between hp1 and hp1_dist }
  6281. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, p_dist);
  6282. if NewReg <> NR_NO then
  6283. begin
  6284. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6285. { Change the jump instruction into a SETcc instruction }
  6286. taicpu(hp1).opcode := A_SETcc;
  6287. taicpu(hp1).opsize := S_B;
  6288. taicpu(hp1).loadreg(0, NewReg);
  6289. { This is now a dead label }
  6290. tai_label(p_label).labsym.decrefs;
  6291. { Prefer adding before the next instruction so the FLAGS
  6292. register is deallocated first }
  6293. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6294. AsmL.InsertBefore(
  6295. hp2,
  6296. hp1_dist
  6297. );
  6298. { Make sure the new register is in use over the new instruction
  6299. (long-winded, but things work best when the FLAGS register
  6300. is not allocated here) }
  6301. AllocRegBetween(NewReg, p_dist, hp2, TmpUsedRegs);
  6302. Result := True;
  6303. { Don't exit yet, as p wasn't changed and hp1, while
  6304. modified, is still intact and might be optimised by the
  6305. SETcc optimisation below }
  6306. end;
  6307. end;
  6308. end;
  6309. if taicpu(p).oper[0]^.typ = top_const then
  6310. begin
  6311. if (taicpu(p).oper[0]^.val = 0) and
  6312. (taicpu(p).oper[1]^.typ = top_reg) and
  6313. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6314. begin
  6315. hp2 := p;
  6316. FirstMatch := True;
  6317. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6318. anything meaningful once it's converted to "test %reg,%reg";
  6319. additionally, some jumps will always (or never) branch, so
  6320. evaluate every jump immediately following the
  6321. comparison, optimising the conditions if possible.
  6322. Similarly with SETcc... those that are always set to 0 or 1
  6323. are changed to MOV instructions }
  6324. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6325. (
  6326. GetNextInstruction(hp2, hp1) and
  6327. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6328. ) do
  6329. begin
  6330. FirstMatch := False;
  6331. case taicpu(hp1).condition of
  6332. C_B, C_C, C_NAE, C_O:
  6333. { For B/NAE:
  6334. Will never branch since an unsigned integer can never be below zero
  6335. For C/O:
  6336. Result cannot overflow because 0 is being subtracted
  6337. }
  6338. begin
  6339. if taicpu(hp1).opcode = A_Jcc then
  6340. begin
  6341. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6342. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6343. RemoveInstruction(hp1);
  6344. { Since hp1 was deleted, hp2 must not be updated }
  6345. Continue;
  6346. end
  6347. else
  6348. begin
  6349. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6350. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6351. taicpu(hp1).opcode := A_MOV;
  6352. taicpu(hp1).ops := 2;
  6353. taicpu(hp1).condition := C_None;
  6354. taicpu(hp1).opsize := S_B;
  6355. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6356. taicpu(hp1).loadconst(0, 0);
  6357. end;
  6358. end;
  6359. C_BE, C_NA:
  6360. begin
  6361. { Will only branch if equal to zero }
  6362. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6363. taicpu(hp1).condition := C_E;
  6364. end;
  6365. C_A, C_NBE:
  6366. begin
  6367. { Will only branch if not equal to zero }
  6368. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6369. taicpu(hp1).condition := C_NE;
  6370. end;
  6371. C_AE, C_NB, C_NC, C_NO:
  6372. begin
  6373. { Will always branch }
  6374. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6375. if taicpu(hp1).opcode = A_Jcc then
  6376. begin
  6377. MakeUnconditional(taicpu(hp1));
  6378. { Any jumps/set that follow will now be dead code }
  6379. RemoveDeadCodeAfterJump(taicpu(hp1));
  6380. Break;
  6381. end
  6382. else
  6383. begin
  6384. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6385. taicpu(hp1).opcode := A_MOV;
  6386. taicpu(hp1).ops := 2;
  6387. taicpu(hp1).condition := C_None;
  6388. taicpu(hp1).opsize := S_B;
  6389. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6390. taicpu(hp1).loadconst(0, 1);
  6391. end;
  6392. end;
  6393. C_None:
  6394. InternalError(2020012201);
  6395. C_P, C_PE, C_NP, C_PO:
  6396. { We can't handle parity checks and they should never be generated
  6397. after a general-purpose CMP (it's used in some floating-point
  6398. comparisons that don't use CMP) }
  6399. InternalError(2020012202);
  6400. else
  6401. { Zero/Equality, Sign, their complements and all of the
  6402. signed comparisons do not need to be converted };
  6403. end;
  6404. hp2 := hp1;
  6405. end;
  6406. { Convert the instruction to a TEST }
  6407. taicpu(p).opcode := A_TEST;
  6408. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6409. Result := True;
  6410. Exit;
  6411. end
  6412. else if (taicpu(p).oper[0]^.val = 1) and
  6413. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6414. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6415. begin
  6416. { Convert; To:
  6417. cmp $1,r/m cmp $0,r/m
  6418. jl @lbl jle @lbl
  6419. }
  6420. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6421. taicpu(p).oper[0]^.val := 0;
  6422. taicpu(hp1).condition := C_LE;
  6423. { If the instruction is now "cmp $0,%reg", convert it to a
  6424. TEST (and effectively do the work of the "cmp $0,%reg" in
  6425. the block above)
  6426. If it's a reference, we can get away with not setting
  6427. Result to True because he haven't evaluated the jump
  6428. in this pass yet.
  6429. }
  6430. if (taicpu(p).oper[1]^.typ = top_reg) then
  6431. begin
  6432. taicpu(p).opcode := A_TEST;
  6433. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6434. Result := True;
  6435. end;
  6436. Exit;
  6437. end
  6438. else if (taicpu(p).oper[1]^.typ = top_reg)
  6439. {$ifdef x86_64}
  6440. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6441. {$endif x86_64}
  6442. then
  6443. begin
  6444. { cmp register,$8000 neg register
  6445. je target --> jo target
  6446. .... only if register is deallocated before jump.}
  6447. case Taicpu(p).opsize of
  6448. S_B: v:=$80;
  6449. S_W: v:=$8000;
  6450. S_L: v:=qword($80000000);
  6451. else
  6452. internalerror(2013112905);
  6453. end;
  6454. if (taicpu(p).oper[0]^.val=v) and
  6455. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6456. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6457. begin
  6458. TransferUsedRegs(TmpUsedRegs);
  6459. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6460. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6461. begin
  6462. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6463. Taicpu(p).opcode:=A_NEG;
  6464. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6465. Taicpu(p).clearop(1);
  6466. Taicpu(p).ops:=1;
  6467. if Taicpu(hp1).condition=C_E then
  6468. Taicpu(hp1).condition:=C_O
  6469. else
  6470. Taicpu(hp1).condition:=C_NO;
  6471. Result:=true;
  6472. exit;
  6473. end;
  6474. end;
  6475. end;
  6476. end;
  6477. if TrySwapMovCmp(p, hp1) then
  6478. begin
  6479. Result := True;
  6480. Exit;
  6481. end;
  6482. end;
  6483. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6484. var
  6485. hp1: tai;
  6486. begin
  6487. {
  6488. remove the second (v)pxor from
  6489. pxor reg,reg
  6490. ...
  6491. pxor reg,reg
  6492. }
  6493. Result:=false;
  6494. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6495. MatchOpType(taicpu(p),top_reg,top_reg) and
  6496. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6497. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6498. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6499. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6500. begin
  6501. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6502. RemoveInstruction(hp1);
  6503. Result:=true;
  6504. Exit;
  6505. end
  6506. {
  6507. replace
  6508. pxor reg1,reg1
  6509. movapd/s reg1,reg2
  6510. dealloc reg1
  6511. by
  6512. pxor reg2,reg2
  6513. }
  6514. else if GetNextInstruction(p,hp1) and
  6515. { we mix single and double opperations here because we assume that the compiler
  6516. generates vmovapd only after double operations and vmovaps only after single operations }
  6517. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6518. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6519. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6520. (taicpu(p).oper[0]^.typ=top_reg) then
  6521. begin
  6522. TransferUsedRegs(TmpUsedRegs);
  6523. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6524. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6525. begin
  6526. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6527. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6528. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6529. RemoveInstruction(hp1);
  6530. result:=true;
  6531. end;
  6532. end;
  6533. end;
  6534. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6535. var
  6536. hp1: tai;
  6537. begin
  6538. {
  6539. remove the second (v)pxor from
  6540. (v)pxor reg,reg
  6541. ...
  6542. (v)pxor reg,reg
  6543. }
  6544. Result:=false;
  6545. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6546. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6547. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6548. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6549. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6550. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6551. begin
  6552. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  6553. RemoveInstruction(hp1);
  6554. Result:=true;
  6555. Exit;
  6556. end
  6557. else
  6558. Result:=OptPass1VOP(p);
  6559. end;
  6560. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6561. var
  6562. hp1 : tai;
  6563. begin
  6564. result:=false;
  6565. { replace
  6566. IMul const,%mreg1,%mreg2
  6567. Mov %reg2,%mreg3
  6568. dealloc %mreg3
  6569. by
  6570. Imul const,%mreg1,%mreg23
  6571. }
  6572. if (taicpu(p).ops=3) and
  6573. GetNextInstruction(p,hp1) and
  6574. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6575. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6576. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6577. begin
  6578. TransferUsedRegs(TmpUsedRegs);
  6579. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6580. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6581. begin
  6582. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6583. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6584. RemoveInstruction(hp1);
  6585. result:=true;
  6586. end;
  6587. end;
  6588. end;
  6589. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6590. var
  6591. hp1 : tai;
  6592. begin
  6593. result:=false;
  6594. { replace
  6595. IMul %reg0,%reg1,%reg2
  6596. Mov %reg2,%reg3
  6597. dealloc %reg2
  6598. by
  6599. Imul %reg0,%reg1,%reg3
  6600. }
  6601. if GetNextInstruction(p,hp1) and
  6602. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6603. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6604. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6605. begin
  6606. TransferUsedRegs(TmpUsedRegs);
  6607. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6608. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6609. begin
  6610. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6611. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6612. RemoveInstruction(hp1);
  6613. result:=true;
  6614. end;
  6615. end;
  6616. end;
  6617. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6618. var
  6619. hp1: tai;
  6620. begin
  6621. Result:=false;
  6622. { get rid of
  6623. (v)cvtss2sd reg0,<reg1,>reg2
  6624. (v)cvtss2sd reg2,<reg2,>reg0
  6625. }
  6626. if GetNextInstruction(p,hp1) and
  6627. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6628. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6629. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6630. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6631. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6632. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6633. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6634. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6635. )
  6636. ) then
  6637. begin
  6638. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6639. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6640. begin
  6641. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6642. RemoveCurrentP(p);
  6643. RemoveInstruction(hp1);
  6644. end
  6645. else
  6646. begin
  6647. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6648. if taicpu(hp1).opcode=A_CVTSD2SS then
  6649. begin
  6650. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6651. taicpu(p).opcode:=A_MOVAPS;
  6652. end
  6653. else
  6654. begin
  6655. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6656. taicpu(p).opcode:=A_VMOVAPS;
  6657. end;
  6658. taicpu(p).ops:=2;
  6659. RemoveInstruction(hp1);
  6660. end;
  6661. Result:=true;
  6662. Exit;
  6663. end;
  6664. end;
  6665. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6666. var
  6667. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6668. ThisReg: TRegister;
  6669. begin
  6670. Result := False;
  6671. if not GetNextInstruction(p,hp1) then
  6672. Exit;
  6673. {
  6674. convert
  6675. j<c> .L1
  6676. mov 1,reg
  6677. jmp .L2
  6678. .L1
  6679. mov 0,reg
  6680. .L2
  6681. into
  6682. mov 0,reg
  6683. set<not(c)> reg
  6684. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6685. would destroy the flag contents
  6686. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6687. executed at the same time as a previous comparison.
  6688. set<not(c)> reg
  6689. movzx reg, reg
  6690. }
  6691. if MatchInstruction(hp1,A_MOV,[]) and
  6692. (taicpu(hp1).oper[0]^.typ = top_const) and
  6693. (
  6694. (
  6695. (taicpu(hp1).oper[1]^.typ = top_reg)
  6696. {$ifdef i386}
  6697. { Under i386, ESI, EDI, EBP and ESP
  6698. don't have an 8-bit representation }
  6699. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6700. {$endif i386}
  6701. ) or (
  6702. {$ifdef i386}
  6703. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6704. {$endif i386}
  6705. (taicpu(hp1).opsize = S_B)
  6706. )
  6707. ) and
  6708. GetNextInstruction(hp1,hp2) and
  6709. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6710. GetNextInstruction(hp2,hp3) and
  6711. SkipAligns(hp3, hp3) and
  6712. (hp3.typ=ait_label) and
  6713. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6714. GetNextInstruction(hp3,hp4) and
  6715. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6716. (taicpu(hp4).oper[0]^.typ = top_const) and
  6717. (
  6718. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6719. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6720. ) and
  6721. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6722. GetNextInstruction(hp4,hp5) and
  6723. SkipAligns(hp5, hp5) and
  6724. (hp5.typ=ait_label) and
  6725. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6726. begin
  6727. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6728. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6729. tai_label(hp3).labsym.DecRefs;
  6730. { If this isn't the only reference to the middle label, we can
  6731. still make a saving - only that the first jump and everything
  6732. that follows will remain. }
  6733. if (tai_label(hp3).labsym.getrefs = 0) then
  6734. begin
  6735. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6736. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6737. else
  6738. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6739. { remove jump, first label and second MOV (also catching any aligns) }
  6740. repeat
  6741. if not GetNextInstruction(hp2, hp3) then
  6742. InternalError(2021040810);
  6743. RemoveInstruction(hp2);
  6744. hp2 := hp3;
  6745. until hp2 = hp5;
  6746. { Don't decrement reference count before the removal loop
  6747. above, otherwise GetNextInstruction won't stop on the
  6748. the label }
  6749. tai_label(hp5).labsym.DecRefs;
  6750. end
  6751. else
  6752. begin
  6753. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6754. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6755. else
  6756. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6757. end;
  6758. taicpu(p).opcode:=A_SETcc;
  6759. taicpu(p).opsize:=S_B;
  6760. taicpu(p).is_jmp:=False;
  6761. if taicpu(hp1).opsize=S_B then
  6762. begin
  6763. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6764. if taicpu(hp1).oper[1]^.typ = top_reg then
  6765. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6766. RemoveInstruction(hp1);
  6767. end
  6768. else
  6769. begin
  6770. { Will be a register because the size can't be S_B otherwise }
  6771. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6772. taicpu(p).loadreg(0, ThisReg);
  6773. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6774. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6775. begin
  6776. case taicpu(hp1).opsize of
  6777. S_W:
  6778. taicpu(hp1).opsize := S_BW;
  6779. S_L:
  6780. taicpu(hp1).opsize := S_BL;
  6781. {$ifdef x86_64}
  6782. S_Q:
  6783. begin
  6784. taicpu(hp1).opsize := S_BL;
  6785. { Change the destination register to 32-bit }
  6786. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6787. end;
  6788. {$endif x86_64}
  6789. else
  6790. InternalError(2021040820);
  6791. end;
  6792. taicpu(hp1).opcode := A_MOVZX;
  6793. taicpu(hp1).loadreg(0, ThisReg);
  6794. end
  6795. else
  6796. begin
  6797. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6798. { hp1 is already a MOV instruction with the correct register }
  6799. taicpu(hp1).loadconst(0, 0);
  6800. { Inserting it right before p will guarantee that the flags are also tracked }
  6801. asml.Remove(hp1);
  6802. asml.InsertBefore(hp1, p);
  6803. end;
  6804. end;
  6805. Result:=true;
  6806. exit;
  6807. end
  6808. else if (hp1.typ = ait_label) then
  6809. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6810. end;
  6811. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6812. var
  6813. hp1, hp2, hp3: tai;
  6814. SourceRef, TargetRef: TReference;
  6815. CurrentReg: TRegister;
  6816. begin
  6817. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6818. if not UseAVX then
  6819. InternalError(2021100501);
  6820. Result := False;
  6821. { Look for the following to simplify:
  6822. vmovdqa/u x(mem1), %xmmreg
  6823. vmovdqa/u %xmmreg, y(mem2)
  6824. vmovdqa/u x+16(mem1), %xmmreg
  6825. vmovdqa/u %xmmreg, y+16(mem2)
  6826. Change to:
  6827. vmovdqa/u x(mem1), %ymmreg
  6828. vmovdqa/u %ymmreg, y(mem2)
  6829. vpxor %ymmreg, %ymmreg, %ymmreg
  6830. ( The VPXOR instruction is to zero the upper half, thus removing the
  6831. need to call the potentially expensive VZEROUPPER instruction. Other
  6832. peephole optimisations can remove VPXOR if it's unnecessary )
  6833. }
  6834. TransferUsedRegs(TmpUsedRegs);
  6835. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6836. { NOTE: In the optimisations below, if the references dictate that an
  6837. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6838. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6839. if (taicpu(p).opsize = S_XMM) and
  6840. MatchOpType(taicpu(p), top_ref, top_reg) and
  6841. GetNextInstruction(p, hp1) and
  6842. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6843. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6844. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6845. begin
  6846. SourceRef := taicpu(p).oper[0]^.ref^;
  6847. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6848. if GetNextInstruction(hp1, hp2) and
  6849. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6850. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6851. begin
  6852. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6853. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6854. Inc(SourceRef.offset, 16);
  6855. { Reuse the register in the first block move }
  6856. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6857. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  6858. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  6859. begin
  6860. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6861. Inc(TargetRef.offset, 16);
  6862. if GetNextInstruction(hp2, hp3) and
  6863. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6864. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6865. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6866. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6867. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6868. begin
  6869. { Update the register tracking to the new size }
  6870. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6871. { Remember that the offsets are 16 ahead }
  6872. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6873. if not (
  6874. ((SourceRef.offset mod 32) = 16) and
  6875. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6876. ) then
  6877. taicpu(p).opcode := A_VMOVDQU;
  6878. taicpu(p).opsize := S_YMM;
  6879. taicpu(p).oper[1]^.reg := CurrentReg;
  6880. if not (
  6881. ((TargetRef.offset mod 32) = 16) and
  6882. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6883. ) then
  6884. taicpu(hp1).opcode := A_VMOVDQU;
  6885. taicpu(hp1).opsize := S_YMM;
  6886. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6887. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6888. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6889. if (pi_uses_ymm in current_procinfo.flags) then
  6890. RemoveInstruction(hp2)
  6891. else
  6892. begin
  6893. taicpu(hp2).opcode := A_VPXOR;
  6894. taicpu(hp2).opsize := S_YMM;
  6895. taicpu(hp2).loadreg(0, CurrentReg);
  6896. taicpu(hp2).loadreg(1, CurrentReg);
  6897. taicpu(hp2).loadreg(2, CurrentReg);
  6898. taicpu(hp2).ops := 3;
  6899. end;
  6900. RemoveInstruction(hp3);
  6901. Result := True;
  6902. Exit;
  6903. end;
  6904. end
  6905. else
  6906. begin
  6907. { See if the next references are 16 less rather than 16 greater }
  6908. Dec(SourceRef.offset, 32); { -16 the other way }
  6909. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6910. begin
  6911. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6912. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6913. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  6914. GetNextInstruction(hp2, hp3) and
  6915. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6916. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6917. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6918. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6919. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6920. begin
  6921. { Update the register tracking to the new size }
  6922. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6923. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6924. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6925. if not(
  6926. ((SourceRef.offset mod 32) = 0) and
  6927. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6928. ) then
  6929. taicpu(hp2).opcode := A_VMOVDQU;
  6930. taicpu(hp2).opsize := S_YMM;
  6931. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6932. if not (
  6933. ((TargetRef.offset mod 32) = 0) and
  6934. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6935. ) then
  6936. taicpu(hp3).opcode := A_VMOVDQU;
  6937. taicpu(hp3).opsize := S_YMM;
  6938. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6939. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6940. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6941. if (pi_uses_ymm in current_procinfo.flags) then
  6942. RemoveInstruction(hp1)
  6943. else
  6944. begin
  6945. taicpu(hp1).opcode := A_VPXOR;
  6946. taicpu(hp1).opsize := S_YMM;
  6947. taicpu(hp1).loadreg(0, CurrentReg);
  6948. taicpu(hp1).loadreg(1, CurrentReg);
  6949. taicpu(hp1).loadreg(2, CurrentReg);
  6950. taicpu(hp1).ops := 3;
  6951. Asml.Remove(hp1);
  6952. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6953. end;
  6954. RemoveCurrentP(p, hp2);
  6955. Result := True;
  6956. Exit;
  6957. end;
  6958. end;
  6959. end;
  6960. end;
  6961. end;
  6962. end;
  6963. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6964. var
  6965. hp2, hp3, first_assignment: tai;
  6966. IncCount, OperIdx: Integer;
  6967. OrigLabel: TAsmLabel;
  6968. begin
  6969. Count := 0;
  6970. Result := False;
  6971. first_assignment := nil;
  6972. if (LoopCount >= 20) then
  6973. begin
  6974. { Guard against infinite loops }
  6975. Exit;
  6976. end;
  6977. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6978. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6979. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6980. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6981. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6982. Exit;
  6983. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6984. {
  6985. change
  6986. jmp .L1
  6987. ...
  6988. .L1:
  6989. mov ##, ## ( multiple movs possible )
  6990. jmp/ret
  6991. into
  6992. mov ##, ##
  6993. jmp/ret
  6994. }
  6995. if not Assigned(hp1) then
  6996. begin
  6997. hp1 := GetLabelWithSym(OrigLabel);
  6998. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6999. Exit;
  7000. end;
  7001. hp2 := hp1;
  7002. while Assigned(hp2) do
  7003. begin
  7004. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7005. SkipLabels(hp2,hp2);
  7006. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7007. Break;
  7008. case taicpu(hp2).opcode of
  7009. A_MOVSS:
  7010. begin
  7011. if taicpu(hp2).ops = 0 then
  7012. { Wrong MOVSS }
  7013. Break;
  7014. Inc(Count);
  7015. if Count >= 5 then
  7016. { Too many to be worthwhile }
  7017. Break;
  7018. GetNextInstruction(hp2, hp2);
  7019. Continue;
  7020. end;
  7021. A_MOV,
  7022. A_MOVD,
  7023. A_MOVQ,
  7024. A_MOVSX,
  7025. {$ifdef x86_64}
  7026. A_MOVSXD,
  7027. {$endif x86_64}
  7028. A_MOVZX,
  7029. A_MOVAPS,
  7030. A_MOVUPS,
  7031. A_MOVSD,
  7032. A_MOVAPD,
  7033. A_MOVUPD,
  7034. A_MOVDQA,
  7035. A_MOVDQU,
  7036. A_VMOVSS,
  7037. A_VMOVAPS,
  7038. A_VMOVUPS,
  7039. A_VMOVSD,
  7040. A_VMOVAPD,
  7041. A_VMOVUPD,
  7042. A_VMOVDQA,
  7043. A_VMOVDQU:
  7044. begin
  7045. Inc(Count);
  7046. if Count >= 5 then
  7047. { Too many to be worthwhile }
  7048. Break;
  7049. GetNextInstruction(hp2, hp2);
  7050. Continue;
  7051. end;
  7052. A_JMP:
  7053. begin
  7054. { Guard against infinite loops }
  7055. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7056. Exit;
  7057. { Analyse this jump first in case it also duplicates assignments }
  7058. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7059. begin
  7060. { Something did change! }
  7061. Result := True;
  7062. Inc(Count, IncCount);
  7063. if Count >= 5 then
  7064. begin
  7065. { Too many to be worthwhile }
  7066. Exit;
  7067. end;
  7068. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7069. Break;
  7070. end;
  7071. Result := True;
  7072. Break;
  7073. end;
  7074. A_RET:
  7075. begin
  7076. Result := True;
  7077. Break;
  7078. end;
  7079. else
  7080. Break;
  7081. end;
  7082. end;
  7083. if Result then
  7084. begin
  7085. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7086. if Count = 0 then
  7087. begin
  7088. Result := False;
  7089. Exit;
  7090. end;
  7091. hp3 := p;
  7092. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7093. while True do
  7094. begin
  7095. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7096. SkipLabels(hp1,hp1);
  7097. if (hp1.typ <> ait_instruction) then
  7098. InternalError(2021040720);
  7099. case taicpu(hp1).opcode of
  7100. A_JMP:
  7101. begin
  7102. { Change the original jump to the new destination }
  7103. OrigLabel.decrefs;
  7104. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7105. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7106. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7107. if not Assigned(first_assignment) then
  7108. InternalError(2021040810)
  7109. else
  7110. p := first_assignment;
  7111. Exit;
  7112. end;
  7113. A_RET:
  7114. begin
  7115. { Now change the jump into a RET instruction }
  7116. ConvertJumpToRET(p, hp1);
  7117. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7118. if not Assigned(first_assignment) then
  7119. InternalError(2021040811)
  7120. else
  7121. p := first_assignment;
  7122. Exit;
  7123. end;
  7124. else
  7125. begin
  7126. { Duplicate the MOV instruction }
  7127. hp3:=tai(hp1.getcopy);
  7128. if first_assignment = nil then
  7129. first_assignment := hp3;
  7130. asml.InsertBefore(hp3, p);
  7131. { Make sure the compiler knows about any final registers written here }
  7132. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7133. with taicpu(hp3).oper[OperIdx]^ do
  7134. begin
  7135. case typ of
  7136. top_ref:
  7137. begin
  7138. if (ref^.base <> NR_NO) and
  7139. (getsupreg(ref^.base) <> RS_ESP) and
  7140. (getsupreg(ref^.base) <> RS_EBP)
  7141. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7142. then
  7143. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7144. if (ref^.index <> NR_NO) and
  7145. (getsupreg(ref^.index) <> RS_ESP) and
  7146. (getsupreg(ref^.index) <> RS_EBP)
  7147. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7148. (ref^.index <> ref^.base) then
  7149. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7150. end;
  7151. top_reg:
  7152. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7153. else
  7154. ;
  7155. end;
  7156. end;
  7157. end;
  7158. end;
  7159. if not GetNextInstruction(hp1, hp1) then
  7160. { Should have dropped out earlier }
  7161. InternalError(2021040710);
  7162. end;
  7163. end;
  7164. end;
  7165. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7166. var
  7167. hp2: tai;
  7168. X: Integer;
  7169. const
  7170. WriteOp: array[0..3] of set of TInsChange = (
  7171. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7172. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7173. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7174. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7175. RegWriteFlags: array[0..7] of set of TInsChange = (
  7176. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7177. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7178. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7179. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7180. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7181. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7182. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7183. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7184. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7185. begin
  7186. { If we have something like:
  7187. cmp ###,%reg1
  7188. mov 0,%reg2
  7189. And no modified registers are shared, move the instruction to before
  7190. the comparison as this means it can be optimised without worrying
  7191. about the FLAGS register. (CMP/MOV is generated by
  7192. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7193. As long as the second instruction doesn't use the flags or one of the
  7194. registers used by CMP or TEST (also check any references that use the
  7195. registers), then it can be moved prior to the comparison.
  7196. }
  7197. Result := False;
  7198. if (hp1.typ <> ait_instruction) or
  7199. taicpu(hp1).is_jmp or
  7200. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7201. Exit;
  7202. { NOP is a pipeline fence, likely marking the beginning of the function
  7203. epilogue, so drop out. Similarly, drop out if POP or RET are
  7204. encountered }
  7205. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7206. Exit;
  7207. if (taicpu(hp1).opcode = A_MOVSS) and
  7208. (taicpu(hp1).ops = 0) then
  7209. { Wrong MOVSS }
  7210. Exit;
  7211. { Check for writes to specific registers first }
  7212. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7213. for X := 0 to 7 do
  7214. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7215. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7216. Exit;
  7217. for X := 0 to taicpu(hp1).ops - 1 do
  7218. begin
  7219. { Check to see if this operand writes to something }
  7220. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7221. { And matches something in the CMP/TEST instruction }
  7222. (
  7223. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7224. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7225. (
  7226. { If it's a register, make sure the register written to doesn't
  7227. appear in the cmp instruction as part of a reference }
  7228. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7229. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7230. )
  7231. ) then
  7232. Exit;
  7233. end;
  7234. { The instruction can be safely moved }
  7235. asml.Remove(hp1);
  7236. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7237. can be optimised into "xor %reg,%reg" later }
  7238. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7239. asml.InsertBefore(hp1, hp2)
  7240. else
  7241. { Note, if p.Previous is nil (even if it should logically never be the
  7242. case), FindRegAllocBackward immediately exits with False and so we
  7243. safely land here (we can't just pass p because FindRegAllocBackward
  7244. immediately exits on an instruction). [Kit] }
  7245. asml.InsertBefore(hp1, p);
  7246. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7247. for X := 0 to taicpu(hp1).ops - 1 do
  7248. case taicpu(hp1).oper[X]^.typ of
  7249. top_reg:
  7250. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7251. top_ref:
  7252. begin
  7253. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7254. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7255. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7256. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7257. end;
  7258. else
  7259. ;
  7260. end;
  7261. if taicpu(hp1).opcode = A_LEA then
  7262. { The flags will be overwritten by the CMP/TEST instruction }
  7263. ConvertLEA(taicpu(hp1));
  7264. Result := True;
  7265. end;
  7266. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7267. function IsXCHGAcceptable: Boolean; inline;
  7268. begin
  7269. { Always accept if optimising for size }
  7270. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7271. (
  7272. {$ifdef x86_64}
  7273. { XCHG takes 3 cycles on AMD Athlon64 }
  7274. (current_settings.optimizecputype >= cpu_core_i)
  7275. {$else x86_64}
  7276. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7277. than 3, so it becomes a saving compared to three MOVs with two of
  7278. them able to execute simultaneously. [Kit] }
  7279. (current_settings.optimizecputype >= cpu_PentiumM)
  7280. {$endif x86_64}
  7281. );
  7282. end;
  7283. var
  7284. NewRef: TReference;
  7285. hp1, hp2, hp3, hp4: Tai;
  7286. {$ifndef x86_64}
  7287. OperIdx: Integer;
  7288. {$endif x86_64}
  7289. NewInstr : Taicpu;
  7290. NewAligh : Tai_align;
  7291. DestLabel: TAsmLabel;
  7292. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7293. var
  7294. NextInstr: tai;
  7295. begin
  7296. Result := False;
  7297. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7298. if not GetNextInstruction(InputInstr, NextInstr) or
  7299. (
  7300. { The FLAGS register isn't always tracked properly, so do not
  7301. perform this optimisation if a conditional statement follows }
  7302. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7303. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7304. ) then
  7305. begin
  7306. reference_reset(NewRef, 1, []);
  7307. NewRef.base := taicpu(p).oper[0]^.reg;
  7308. NewRef.scalefactor := 1;
  7309. if taicpu(InputInstr).opcode = A_ADD then
  7310. begin
  7311. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7312. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7313. end
  7314. else
  7315. begin
  7316. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7317. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7318. end;
  7319. taicpu(p).opcode := A_LEA;
  7320. taicpu(p).loadref(0, NewRef);
  7321. RemoveInstruction(InputInstr);
  7322. Result := True;
  7323. end;
  7324. end;
  7325. begin
  7326. Result:=false;
  7327. { This optimisation adds an instruction, so only do it for speed }
  7328. if not (cs_opt_size in current_settings.optimizerswitches) and
  7329. MatchOpType(taicpu(p), top_const, top_reg) and
  7330. (taicpu(p).oper[0]^.val = 0) then
  7331. begin
  7332. { To avoid compiler warning }
  7333. DestLabel := nil;
  7334. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7335. InternalError(2021040750);
  7336. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7337. Exit;
  7338. case hp1.typ of
  7339. ait_label:
  7340. begin
  7341. { Change:
  7342. mov $0,%reg mov $0,%reg
  7343. @Lbl1: @Lbl1:
  7344. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7345. je @Lbl2 jne @Lbl2
  7346. To: To:
  7347. mov $0,%reg mov $0,%reg
  7348. jmp @Lbl2 jmp @Lbl3
  7349. (align) (align)
  7350. @Lbl1: @Lbl1:
  7351. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7352. je @Lbl2 je @Lbl2
  7353. @Lbl3: <-- Only if label exists
  7354. (Not if it's optimised for size)
  7355. }
  7356. if not GetNextInstruction(hp1, hp2) then
  7357. Exit;
  7358. if not (cs_opt_size in current_settings.optimizerswitches) and
  7359. (hp2.typ = ait_instruction) and
  7360. (
  7361. { Register sizes must exactly match }
  7362. (
  7363. (taicpu(hp2).opcode = A_CMP) and
  7364. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7365. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7366. ) or (
  7367. (taicpu(hp2).opcode = A_TEST) and
  7368. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7369. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7370. )
  7371. ) and GetNextInstruction(hp2, hp3) and
  7372. (hp3.typ = ait_instruction) and
  7373. (taicpu(hp3).opcode = A_JCC) and
  7374. (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
  7375. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7376. begin
  7377. { Check condition of jump }
  7378. { Always true? }
  7379. if condition_in(C_E, taicpu(hp3).condition) then
  7380. begin
  7381. { Copy label symbol and obtain matching label entry for the
  7382. conditional jump, as this will be our destination}
  7383. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7384. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7385. Result := True;
  7386. end
  7387. { Always false? }
  7388. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7389. begin
  7390. { This is only worth it if there's a jump to take }
  7391. case hp2.typ of
  7392. ait_instruction:
  7393. begin
  7394. if taicpu(hp2).opcode = A_JMP then
  7395. begin
  7396. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7397. { An unconditional jump follows the conditional jump which will always be false,
  7398. so use this jump's destination for the new jump }
  7399. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7400. Result := True;
  7401. end
  7402. else if taicpu(hp2).opcode = A_JCC then
  7403. begin
  7404. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7405. if condition_in(C_E, taicpu(hp2).condition) then
  7406. begin
  7407. { A second conditional jump follows the conditional jump which will always be false,
  7408. while the second jump is always True, so use this jump's destination for the new jump }
  7409. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7410. Result := True;
  7411. end;
  7412. { Don't risk it if the jump isn't always true (Result remains False) }
  7413. end;
  7414. end;
  7415. else
  7416. { If anything else don't optimise };
  7417. end;
  7418. end;
  7419. if Result then
  7420. begin
  7421. { Just so we have something to insert as a paremeter}
  7422. reference_reset(NewRef, 1, []);
  7423. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7424. { Now actually load the correct parameter (this also
  7425. increases the reference count) }
  7426. NewInstr.loadsymbol(0, DestLabel, 0);
  7427. { Get instruction before original label (may not be p under -O3) }
  7428. if not GetLastInstruction(hp1, hp2) then
  7429. { Shouldn't fail here }
  7430. InternalError(2021040701);
  7431. AsmL.InsertAfter(NewInstr, hp2);
  7432. { Add new alignment field }
  7433. (* AsmL.InsertAfter(
  7434. cai_align.create_max(
  7435. current_settings.alignment.jumpalign,
  7436. current_settings.alignment.jumpalignskipmax
  7437. ),
  7438. NewInstr
  7439. ); *)
  7440. end;
  7441. Exit;
  7442. end;
  7443. end;
  7444. else
  7445. ;
  7446. end;
  7447. end;
  7448. if not GetNextInstruction(p, hp1) then
  7449. Exit;
  7450. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7451. and DoMovCmpMemOpt(p, hp1, True) then
  7452. begin
  7453. Result := True;
  7454. Exit;
  7455. end
  7456. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7457. begin
  7458. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7459. further, but we can't just put this jump optimisation in pass 1
  7460. because it tends to perform worse when conditional jumps are
  7461. nearby (e.g. when converting CMOV instructions). [Kit] }
  7462. if OptPass2JMP(hp1) then
  7463. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7464. Result := OptPass1MOV(p)
  7465. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7466. returned True and the instruction is still a MOV, thus checking
  7467. the optimisations below }
  7468. { If OptPass2JMP returned False, no optimisations were done to
  7469. the jump and there are no further optimisations that can be done
  7470. to the MOV instruction on this pass }
  7471. end
  7472. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7473. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7474. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7475. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7476. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7477. begin
  7478. { Change:
  7479. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7480. addl/q $x,%reg2 subl/q $x,%reg2
  7481. To:
  7482. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7483. }
  7484. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7485. { be lazy, checking separately for sub would be slightly better }
  7486. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7487. begin
  7488. TransferUsedRegs(TmpUsedRegs);
  7489. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7490. if TryMovArith2Lea(hp1) then
  7491. begin
  7492. Result := True;
  7493. Exit;
  7494. end
  7495. end
  7496. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7497. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7498. { Same as above, but also adds or subtracts to %reg2 in between.
  7499. It's still valid as long as the flags aren't in use }
  7500. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7501. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7502. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7503. { be lazy, checking separately for sub would be slightly better }
  7504. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7505. begin
  7506. TransferUsedRegs(TmpUsedRegs);
  7507. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7508. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7509. if TryMovArith2Lea(hp2) then
  7510. begin
  7511. Result := True;
  7512. Exit;
  7513. end;
  7514. end;
  7515. end
  7516. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7517. {$ifdef x86_64}
  7518. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7519. {$else x86_64}
  7520. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7521. {$endif x86_64}
  7522. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7523. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7524. { mov reg1, reg2 mov reg1, reg2
  7525. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7526. begin
  7527. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7528. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7529. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7530. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7531. TransferUsedRegs(TmpUsedRegs);
  7532. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7533. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7534. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7535. then
  7536. begin
  7537. RemoveCurrentP(p, hp1);
  7538. Result:=true;
  7539. end;
  7540. exit;
  7541. end
  7542. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7543. IsXCHGAcceptable and
  7544. { XCHG doesn't support 8-byte registers }
  7545. (taicpu(p).opsize <> S_B) and
  7546. MatchInstruction(hp1, A_MOV, []) and
  7547. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7548. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7549. GetNextInstruction(hp1, hp2) and
  7550. MatchInstruction(hp2, A_MOV, []) and
  7551. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7552. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7553. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7554. begin
  7555. { mov %reg1,%reg2
  7556. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7557. mov %reg2,%reg3
  7558. (%reg2 not used afterwards)
  7559. Note that xchg takes 3 cycles to execute, and generally mov's take
  7560. only one cycle apiece, but the first two mov's can be executed in
  7561. parallel, only taking 2 cycles overall. Older processors should
  7562. therefore only optimise for size. [Kit]
  7563. }
  7564. TransferUsedRegs(TmpUsedRegs);
  7565. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7566. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7567. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7568. begin
  7569. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7570. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7571. taicpu(hp1).opcode := A_XCHG;
  7572. RemoveCurrentP(p, hp1);
  7573. RemoveInstruction(hp2);
  7574. Result := True;
  7575. Exit;
  7576. end;
  7577. end
  7578. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7579. MatchInstruction(hp1, A_SAR, []) then
  7580. begin
  7581. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7582. begin
  7583. { the use of %edx also covers the opsize being S_L }
  7584. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7585. begin
  7586. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7587. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7588. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7589. begin
  7590. { Change:
  7591. movl %eax,%edx
  7592. sarl $31,%edx
  7593. To:
  7594. cltd
  7595. }
  7596. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7597. RemoveInstruction(hp1);
  7598. taicpu(p).opcode := A_CDQ;
  7599. taicpu(p).opsize := S_NO;
  7600. taicpu(p).clearop(1);
  7601. taicpu(p).clearop(0);
  7602. taicpu(p).ops:=0;
  7603. Result := True;
  7604. end
  7605. else if (cs_opt_size in current_settings.optimizerswitches) and
  7606. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7607. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7608. begin
  7609. { Change:
  7610. movl %edx,%eax
  7611. sarl $31,%edx
  7612. To:
  7613. movl %edx,%eax
  7614. cltd
  7615. Note that this creates a dependency between the two instructions,
  7616. so only perform if optimising for size.
  7617. }
  7618. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7619. taicpu(hp1).opcode := A_CDQ;
  7620. taicpu(hp1).opsize := S_NO;
  7621. taicpu(hp1).clearop(1);
  7622. taicpu(hp1).clearop(0);
  7623. taicpu(hp1).ops:=0;
  7624. end;
  7625. {$ifndef x86_64}
  7626. end
  7627. { Don't bother if CMOV is supported, because a more optimal
  7628. sequence would have been generated for the Abs() intrinsic }
  7629. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7630. { the use of %eax also covers the opsize being S_L }
  7631. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7632. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7633. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7634. GetNextInstruction(hp1, hp2) and
  7635. MatchInstruction(hp2, A_XOR, [S_L]) and
  7636. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7637. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7638. GetNextInstruction(hp2, hp3) and
  7639. MatchInstruction(hp3, A_SUB, [S_L]) and
  7640. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7641. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7642. begin
  7643. { Change:
  7644. movl %eax,%edx
  7645. sarl $31,%eax
  7646. xorl %eax,%edx
  7647. subl %eax,%edx
  7648. (Instruction that uses %edx)
  7649. (%eax deallocated)
  7650. (%edx deallocated)
  7651. To:
  7652. cltd
  7653. xorl %edx,%eax <-- Note the registers have swapped
  7654. subl %edx,%eax
  7655. (Instruction that uses %eax) <-- %eax rather than %edx
  7656. }
  7657. TransferUsedRegs(TmpUsedRegs);
  7658. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7659. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7660. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7661. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7662. begin
  7663. if GetNextInstruction(hp3, hp4) and
  7664. not RegModifiedByInstruction(NR_EDX, hp4) and
  7665. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7666. begin
  7667. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7668. taicpu(p).opcode := A_CDQ;
  7669. taicpu(p).clearop(1);
  7670. taicpu(p).clearop(0);
  7671. taicpu(p).ops:=0;
  7672. RemoveInstruction(hp1);
  7673. taicpu(hp2).loadreg(0, NR_EDX);
  7674. taicpu(hp2).loadreg(1, NR_EAX);
  7675. taicpu(hp3).loadreg(0, NR_EDX);
  7676. taicpu(hp3).loadreg(1, NR_EAX);
  7677. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7678. { Convert references in the following instruction (hp4) from %edx to %eax }
  7679. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7680. with taicpu(hp4).oper[OperIdx]^ do
  7681. case typ of
  7682. top_reg:
  7683. if getsupreg(reg) = RS_EDX then
  7684. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7685. top_ref:
  7686. begin
  7687. if getsupreg(reg) = RS_EDX then
  7688. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7689. if getsupreg(reg) = RS_EDX then
  7690. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7691. end;
  7692. else
  7693. ;
  7694. end;
  7695. end;
  7696. end;
  7697. {$else x86_64}
  7698. end;
  7699. end
  7700. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7701. { the use of %rdx also covers the opsize being S_Q }
  7702. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7703. begin
  7704. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7705. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7706. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7707. begin
  7708. { Change:
  7709. movq %rax,%rdx
  7710. sarq $63,%rdx
  7711. To:
  7712. cqto
  7713. }
  7714. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7715. RemoveInstruction(hp1);
  7716. taicpu(p).opcode := A_CQO;
  7717. taicpu(p).opsize := S_NO;
  7718. taicpu(p).clearop(1);
  7719. taicpu(p).clearop(0);
  7720. taicpu(p).ops:=0;
  7721. Result := True;
  7722. end
  7723. else if (cs_opt_size in current_settings.optimizerswitches) and
  7724. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7725. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7726. begin
  7727. { Change:
  7728. movq %rdx,%rax
  7729. sarq $63,%rdx
  7730. To:
  7731. movq %rdx,%rax
  7732. cqto
  7733. Note that this creates a dependency between the two instructions,
  7734. so only perform if optimising for size.
  7735. }
  7736. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7737. taicpu(hp1).opcode := A_CQO;
  7738. taicpu(hp1).opsize := S_NO;
  7739. taicpu(hp1).clearop(1);
  7740. taicpu(hp1).clearop(0);
  7741. taicpu(hp1).ops:=0;
  7742. {$endif x86_64}
  7743. end;
  7744. end;
  7745. end
  7746. else if MatchInstruction(hp1, A_MOV, []) and
  7747. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7748. { Though "GetNextInstruction" could be factored out, along with
  7749. the instructions that depend on hp2, it is an expensive call that
  7750. should be delayed for as long as possible, hence we do cheaper
  7751. checks first that are likely to be False. [Kit] }
  7752. begin
  7753. if (
  7754. (
  7755. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7756. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7757. (
  7758. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7759. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7760. )
  7761. ) or
  7762. (
  7763. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7764. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7765. (
  7766. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7767. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7768. )
  7769. )
  7770. ) and
  7771. GetNextInstruction(hp1, hp2) and
  7772. MatchInstruction(hp2, A_SAR, []) and
  7773. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7774. begin
  7775. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7776. begin
  7777. { Change:
  7778. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7779. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7780. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7781. To:
  7782. movl r/m,%eax <- Note the change in register
  7783. cltd
  7784. }
  7785. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7786. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7787. taicpu(p).loadreg(1, NR_EAX);
  7788. taicpu(hp1).opcode := A_CDQ;
  7789. taicpu(hp1).clearop(1);
  7790. taicpu(hp1).clearop(0);
  7791. taicpu(hp1).ops:=0;
  7792. RemoveInstruction(hp2);
  7793. (*
  7794. {$ifdef x86_64}
  7795. end
  7796. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7797. { This code sequence does not get generated - however it might become useful
  7798. if and when 128-bit signed integer types make an appearance, so the code
  7799. is kept here for when it is eventually needed. [Kit] }
  7800. (
  7801. (
  7802. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7803. (
  7804. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7805. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7806. )
  7807. ) or
  7808. (
  7809. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7810. (
  7811. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7812. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7813. )
  7814. )
  7815. ) and
  7816. GetNextInstruction(hp1, hp2) and
  7817. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7818. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7819. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7820. begin
  7821. { Change:
  7822. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7823. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7824. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7825. To:
  7826. movq r/m,%rax <- Note the change in register
  7827. cqto
  7828. }
  7829. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7830. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7831. taicpu(p).loadreg(1, NR_RAX);
  7832. taicpu(hp1).opcode := A_CQO;
  7833. taicpu(hp1).clearop(1);
  7834. taicpu(hp1).clearop(0);
  7835. taicpu(hp1).ops:=0;
  7836. RemoveInstruction(hp2);
  7837. {$endif x86_64}
  7838. *)
  7839. end;
  7840. end;
  7841. {$ifdef x86_64}
  7842. end
  7843. else if (taicpu(p).opsize = S_L) and
  7844. (taicpu(p).oper[1]^.typ = top_reg) and
  7845. (
  7846. MatchInstruction(hp1, A_MOV,[]) and
  7847. (taicpu(hp1).opsize = S_L) and
  7848. (taicpu(hp1).oper[1]^.typ = top_reg)
  7849. ) and (
  7850. GetNextInstruction(hp1, hp2) and
  7851. (tai(hp2).typ=ait_instruction) and
  7852. (taicpu(hp2).opsize = S_Q) and
  7853. (
  7854. (
  7855. MatchInstruction(hp2, A_ADD,[]) and
  7856. (taicpu(hp2).opsize = S_Q) and
  7857. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7858. (
  7859. (
  7860. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7861. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7862. ) or (
  7863. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7864. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7865. )
  7866. )
  7867. ) or (
  7868. MatchInstruction(hp2, A_LEA,[]) and
  7869. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7870. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7871. (
  7872. (
  7873. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7874. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7875. ) or (
  7876. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7877. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7878. )
  7879. ) and (
  7880. (
  7881. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7882. ) or (
  7883. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7884. )
  7885. )
  7886. )
  7887. )
  7888. ) and (
  7889. GetNextInstruction(hp2, hp3) and
  7890. MatchInstruction(hp3, A_SHR,[]) and
  7891. (taicpu(hp3).opsize = S_Q) and
  7892. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7893. (taicpu(hp3).oper[0]^.val = 1) and
  7894. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7895. ) then
  7896. begin
  7897. { Change movl x, reg1d movl x, reg1d
  7898. movl y, reg2d movl y, reg2d
  7899. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7900. shrq $1, reg1q shrq $1, reg1q
  7901. ( reg1d and reg2d can be switched around in the first two instructions )
  7902. To movl x, reg1d
  7903. addl y, reg1d
  7904. rcrl $1, reg1d
  7905. This corresponds to the common expression (x + y) shr 1, where
  7906. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7907. smaller code, but won't account for x + y causing an overflow). [Kit]
  7908. }
  7909. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7910. { Change first MOV command to have the same register as the final output }
  7911. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7912. else
  7913. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7914. { Change second MOV command to an ADD command. This is easier than
  7915. converting the existing command because it means we don't have to
  7916. touch 'y', which might be a complicated reference, and also the
  7917. fact that the third command might either be ADD or LEA. [Kit] }
  7918. taicpu(hp1).opcode := A_ADD;
  7919. { Delete old ADD/LEA instruction }
  7920. RemoveInstruction(hp2);
  7921. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7922. taicpu(hp3).opcode := A_RCR;
  7923. taicpu(hp3).changeopsize(S_L);
  7924. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7925. {$endif x86_64}
  7926. end;
  7927. end;
  7928. {$push}
  7929. {$q-}{$r-}
  7930. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7931. var
  7932. ThisReg: TRegister;
  7933. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7934. TargetSubReg: TSubRegister;
  7935. hp1, hp2: tai;
  7936. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  7937. { Store list of found instructions so we don't have to call
  7938. GetNextInstructionUsingReg multiple times }
  7939. InstrList: array of taicpu;
  7940. InstrMax, Index: Integer;
  7941. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7942. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7943. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7944. WorkingValue: TCgInt;
  7945. PreMessage: string;
  7946. { Data flow analysis }
  7947. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7948. BitwiseOnly, OrXorUsed,
  7949. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7950. function CheckOverflowConditions: Boolean;
  7951. begin
  7952. Result := True;
  7953. if (TestValSignedMax > SignedUpperLimit) then
  7954. UpperSignedOverflow := True;
  7955. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7956. LowerSignedOverflow := True;
  7957. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7958. LowerUnsignedOverflow := True;
  7959. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7960. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7961. begin
  7962. { Absolute overflow }
  7963. Result := False;
  7964. Exit;
  7965. end;
  7966. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7967. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7968. ShiftDownOverflow := True;
  7969. if (TestValMin < 0) or (TestValMax < 0) then
  7970. begin
  7971. LowerUnsignedOverflow := True;
  7972. UpperUnsignedOverflow := True;
  7973. end;
  7974. end;
  7975. function AdjustInitialLoadAndSize: Boolean;
  7976. begin
  7977. Result := False;
  7978. if not p_removed then
  7979. begin
  7980. if TargetSize = MinSize then
  7981. begin
  7982. { Convert the input MOVZX to a MOV }
  7983. if (taicpu(p).oper[0]^.typ = top_reg) and
  7984. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7985. begin
  7986. { Or remove it completely! }
  7987. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7988. RemoveCurrentP(p);
  7989. p_removed := True;
  7990. end
  7991. else
  7992. begin
  7993. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7994. taicpu(p).opcode := A_MOV;
  7995. taicpu(p).oper[1]^.reg := ThisReg;
  7996. taicpu(p).opsize := TargetSize;
  7997. end;
  7998. Result := True;
  7999. end
  8000. else if TargetSize <> MaxSize then
  8001. begin
  8002. case MaxSize of
  8003. S_L:
  8004. if TargetSize = S_W then
  8005. begin
  8006. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8007. taicpu(p).opsize := S_BW;
  8008. taicpu(p).oper[1]^.reg := ThisReg;
  8009. Result := True;
  8010. end
  8011. else
  8012. InternalError(2020112341);
  8013. S_W:
  8014. if TargetSize = S_L then
  8015. begin
  8016. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8017. taicpu(p).opsize := S_BL;
  8018. taicpu(p).oper[1]^.reg := ThisReg;
  8019. Result := True;
  8020. end
  8021. else
  8022. InternalError(2020112342);
  8023. else
  8024. ;
  8025. end;
  8026. end
  8027. else if not hp1_removed and not RegInUse then
  8028. begin
  8029. { If we have something like:
  8030. movzbl (oper),%regd
  8031. add x, %regd
  8032. movzbl %regb, %regd
  8033. We can reduce the register size to the input of the final
  8034. movzbl instruction. Overflows won't have any effect.
  8035. }
  8036. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8037. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8038. begin
  8039. TargetSize := S_B;
  8040. setsubreg(ThisReg, R_SUBL);
  8041. Result := True;
  8042. end
  8043. else if (taicpu(p).opsize = S_WL) and
  8044. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8045. begin
  8046. TargetSize := S_W;
  8047. setsubreg(ThisReg, R_SUBW);
  8048. Result := True;
  8049. end;
  8050. if Result then
  8051. begin
  8052. { Convert the input MOVZX to a MOV }
  8053. if (taicpu(p).oper[0]^.typ = top_reg) and
  8054. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8055. begin
  8056. { Or remove it completely! }
  8057. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8058. RemoveCurrentP(p);
  8059. p_removed := True;
  8060. end
  8061. else
  8062. begin
  8063. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8064. taicpu(p).opcode := A_MOV;
  8065. taicpu(p).oper[1]^.reg := ThisReg;
  8066. taicpu(p).opsize := TargetSize;
  8067. end;
  8068. end;
  8069. end;
  8070. end;
  8071. end;
  8072. procedure AdjustFinalLoad;
  8073. begin
  8074. if not LowerUnsignedOverflow then
  8075. begin
  8076. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8077. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8078. begin
  8079. { Convert the output MOVZX to a MOV }
  8080. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8081. begin
  8082. { Or remove it completely! }
  8083. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8084. { Be careful; if p = hp1 and p was also removed, p
  8085. will become a dangling pointer }
  8086. if p = hp1 then
  8087. begin
  8088. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8089. p_removed := True;
  8090. end
  8091. else
  8092. RemoveInstruction(hp1);
  8093. hp1_removed := True;
  8094. end
  8095. else
  8096. begin
  8097. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8098. taicpu(hp1).opcode := A_MOV;
  8099. taicpu(hp1).oper[0]^.reg := ThisReg;
  8100. taicpu(hp1).opsize := TargetSize;
  8101. end;
  8102. end
  8103. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8104. begin
  8105. { Need to change the size of the output }
  8106. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8107. taicpu(hp1).oper[0]^.reg := ThisReg;
  8108. taicpu(hp1).opsize := S_BL;
  8109. end;
  8110. end;
  8111. end;
  8112. function CompressInstructions: Boolean;
  8113. var
  8114. LocalIndex: Integer;
  8115. begin
  8116. Result := False;
  8117. { The objective here is to try to find a combination that
  8118. removes one of the MOV/Z instructions. }
  8119. if (
  8120. (taicpu(p).oper[0]^.typ <> top_reg) or
  8121. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8122. ) and
  8123. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8124. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8125. begin
  8126. { Make a preference to remove the second MOVZX instruction }
  8127. case taicpu(hp1).opsize of
  8128. S_BL, S_WL:
  8129. begin
  8130. TargetSize := S_L;
  8131. TargetSubReg := R_SUBD;
  8132. end;
  8133. S_BW:
  8134. begin
  8135. TargetSize := S_W;
  8136. TargetSubReg := R_SUBW;
  8137. end;
  8138. else
  8139. InternalError(2020112302);
  8140. end;
  8141. end
  8142. else
  8143. begin
  8144. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8145. begin
  8146. { Exceeded lower bound but not upper bound }
  8147. TargetSize := MaxSize;
  8148. end
  8149. else if not LowerUnsignedOverflow then
  8150. begin
  8151. { Size didn't exceed lower bound }
  8152. TargetSize := MinSize;
  8153. end
  8154. else
  8155. Exit;
  8156. end;
  8157. case TargetSize of
  8158. S_B:
  8159. TargetSubReg := R_SUBL;
  8160. S_W:
  8161. TargetSubReg := R_SUBW;
  8162. S_L:
  8163. TargetSubReg := R_SUBD;
  8164. else
  8165. InternalError(2020112350);
  8166. end;
  8167. { Update the register to its new size }
  8168. setsubreg(ThisReg, TargetSubReg);
  8169. RegInUse := False;
  8170. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8171. begin
  8172. { Check to see if the active register is used afterwards;
  8173. if not, we can change it and make a saving. }
  8174. TransferUsedRegs(TmpUsedRegs);
  8175. { The target register may be marked as in use to cross
  8176. a jump to a distant label, so exclude it }
  8177. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8178. hp2 := p;
  8179. repeat
  8180. { Explicitly check for the excluded register (don't include the first
  8181. instruction as it may be reading from here }
  8182. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8183. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8184. begin
  8185. RegInUse := True;
  8186. Break;
  8187. end;
  8188. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8189. if not GetNextInstruction(hp2, hp2) then
  8190. InternalError(2020112340);
  8191. until (hp2 = hp1);
  8192. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8193. { We might still be able to get away with this }
  8194. RegInUse := not
  8195. (
  8196. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8197. (hp2.typ = ait_instruction) and
  8198. (
  8199. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8200. instruction that doesn't actually contain ThisReg }
  8201. (cs_opt_level3 in current_settings.optimizerswitches) or
  8202. RegInInstruction(ThisReg, hp2)
  8203. ) and
  8204. RegLoadedWithNewValue(ThisReg, hp2)
  8205. );
  8206. if not RegInUse then
  8207. begin
  8208. { Force the register size to the same as this instruction so it can be removed}
  8209. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8210. begin
  8211. TargetSize := S_L;
  8212. TargetSubReg := R_SUBD;
  8213. end
  8214. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8215. begin
  8216. TargetSize := S_W;
  8217. TargetSubReg := R_SUBW;
  8218. end;
  8219. ThisReg := taicpu(hp1).oper[1]^.reg;
  8220. setsubreg(ThisReg, TargetSubReg);
  8221. RegChanged := True;
  8222. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8223. TransferUsedRegs(TmpUsedRegs);
  8224. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8225. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8226. if p = hp1 then
  8227. begin
  8228. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8229. p_removed := True;
  8230. end
  8231. else
  8232. RemoveInstruction(hp1);
  8233. hp1_removed := True;
  8234. { Instruction will become "mov %reg,%reg" }
  8235. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8236. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8237. begin
  8238. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8239. RemoveCurrentP(p);
  8240. p_removed := True;
  8241. end
  8242. else
  8243. taicpu(p).oper[1]^.reg := ThisReg;
  8244. Result := True;
  8245. end
  8246. else
  8247. begin
  8248. if TargetSize <> MaxSize then
  8249. begin
  8250. { Since the register is in use, we have to force it to
  8251. MaxSize otherwise part of it may become undefined later on }
  8252. TargetSize := MaxSize;
  8253. case TargetSize of
  8254. S_B:
  8255. TargetSubReg := R_SUBL;
  8256. S_W:
  8257. TargetSubReg := R_SUBW;
  8258. S_L:
  8259. TargetSubReg := R_SUBD;
  8260. else
  8261. InternalError(2020112351);
  8262. end;
  8263. setsubreg(ThisReg, TargetSubReg);
  8264. end;
  8265. AdjustFinalLoad;
  8266. end;
  8267. end
  8268. else
  8269. AdjustFinalLoad;
  8270. Result := AdjustInitialLoadAndSize or Result;
  8271. { Now go through every instruction we found and change the
  8272. size. If TargetSize = MaxSize, then almost no changes are
  8273. needed and Result can remain False if it hasn't been set
  8274. yet.
  8275. If RegChanged is True, then the register requires changing
  8276. and so the point about TargetSize = MaxSize doesn't apply. }
  8277. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8278. begin
  8279. for LocalIndex := 0 to InstrMax do
  8280. begin
  8281. { If p_removed is true, then the original MOV/Z was removed
  8282. and removing the AND instruction may not be safe if it
  8283. appears first }
  8284. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8285. InternalError(2020112310);
  8286. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8287. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8288. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8289. InstrList[LocalIndex].opsize := TargetSize;
  8290. end;
  8291. Result := True;
  8292. end;
  8293. end;
  8294. begin
  8295. Result := False;
  8296. p_removed := False;
  8297. hp1_removed := False;
  8298. ThisReg := taicpu(p).oper[1]^.reg;
  8299. { Check for:
  8300. movs/z ###,%ecx (or %cx or %rcx)
  8301. ...
  8302. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8303. (dealloc %ecx)
  8304. Change to:
  8305. mov ###,%cl (if ### = %cl, then remove completely)
  8306. ...
  8307. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8308. }
  8309. if (getsupreg(ThisReg) = RS_ECX) and
  8310. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8311. (hp1.typ = ait_instruction) and
  8312. (
  8313. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8314. instruction that doesn't actually contain ECX }
  8315. (cs_opt_level3 in current_settings.optimizerswitches) or
  8316. RegInInstruction(NR_ECX, hp1) or
  8317. (
  8318. { It's common for the shift/rotate's read/write register to be
  8319. initialised in between, so under -O2 and under, search ahead
  8320. one more instruction
  8321. }
  8322. GetNextInstruction(hp1, hp1) and
  8323. (hp1.typ = ait_instruction) and
  8324. RegInInstruction(NR_ECX, hp1)
  8325. )
  8326. ) and
  8327. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8328. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8329. begin
  8330. TransferUsedRegs(TmpUsedRegs);
  8331. hp2 := p;
  8332. repeat
  8333. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8334. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8335. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8336. begin
  8337. case taicpu(p).opsize of
  8338. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8339. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8340. begin
  8341. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8342. RemoveCurrentP(p);
  8343. end
  8344. else
  8345. begin
  8346. taicpu(p).opcode := A_MOV;
  8347. taicpu(p).opsize := S_B;
  8348. taicpu(p).oper[1]^.reg := NR_CL;
  8349. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8350. end;
  8351. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8352. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8353. begin
  8354. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8355. RemoveCurrentP(p);
  8356. end
  8357. else
  8358. begin
  8359. taicpu(p).opcode := A_MOV;
  8360. taicpu(p).opsize := S_W;
  8361. taicpu(p).oper[1]^.reg := NR_CX;
  8362. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8363. end;
  8364. {$ifdef x86_64}
  8365. S_LQ:
  8366. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8367. begin
  8368. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8369. RemoveCurrentP(p);
  8370. end
  8371. else
  8372. begin
  8373. taicpu(p).opcode := A_MOV;
  8374. taicpu(p).opsize := S_L;
  8375. taicpu(p).oper[1]^.reg := NR_ECX;
  8376. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8377. end;
  8378. {$endif x86_64}
  8379. else
  8380. InternalError(2021120401);
  8381. end;
  8382. Result := True;
  8383. Exit;
  8384. end;
  8385. end;
  8386. { This is anything but quick! }
  8387. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8388. Exit;
  8389. SetLength(InstrList, 0);
  8390. InstrMax := -1;
  8391. case taicpu(p).opsize of
  8392. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8393. begin
  8394. {$if defined(i386) or defined(i8086)}
  8395. { If the target size is 8-bit, make sure we can actually encode it }
  8396. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8397. Exit;
  8398. {$endif i386 or i8086}
  8399. LowerLimit := $FF;
  8400. SignedLowerLimit := $7F;
  8401. SignedLowerLimitBottom := -128;
  8402. MinSize := S_B;
  8403. if taicpu(p).opsize = S_BW then
  8404. begin
  8405. MaxSize := S_W;
  8406. UpperLimit := $FFFF;
  8407. SignedUpperLimit := $7FFF;
  8408. SignedUpperLimitBottom := -32768;
  8409. end
  8410. else
  8411. begin
  8412. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8413. MaxSize := S_L;
  8414. UpperLimit := $FFFFFFFF;
  8415. SignedUpperLimit := $7FFFFFFF;
  8416. SignedUpperLimitBottom := -2147483648;
  8417. end;
  8418. end;
  8419. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8420. begin
  8421. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8422. LowerLimit := $FFFF;
  8423. SignedLowerLimit := $7FFF;
  8424. SignedLowerLimitBottom := -32768;
  8425. UpperLimit := $FFFFFFFF;
  8426. SignedUpperLimit := $7FFFFFFF;
  8427. SignedUpperLimitBottom := -2147483648;
  8428. MinSize := S_W;
  8429. MaxSize := S_L;
  8430. end;
  8431. {$ifdef x86_64}
  8432. S_LQ:
  8433. begin
  8434. { Both the lower and upper limits are set to 32-bit. If a limit
  8435. is breached, then optimisation is impossible }
  8436. LowerLimit := $FFFFFFFF;
  8437. SignedLowerLimit := $7FFFFFFF;
  8438. SignedLowerLimitBottom := -2147483648;
  8439. UpperLimit := $FFFFFFFF;
  8440. SignedUpperLimit := $7FFFFFFF;
  8441. SignedUpperLimitBottom := -2147483648;
  8442. MinSize := S_L;
  8443. MaxSize := S_L;
  8444. end;
  8445. {$endif x86_64}
  8446. else
  8447. InternalError(2020112301);
  8448. end;
  8449. TestValMin := 0;
  8450. TestValMax := LowerLimit;
  8451. TestValSignedMax := SignedLowerLimit;
  8452. TryShiftDownLimit := LowerLimit;
  8453. TryShiftDown := S_NO;
  8454. ShiftDownOverflow := False;
  8455. RegChanged := False;
  8456. BitwiseOnly := True;
  8457. OrXorUsed := False;
  8458. UpperSignedOverflow := False;
  8459. LowerSignedOverflow := False;
  8460. UpperUnsignedOverflow := False;
  8461. LowerUnsignedOverflow := False;
  8462. hp1 := p;
  8463. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8464. (hp1.typ = ait_instruction) and
  8465. (
  8466. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8467. instruction that doesn't actually contain ThisReg }
  8468. (cs_opt_level3 in current_settings.optimizerswitches) or
  8469. { This allows this Movx optimisation to work through the SETcc instructions
  8470. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8471. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8472. skip over these SETcc instructions). }
  8473. (taicpu(hp1).opcode = A_SETcc) or
  8474. RegInInstruction(ThisReg, hp1)
  8475. ) do
  8476. begin
  8477. case taicpu(hp1).opcode of
  8478. A_INC,A_DEC:
  8479. begin
  8480. { Has to be an exact match on the register }
  8481. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8482. Break;
  8483. if taicpu(hp1).opcode = A_INC then
  8484. begin
  8485. Inc(TestValMin);
  8486. Inc(TestValMax);
  8487. Inc(TestValSignedMax);
  8488. end
  8489. else
  8490. begin
  8491. Dec(TestValMin);
  8492. Dec(TestValMax);
  8493. Dec(TestValSignedMax);
  8494. end;
  8495. end;
  8496. A_TEST, A_CMP:
  8497. begin
  8498. if (
  8499. { Too high a risk of non-linear behaviour that breaks DFA
  8500. here, unless it's cmp $0,%reg, which is equivalent to
  8501. test %reg,%reg }
  8502. OrXorUsed and
  8503. (taicpu(hp1).opcode = A_CMP) and
  8504. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8505. ) or
  8506. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8507. { Has to be an exact match on the register }
  8508. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8509. (
  8510. { Permit "test %reg,%reg" }
  8511. (taicpu(hp1).opcode = A_TEST) and
  8512. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8513. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8514. ) or
  8515. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8516. { Make sure the comparison value is not smaller than the
  8517. smallest allowed signed value for the minimum size (e.g.
  8518. -128 for 8-bit) }
  8519. not (
  8520. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8521. { Is it in the negative range? }
  8522. (
  8523. (taicpu(hp1).oper[0]^.val < 0) and
  8524. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8525. )
  8526. ) then
  8527. Break;
  8528. { Check to see if the active register is used afterwards }
  8529. TransferUsedRegs(TmpUsedRegs);
  8530. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8531. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8532. begin
  8533. { Make sure the comparison or any previous instructions
  8534. hasn't pushed the test values outside of the range of
  8535. MinSize }
  8536. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8537. begin
  8538. { Exceeded lower bound but not upper bound }
  8539. Exit;
  8540. end
  8541. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8542. begin
  8543. { Size didn't exceed lower bound }
  8544. TargetSize := MinSize;
  8545. end
  8546. else
  8547. Break;
  8548. case TargetSize of
  8549. S_B:
  8550. TargetSubReg := R_SUBL;
  8551. S_W:
  8552. TargetSubReg := R_SUBW;
  8553. S_L:
  8554. TargetSubReg := R_SUBD;
  8555. else
  8556. InternalError(2021051002);
  8557. end;
  8558. if TargetSize <> MaxSize then
  8559. begin
  8560. { Update the register to its new size }
  8561. setsubreg(ThisReg, TargetSubReg);
  8562. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8563. taicpu(hp1).oper[1]^.reg := ThisReg;
  8564. taicpu(hp1).opsize := TargetSize;
  8565. { Convert the input MOVZX to a MOV if necessary }
  8566. AdjustInitialLoadAndSize;
  8567. if (InstrMax >= 0) then
  8568. begin
  8569. for Index := 0 to InstrMax do
  8570. begin
  8571. { If p_removed is true, then the original MOV/Z was removed
  8572. and removing the AND instruction may not be safe if it
  8573. appears first }
  8574. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8575. InternalError(2020112311);
  8576. if InstrList[Index].oper[0]^.typ = top_reg then
  8577. InstrList[Index].oper[0]^.reg := ThisReg;
  8578. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8579. InstrList[Index].opsize := MinSize;
  8580. end;
  8581. end;
  8582. Result := True;
  8583. end;
  8584. Exit;
  8585. end;
  8586. end;
  8587. A_SETcc:
  8588. begin
  8589. { This allows this Movx optimisation to work through the SETcc instructions
  8590. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8591. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8592. skip over these SETcc instructions). }
  8593. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8594. { Of course, break out if the current register is used }
  8595. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8596. Break
  8597. else
  8598. { We must use Continue so the instruction doesn't get added
  8599. to InstrList }
  8600. Continue;
  8601. end;
  8602. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8603. begin
  8604. if
  8605. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8606. { Has to be an exact match on the register }
  8607. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8608. (
  8609. (
  8610. (taicpu(hp1).oper[0]^.typ = top_const) and
  8611. (
  8612. (
  8613. (taicpu(hp1).opcode = A_SHL) and
  8614. (
  8615. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8616. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8617. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8618. )
  8619. ) or (
  8620. (taicpu(hp1).opcode <> A_SHL) and
  8621. (
  8622. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8623. { Is it in the negative range? }
  8624. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8625. )
  8626. )
  8627. )
  8628. ) or (
  8629. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8630. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8631. )
  8632. ) then
  8633. Break;
  8634. { Only process OR and XOR if there are only bitwise operations,
  8635. since otherwise they can too easily fool the data flow
  8636. analysis (they can cause non-linear behaviour) }
  8637. case taicpu(hp1).opcode of
  8638. A_ADD:
  8639. begin
  8640. if OrXorUsed then
  8641. { Too high a risk of non-linear behaviour that breaks DFA here }
  8642. Break
  8643. else
  8644. BitwiseOnly := False;
  8645. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8646. begin
  8647. TestValMin := TestValMin * 2;
  8648. TestValMax := TestValMax * 2;
  8649. TestValSignedMax := TestValSignedMax * 2;
  8650. end
  8651. else
  8652. begin
  8653. WorkingValue := taicpu(hp1).oper[0]^.val;
  8654. TestValMin := TestValMin + WorkingValue;
  8655. TestValMax := TestValMax + WorkingValue;
  8656. TestValSignedMax := TestValSignedMax + WorkingValue;
  8657. end;
  8658. end;
  8659. A_SUB:
  8660. begin
  8661. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8662. begin
  8663. TestValMin := 0;
  8664. TestValMax := 0;
  8665. TestValSignedMax := 0;
  8666. end
  8667. else
  8668. begin
  8669. if OrXorUsed then
  8670. { Too high a risk of non-linear behaviour that breaks DFA here }
  8671. Break
  8672. else
  8673. BitwiseOnly := False;
  8674. WorkingValue := taicpu(hp1).oper[0]^.val;
  8675. TestValMin := TestValMin - WorkingValue;
  8676. TestValMax := TestValMax - WorkingValue;
  8677. TestValSignedMax := TestValSignedMax - WorkingValue;
  8678. end;
  8679. end;
  8680. A_AND:
  8681. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8682. begin
  8683. { we might be able to go smaller if AND appears first }
  8684. if InstrMax = -1 then
  8685. case MinSize of
  8686. S_B:
  8687. ;
  8688. S_W:
  8689. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8690. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8691. begin
  8692. TryShiftDown := S_B;
  8693. TryShiftDownLimit := $FF;
  8694. end;
  8695. S_L:
  8696. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8697. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8698. begin
  8699. TryShiftDown := S_B;
  8700. TryShiftDownLimit := $FF;
  8701. end
  8702. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8703. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8704. begin
  8705. TryShiftDown := S_W;
  8706. TryShiftDownLimit := $FFFF;
  8707. end;
  8708. else
  8709. InternalError(2020112320);
  8710. end;
  8711. WorkingValue := taicpu(hp1).oper[0]^.val;
  8712. TestValMin := TestValMin and WorkingValue;
  8713. TestValMax := TestValMax and WorkingValue;
  8714. TestValSignedMax := TestValSignedMax and WorkingValue;
  8715. end;
  8716. A_OR:
  8717. begin
  8718. if not BitwiseOnly then
  8719. Break;
  8720. OrXorUsed := True;
  8721. WorkingValue := taicpu(hp1).oper[0]^.val;
  8722. TestValMin := TestValMin or WorkingValue;
  8723. TestValMax := TestValMax or WorkingValue;
  8724. TestValSignedMax := TestValSignedMax or WorkingValue;
  8725. end;
  8726. A_XOR:
  8727. begin
  8728. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8729. begin
  8730. TestValMin := 0;
  8731. TestValMax := 0;
  8732. TestValSignedMax := 0;
  8733. end
  8734. else
  8735. begin
  8736. if not BitwiseOnly then
  8737. Break;
  8738. OrXorUsed := True;
  8739. WorkingValue := taicpu(hp1).oper[0]^.val;
  8740. TestValMin := TestValMin xor WorkingValue;
  8741. TestValMax := TestValMax xor WorkingValue;
  8742. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8743. end;
  8744. end;
  8745. A_SHL:
  8746. begin
  8747. BitwiseOnly := False;
  8748. WorkingValue := taicpu(hp1).oper[0]^.val;
  8749. TestValMin := TestValMin shl WorkingValue;
  8750. TestValMax := TestValMax shl WorkingValue;
  8751. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8752. end;
  8753. A_SHR,
  8754. { The first instruction was MOVZX, so the value won't be negative }
  8755. A_SAR:
  8756. begin
  8757. if InstrMax <> -1 then
  8758. BitwiseOnly := False
  8759. else
  8760. { we might be able to go smaller if SHR appears first }
  8761. case MinSize of
  8762. S_B:
  8763. ;
  8764. S_W:
  8765. if (taicpu(hp1).oper[0]^.val >= 8) then
  8766. begin
  8767. TryShiftDown := S_B;
  8768. TryShiftDownLimit := $FF;
  8769. TryShiftDownSignedLimit := $7F;
  8770. TryShiftDownSignedLimitLower := -128;
  8771. end;
  8772. S_L:
  8773. if (taicpu(hp1).oper[0]^.val >= 24) then
  8774. begin
  8775. TryShiftDown := S_B;
  8776. TryShiftDownLimit := $FF;
  8777. TryShiftDownSignedLimit := $7F;
  8778. TryShiftDownSignedLimitLower := -128;
  8779. end
  8780. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8781. begin
  8782. TryShiftDown := S_W;
  8783. TryShiftDownLimit := $FFFF;
  8784. TryShiftDownSignedLimit := $7FFF;
  8785. TryShiftDownSignedLimitLower := -32768;
  8786. end;
  8787. else
  8788. InternalError(2020112321);
  8789. end;
  8790. WorkingValue := taicpu(hp1).oper[0]^.val;
  8791. if taicpu(hp1).opcode = A_SAR then
  8792. begin
  8793. TestValMin := SarInt64(TestValMin, WorkingValue);
  8794. TestValMax := SarInt64(TestValMax, WorkingValue);
  8795. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8796. end
  8797. else
  8798. begin
  8799. TestValMin := TestValMin shr WorkingValue;
  8800. TestValMax := TestValMax shr WorkingValue;
  8801. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8802. end;
  8803. end;
  8804. else
  8805. InternalError(2020112303);
  8806. end;
  8807. end;
  8808. (*
  8809. A_IMUL:
  8810. case taicpu(hp1).ops of
  8811. 2:
  8812. begin
  8813. if not MatchOpType(hp1, top_reg, top_reg) or
  8814. { Has to be an exact match on the register }
  8815. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8816. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8817. Break;
  8818. TestValMin := TestValMin * TestValMin;
  8819. TestValMax := TestValMax * TestValMax;
  8820. TestValSignedMax := TestValSignedMax * TestValMax;
  8821. end;
  8822. 3:
  8823. begin
  8824. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8825. { Has to be an exact match on the register }
  8826. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8827. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8828. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8829. { Is it in the negative range? }
  8830. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8831. Break;
  8832. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8833. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8834. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8835. end;
  8836. else
  8837. Break;
  8838. end;
  8839. A_IDIV:
  8840. case taicpu(hp1).ops of
  8841. 3:
  8842. begin
  8843. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8844. { Has to be an exact match on the register }
  8845. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8846. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8847. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8848. { Is it in the negative range? }
  8849. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8850. Break;
  8851. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8852. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8853. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8854. end;
  8855. else
  8856. Break;
  8857. end;
  8858. *)
  8859. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8860. begin
  8861. { If there are no instructions in between, then we might be able to make a saving }
  8862. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8863. Break;
  8864. { We have something like:
  8865. movzbw %dl,%dx
  8866. ...
  8867. movswl %dx,%edx
  8868. Change the latter to a zero-extension then enter the
  8869. A_MOVZX case branch.
  8870. }
  8871. {$ifdef x86_64}
  8872. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8873. begin
  8874. { this becomes a zero extension from 32-bit to 64-bit, but
  8875. the upper 32 bits are already zero, so just delete the
  8876. instruction }
  8877. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8878. RemoveInstruction(hp1);
  8879. Result := True;
  8880. Exit;
  8881. end
  8882. else
  8883. {$endif x86_64}
  8884. begin
  8885. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8886. taicpu(hp1).opcode := A_MOVZX;
  8887. {$ifdef x86_64}
  8888. case taicpu(hp1).opsize of
  8889. S_BQ:
  8890. begin
  8891. taicpu(hp1).opsize := S_BL;
  8892. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8893. end;
  8894. S_WQ:
  8895. begin
  8896. taicpu(hp1).opsize := S_WL;
  8897. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8898. end;
  8899. S_LQ:
  8900. begin
  8901. taicpu(hp1).opcode := A_MOV;
  8902. taicpu(hp1).opsize := S_L;
  8903. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8904. { In this instance, we need to break out because the
  8905. instruction is no longer MOVZX or MOVSXD }
  8906. Result := True;
  8907. Exit;
  8908. end;
  8909. else
  8910. ;
  8911. end;
  8912. {$endif x86_64}
  8913. Result := CompressInstructions;
  8914. Exit;
  8915. end;
  8916. end;
  8917. A_MOVZX:
  8918. begin
  8919. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8920. Break;
  8921. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8922. begin
  8923. if (InstrMax = -1) and
  8924. { Will return false if the second parameter isn't ThisReg
  8925. (can happen on -O2 and under) }
  8926. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8927. begin
  8928. { The two MOVZX instructions are adjacent, so remove the first one }
  8929. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8930. RemoveCurrentP(p);
  8931. Result := True;
  8932. Exit;
  8933. end;
  8934. Break;
  8935. end;
  8936. Result := CompressInstructions;
  8937. Exit;
  8938. end;
  8939. else
  8940. { This includes ADC, SBB and IDIV }
  8941. Break;
  8942. end;
  8943. if not CheckOverflowConditions then
  8944. Break;
  8945. { Contains highest index (so instruction count - 1) }
  8946. Inc(InstrMax);
  8947. if InstrMax > High(InstrList) then
  8948. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8949. InstrList[InstrMax] := taicpu(hp1);
  8950. end;
  8951. end;
  8952. {$pop}
  8953. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8954. var
  8955. hp1 : tai;
  8956. begin
  8957. Result:=false;
  8958. if (taicpu(p).ops >= 2) and
  8959. ((taicpu(p).oper[0]^.typ = top_const) or
  8960. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8961. (taicpu(p).oper[1]^.typ = top_reg) and
  8962. ((taicpu(p).ops = 2) or
  8963. ((taicpu(p).oper[2]^.typ = top_reg) and
  8964. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8965. GetLastInstruction(p,hp1) and
  8966. MatchInstruction(hp1,A_MOV,[]) and
  8967. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8968. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8969. begin
  8970. TransferUsedRegs(TmpUsedRegs);
  8971. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8972. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8973. { change
  8974. mov reg1,reg2
  8975. imul y,reg2 to imul y,reg1,reg2 }
  8976. begin
  8977. taicpu(p).ops := 3;
  8978. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8979. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8980. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8981. RemoveInstruction(hp1);
  8982. result:=true;
  8983. end;
  8984. end;
  8985. end;
  8986. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8987. var
  8988. ThisLabel: TAsmLabel;
  8989. begin
  8990. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8991. ThisLabel.decrefs;
  8992. taicpu(p).opcode := A_RET;
  8993. taicpu(p).is_jmp := false;
  8994. taicpu(p).ops := taicpu(ret_p).ops;
  8995. case taicpu(ret_p).ops of
  8996. 0:
  8997. taicpu(p).clearop(0);
  8998. 1:
  8999. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9000. else
  9001. internalerror(2016041301);
  9002. end;
  9003. { If the original label is now dead, it might turn out that the label
  9004. immediately follows p. As a result, everything beyond it, which will
  9005. be just some final register configuration and a RET instruction, is
  9006. now dead code. [Kit] }
  9007. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9008. running RemoveDeadCodeAfterJump for each RET instruction, because
  9009. this optimisation rarely happens and most RETs appear at the end of
  9010. routines where there is nothing that can be stripped. [Kit] }
  9011. if not ThisLabel.is_used then
  9012. RemoveDeadCodeAfterJump(p);
  9013. end;
  9014. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9015. var
  9016. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9017. Unconditional, PotentialModified: Boolean;
  9018. OperPtr: POper;
  9019. NewRef: TReference;
  9020. InstrList: array of taicpu;
  9021. InstrMax, Index: Integer;
  9022. const
  9023. {$ifdef DEBUG_AOPTCPU}
  9024. SNoFlags: shortstring = ' so the flags aren''t modified';
  9025. {$else DEBUG_AOPTCPU}
  9026. SNoFlags = '';
  9027. {$endif DEBUG_AOPTCPU}
  9028. begin
  9029. Result:=false;
  9030. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9031. begin
  9032. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9033. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9034. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9035. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9036. GetNextInstruction(hp1, hp2) and
  9037. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9038. { Change from: To:
  9039. set(C) %reg j(~C) label
  9040. test %reg,%reg/cmp $0,%reg
  9041. je label
  9042. set(C) %reg j(C) label
  9043. test %reg,%reg/cmp $0,%reg
  9044. jne label
  9045. (Also do something similar with sete/setne instead of je/jne)
  9046. }
  9047. begin
  9048. { Before we do anything else, we need to check the instructions
  9049. in between SETcc and TEST to make sure they don't modify the
  9050. FLAGS register - if -O2 or under, there won't be any
  9051. instructions between SET and TEST }
  9052. TransferUsedRegs(TmpUsedRegs);
  9053. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9054. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9055. begin
  9056. next := p;
  9057. SetLength(InstrList, 0);
  9058. InstrMax := -1;
  9059. PotentialModified := False;
  9060. { Make a note of every instruction that modifies the FLAGS
  9061. register }
  9062. while GetNextInstruction(next, next) and (next <> hp1) do
  9063. begin
  9064. if next.typ <> ait_instruction then
  9065. { GetNextInstructionUsingReg should have returned False }
  9066. InternalError(2021051701);
  9067. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9068. begin
  9069. case taicpu(next).opcode of
  9070. A_SETcc,
  9071. A_CMOVcc,
  9072. A_Jcc:
  9073. begin
  9074. if PotentialModified then
  9075. { Not safe because the flags were modified earlier }
  9076. Exit
  9077. else
  9078. { Condition is the same as the initial SETcc, so this is safe
  9079. (don't add to instruction list though) }
  9080. Continue;
  9081. end;
  9082. A_ADD:
  9083. begin
  9084. if (taicpu(next).opsize = S_B) or
  9085. { LEA doesn't support 8-bit operands }
  9086. (taicpu(next).oper[1]^.typ <> top_reg) or
  9087. { Must write to a register }
  9088. (taicpu(next).oper[0]^.typ = top_ref) then
  9089. { Require a constant or a register }
  9090. Exit;
  9091. PotentialModified := True;
  9092. end;
  9093. A_SUB:
  9094. begin
  9095. if (taicpu(next).opsize = S_B) or
  9096. { LEA doesn't support 8-bit operands }
  9097. (taicpu(next).oper[1]^.typ <> top_reg) or
  9098. { Must write to a register }
  9099. (taicpu(next).oper[0]^.typ <> top_const) or
  9100. (taicpu(next).oper[0]^.val = $80000000) then
  9101. { Can't subtract a register with LEA - also
  9102. check that the value isn't -2^31, as this
  9103. can't be negated }
  9104. Exit;
  9105. PotentialModified := True;
  9106. end;
  9107. A_SAL,
  9108. A_SHL:
  9109. begin
  9110. if (taicpu(next).opsize = S_B) or
  9111. { LEA doesn't support 8-bit operands }
  9112. (taicpu(next).oper[1]^.typ <> top_reg) or
  9113. { Must write to a register }
  9114. (taicpu(next).oper[0]^.typ <> top_const) or
  9115. (taicpu(next).oper[0]^.val < 0) or
  9116. (taicpu(next).oper[0]^.val > 3) then
  9117. Exit;
  9118. PotentialModified := True;
  9119. end;
  9120. A_IMUL:
  9121. begin
  9122. if (taicpu(next).ops <> 3) or
  9123. (taicpu(next).oper[1]^.typ <> top_reg) or
  9124. { Must write to a register }
  9125. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9126. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9127. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9128. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9129. Exit
  9130. else
  9131. PotentialModified := True;
  9132. end;
  9133. else
  9134. { Don't know how to change this, so abort }
  9135. Exit;
  9136. end;
  9137. { Contains highest index (so instruction count - 1) }
  9138. Inc(InstrMax);
  9139. if InstrMax > High(InstrList) then
  9140. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9141. InstrList[InstrMax] := taicpu(next);
  9142. end;
  9143. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9144. end;
  9145. if not Assigned(next) or (next <> hp1) then
  9146. { It should be equal to hp1 }
  9147. InternalError(2021051702);
  9148. { Cycle through each instruction and check to see if we can
  9149. change them to versions that don't modify the flags }
  9150. if (InstrMax >= 0) then
  9151. begin
  9152. for Index := 0 to InstrMax do
  9153. case InstrList[Index].opcode of
  9154. A_ADD:
  9155. begin
  9156. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9157. InstrList[Index].opcode := A_LEA;
  9158. reference_reset(NewRef, 1, []);
  9159. NewRef.base := InstrList[Index].oper[1]^.reg;
  9160. if InstrList[Index].oper[0]^.typ = top_reg then
  9161. begin
  9162. NewRef.index := InstrList[Index].oper[0]^.reg;
  9163. NewRef.scalefactor := 1;
  9164. end
  9165. else
  9166. NewRef.offset := InstrList[Index].oper[0]^.val;
  9167. InstrList[Index].loadref(0, NewRef);
  9168. end;
  9169. A_SUB:
  9170. begin
  9171. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9172. InstrList[Index].opcode := A_LEA;
  9173. reference_reset(NewRef, 1, []);
  9174. NewRef.base := InstrList[Index].oper[1]^.reg;
  9175. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9176. InstrList[Index].loadref(0, NewRef);
  9177. end;
  9178. A_SHL,
  9179. A_SAL:
  9180. begin
  9181. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9182. InstrList[Index].opcode := A_LEA;
  9183. reference_reset(NewRef, 1, []);
  9184. NewRef.index := InstrList[Index].oper[1]^.reg;
  9185. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9186. InstrList[Index].loadref(0, NewRef);
  9187. end;
  9188. A_IMUL:
  9189. begin
  9190. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9191. InstrList[Index].opcode := A_LEA;
  9192. reference_reset(NewRef, 1, []);
  9193. NewRef.index := InstrList[Index].oper[1]^.reg;
  9194. case InstrList[Index].oper[0]^.val of
  9195. 2, 4, 8:
  9196. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9197. else {3, 5 and 9}
  9198. begin
  9199. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9200. NewRef.base := InstrList[Index].oper[1]^.reg;
  9201. end;
  9202. end;
  9203. InstrList[Index].loadref(0, NewRef);
  9204. end;
  9205. else
  9206. InternalError(2021051710);
  9207. end;
  9208. end;
  9209. { Mark the FLAGS register as used across this whole block }
  9210. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9211. end;
  9212. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9213. JumpC := taicpu(hp2).condition;
  9214. Unconditional := False;
  9215. if conditions_equal(JumpC, C_E) then
  9216. SetC := inverse_cond(taicpu(p).condition)
  9217. else if conditions_equal(JumpC, C_NE) then
  9218. SetC := taicpu(p).condition
  9219. else
  9220. { We've got something weird here (and inefficent) }
  9221. begin
  9222. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9223. SetC := C_NONE;
  9224. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9225. if condition_in(C_AE, JumpC) then
  9226. Unconditional := True
  9227. else
  9228. { Not sure what to do with this jump - drop out }
  9229. Exit;
  9230. end;
  9231. RemoveInstruction(hp1);
  9232. if Unconditional then
  9233. MakeUnconditional(taicpu(hp2))
  9234. else
  9235. begin
  9236. if SetC = C_NONE then
  9237. InternalError(2018061402);
  9238. taicpu(hp2).SetCondition(SetC);
  9239. end;
  9240. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9241. TmpUsedRegs }
  9242. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9243. begin
  9244. RemoveCurrentp(p, hp2);
  9245. if taicpu(hp2).opcode = A_SETcc then
  9246. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9247. else
  9248. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9249. end
  9250. else
  9251. if taicpu(hp2).opcode = A_SETcc then
  9252. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9253. else
  9254. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9255. Result := True;
  9256. end
  9257. else if
  9258. { Make sure the instructions are adjacent }
  9259. (
  9260. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9261. GetNextInstruction(p, hp1)
  9262. ) and
  9263. MatchInstruction(hp1, A_MOV, [S_B]) and
  9264. { Writing to memory is allowed }
  9265. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9266. begin
  9267. {
  9268. Watch out for sequences such as:
  9269. set(c)b %regb
  9270. movb %regb,(ref)
  9271. movb $0,1(ref)
  9272. movb $0,2(ref)
  9273. movb $0,3(ref)
  9274. Much more efficient to turn it into:
  9275. movl $0,%regl
  9276. set(c)b %regb
  9277. movl %regl,(ref)
  9278. Or:
  9279. set(c)b %regb
  9280. movzbl %regb,%regl
  9281. movl %regl,(ref)
  9282. }
  9283. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9284. GetNextInstruction(hp1, hp2) and
  9285. MatchInstruction(hp2, A_MOV, [S_B]) and
  9286. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9287. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9288. begin
  9289. { Don't do anything else except set Result to True }
  9290. end
  9291. else
  9292. begin
  9293. if taicpu(p).oper[0]^.typ = top_reg then
  9294. begin
  9295. TransferUsedRegs(TmpUsedRegs);
  9296. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9297. end;
  9298. { If it's not a register, it's a memory address }
  9299. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9300. begin
  9301. { Even if the register is still in use, we can minimise the
  9302. pipeline stall by changing the MOV into another SETcc. }
  9303. taicpu(hp1).opcode := A_SETcc;
  9304. taicpu(hp1).condition := taicpu(p).condition;
  9305. if taicpu(hp1).oper[1]^.typ = top_ref then
  9306. begin
  9307. { Swapping the operand pointers like this is probably a
  9308. bit naughty, but it is far faster than using loadoper
  9309. to transfer the reference from oper[1] to oper[0] if
  9310. you take into account the extra procedure calls and
  9311. the memory allocation and deallocation required }
  9312. OperPtr := taicpu(hp1).oper[1];
  9313. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9314. taicpu(hp1).oper[0] := OperPtr;
  9315. end
  9316. else
  9317. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9318. taicpu(hp1).clearop(1);
  9319. taicpu(hp1).ops := 1;
  9320. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9321. end
  9322. else
  9323. begin
  9324. if taicpu(hp1).oper[1]^.typ = top_reg then
  9325. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9326. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9327. RemoveInstruction(hp1);
  9328. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9329. end
  9330. end;
  9331. Result := True;
  9332. end;
  9333. end;
  9334. end;
  9335. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9336. var
  9337. hp1: tai;
  9338. Count: Integer;
  9339. OrigLabel: TAsmLabel;
  9340. begin
  9341. result := False;
  9342. { Sometimes, the optimisations below can permit this }
  9343. RemoveDeadCodeAfterJump(p);
  9344. 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
  9345. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9346. begin
  9347. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9348. { Also a side-effect of optimisations }
  9349. if CollapseZeroDistJump(p, OrigLabel) then
  9350. begin
  9351. Result := True;
  9352. Exit;
  9353. end;
  9354. hp1 := GetLabelWithSym(OrigLabel);
  9355. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9356. begin
  9357. if taicpu(hp1).opcode = A_RET then
  9358. begin
  9359. {
  9360. change
  9361. jmp .L1
  9362. ...
  9363. .L1:
  9364. ret
  9365. into
  9366. ret
  9367. }
  9368. begin
  9369. ConvertJumpToRET(p, hp1);
  9370. result:=true;
  9371. end;
  9372. end
  9373. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  9374. not (cs_opt_size in current_settings.optimizerswitches) and
  9375. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9376. begin
  9377. Result := True;
  9378. Exit;
  9379. end;
  9380. end;
  9381. end;
  9382. end;
  9383. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9384. begin
  9385. CanBeCMOV:=assigned(p) and
  9386. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9387. { we can't use cmov ref,reg because
  9388. ref could be nil and cmov still throws an exception
  9389. if ref=nil but the mov isn't done (FK)
  9390. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9391. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9392. }
  9393. (taicpu(p).oper[1]^.typ = top_reg) and
  9394. (
  9395. (taicpu(p).oper[0]^.typ = top_reg) or
  9396. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9397. it is not expected that this can cause a seg. violation }
  9398. (
  9399. (taicpu(p).oper[0]^.typ = top_ref) and
  9400. IsRefSafe(taicpu(p).oper[0]^.ref)
  9401. )
  9402. );
  9403. end;
  9404. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9405. var
  9406. hp1,hp2: tai;
  9407. {$ifndef i8086}
  9408. hp3,hp4,hpmov2, hp5: tai;
  9409. l : Longint;
  9410. condition : TAsmCond;
  9411. {$endif i8086}
  9412. carryadd_opcode : TAsmOp;
  9413. symbol: TAsmSymbol;
  9414. increg, tmpreg: TRegister;
  9415. begin
  9416. result:=false;
  9417. if GetNextInstruction(p,hp1) then
  9418. begin
  9419. if (hp1.typ=ait_label) then
  9420. begin
  9421. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9422. Exit;
  9423. end
  9424. else if (hp1.typ<>ait_instruction) then
  9425. Exit;
  9426. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9427. if (
  9428. (
  9429. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9430. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9431. (Taicpu(hp1).oper[0]^.val=1)
  9432. ) or
  9433. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9434. ) and
  9435. GetNextInstruction(hp1,hp2) and
  9436. SkipAligns(hp2, hp2) and
  9437. (hp2.typ = ait_label) and
  9438. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9439. { jb @@1 cmc
  9440. inc/dec operand --> adc/sbb operand,0
  9441. @@1:
  9442. ... and ...
  9443. jnb @@1
  9444. inc/dec operand --> adc/sbb operand,0
  9445. @@1: }
  9446. begin
  9447. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9448. begin
  9449. case taicpu(hp1).opcode of
  9450. A_INC,
  9451. A_ADD:
  9452. carryadd_opcode:=A_ADC;
  9453. A_DEC,
  9454. A_SUB:
  9455. carryadd_opcode:=A_SBB;
  9456. else
  9457. InternalError(2021011001);
  9458. end;
  9459. Taicpu(p).clearop(0);
  9460. Taicpu(p).ops:=0;
  9461. Taicpu(p).is_jmp:=false;
  9462. Taicpu(p).opcode:=A_CMC;
  9463. Taicpu(p).condition:=C_NONE;
  9464. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9465. Taicpu(hp1).ops:=2;
  9466. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9467. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9468. else
  9469. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9470. Taicpu(hp1).loadconst(0,0);
  9471. Taicpu(hp1).opcode:=carryadd_opcode;
  9472. result:=true;
  9473. exit;
  9474. end
  9475. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9476. begin
  9477. case taicpu(hp1).opcode of
  9478. A_INC,
  9479. A_ADD:
  9480. carryadd_opcode:=A_ADC;
  9481. A_DEC,
  9482. A_SUB:
  9483. carryadd_opcode:=A_SBB;
  9484. else
  9485. InternalError(2021011002);
  9486. end;
  9487. Taicpu(hp1).ops:=2;
  9488. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9489. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9490. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9491. else
  9492. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9493. Taicpu(hp1).loadconst(0,0);
  9494. Taicpu(hp1).opcode:=carryadd_opcode;
  9495. RemoveCurrentP(p, hp1);
  9496. result:=true;
  9497. exit;
  9498. end
  9499. {
  9500. jcc @@1 setcc tmpreg
  9501. inc/dec/add/sub operand -> (movzx tmpreg)
  9502. @@1: add/sub tmpreg,operand
  9503. While this increases code size slightly, it makes the code much faster if the
  9504. jump is unpredictable
  9505. }
  9506. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9507. begin
  9508. { search for an available register which is volatile }
  9509. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9510. if increg <> NR_NO then
  9511. begin
  9512. { We don't need to check if tmpreg is in hp1 or not, because
  9513. it will be marked as in use at p (if not, this is
  9514. indictive of a compiler bug). }
  9515. TAsmLabel(symbol).decrefs;
  9516. Taicpu(p).clearop(0);
  9517. Taicpu(p).ops:=1;
  9518. Taicpu(p).is_jmp:=false;
  9519. Taicpu(p).opcode:=A_SETcc;
  9520. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9521. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9522. Taicpu(p).loadreg(0,increg);
  9523. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9524. begin
  9525. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9526. R_SUBW:
  9527. begin
  9528. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9529. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9530. end;
  9531. R_SUBD:
  9532. begin
  9533. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9534. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9535. end;
  9536. {$ifdef x86_64}
  9537. R_SUBQ:
  9538. begin
  9539. { MOVZX doesn't have a 64-bit variant, because
  9540. the 32-bit version implicitly zeroes the
  9541. upper 32-bits of the destination register }
  9542. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9543. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9544. setsubreg(tmpreg, R_SUBQ);
  9545. end;
  9546. {$endif x86_64}
  9547. else
  9548. Internalerror(2020030601);
  9549. end;
  9550. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9551. asml.InsertAfter(hp2,p);
  9552. end
  9553. else
  9554. tmpreg := increg;
  9555. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9556. begin
  9557. Taicpu(hp1).ops:=2;
  9558. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9559. end;
  9560. Taicpu(hp1).loadreg(0,tmpreg);
  9561. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9562. Result := True;
  9563. { p is no longer a Jcc instruction, so exit }
  9564. Exit;
  9565. end;
  9566. end;
  9567. end;
  9568. { Detect the following:
  9569. jmp<cond> @Lbl1
  9570. jmp @Lbl2
  9571. ...
  9572. @Lbl1:
  9573. ret
  9574. Change to:
  9575. jmp<inv_cond> @Lbl2
  9576. ret
  9577. }
  9578. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9579. begin
  9580. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9581. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9582. MatchInstruction(hp2,A_RET,[S_NO]) then
  9583. begin
  9584. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9585. { Change label address to that of the unconditional jump }
  9586. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9587. TAsmLabel(symbol).DecRefs;
  9588. taicpu(hp1).opcode := A_RET;
  9589. taicpu(hp1).is_jmp := false;
  9590. taicpu(hp1).ops := taicpu(hp2).ops;
  9591. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9592. case taicpu(hp2).ops of
  9593. 0:
  9594. taicpu(hp1).clearop(0);
  9595. 1:
  9596. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9597. else
  9598. internalerror(2016041302);
  9599. end;
  9600. end;
  9601. {$ifndef i8086}
  9602. end
  9603. {
  9604. convert
  9605. j<c> .L1
  9606. mov 1,reg
  9607. jmp .L2
  9608. .L1
  9609. mov 0,reg
  9610. .L2
  9611. into
  9612. mov 0,reg
  9613. set<not(c)> reg
  9614. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9615. would destroy the flag contents
  9616. }
  9617. else if MatchInstruction(hp1,A_MOV,[]) and
  9618. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9619. {$ifdef i386}
  9620. (
  9621. { Under i386, ESI, EDI, EBP and ESP
  9622. don't have an 8-bit representation }
  9623. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9624. ) and
  9625. {$endif i386}
  9626. (taicpu(hp1).oper[0]^.val=1) and
  9627. GetNextInstruction(hp1,hp2) and
  9628. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9629. GetNextInstruction(hp2,hp3) and
  9630. { skip align }
  9631. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9632. (hp3.typ=ait_label) and
  9633. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9634. (tai_label(hp3).labsym.getrefs=1) and
  9635. GetNextInstruction(hp3,hp4) and
  9636. MatchInstruction(hp4,A_MOV,[]) and
  9637. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9638. (taicpu(hp4).oper[0]^.val=0) and
  9639. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9640. GetNextInstruction(hp4,hp5) and
  9641. (hp5.typ=ait_label) and
  9642. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9643. (tai_label(hp5).labsym.getrefs=1) then
  9644. begin
  9645. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9646. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9647. { remove last label }
  9648. RemoveInstruction(hp5);
  9649. { remove second label }
  9650. RemoveInstruction(hp3);
  9651. { if align is present remove it }
  9652. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9653. RemoveInstruction(hp3);
  9654. { remove jmp }
  9655. RemoveInstruction(hp2);
  9656. if taicpu(hp1).opsize=S_B then
  9657. RemoveInstruction(hp1)
  9658. else
  9659. taicpu(hp1).loadconst(0,0);
  9660. taicpu(hp4).opcode:=A_SETcc;
  9661. taicpu(hp4).opsize:=S_B;
  9662. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9663. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9664. taicpu(hp4).opercnt:=1;
  9665. taicpu(hp4).ops:=1;
  9666. taicpu(hp4).freeop(1);
  9667. RemoveCurrentP(p);
  9668. Result:=true;
  9669. exit;
  9670. end
  9671. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9672. begin
  9673. { check for
  9674. jCC xxx
  9675. <several movs>
  9676. xxx:
  9677. Also spot:
  9678. Jcc xxx
  9679. <several movs>
  9680. jmp xxx
  9681. Change to:
  9682. <several cmovs with inverted condition>
  9683. jmp xxx
  9684. }
  9685. l:=0;
  9686. while assigned(hp1) and
  9687. CanBeCMOV(hp1) and
  9688. { stop on labels }
  9689. not(hp1.typ=ait_label) do
  9690. begin
  9691. inc(l);
  9692. hp5 := hp1;
  9693. GetNextInstruction(hp1,hp1);
  9694. end;
  9695. if assigned(hp1) then
  9696. begin
  9697. TransferUsedRegs(TmpUsedRegs);
  9698. if (
  9699. MatchInstruction(hp1, A_JMP, []) and
  9700. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9701. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9702. ) or
  9703. FindLabel(tasmlabel(symbol),hp1) then
  9704. begin
  9705. if (l<=4) and (l>0) then
  9706. begin
  9707. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9708. condition:=inverse_cond(taicpu(p).condition);
  9709. UpdateUsedRegs(tai(p.next));
  9710. GetNextInstruction(p,hp1);
  9711. repeat
  9712. if not Assigned(hp1) then
  9713. InternalError(2018062900);
  9714. taicpu(hp1).opcode:=A_CMOVcc;
  9715. taicpu(hp1).condition:=condition;
  9716. UpdateUsedRegs(tai(hp1.next));
  9717. GetNextInstruction(hp1,hp1);
  9718. until not(CanBeCMOV(hp1));
  9719. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9720. hp2 := hp1;
  9721. repeat
  9722. if not Assigned(hp2) then
  9723. InternalError(2018062910);
  9724. case hp2.typ of
  9725. ait_label:
  9726. { What we expected - break out of the loop (it won't be a dead label at the top of
  9727. a cluster because that was optimised at an earlier stage) }
  9728. Break;
  9729. ait_align:
  9730. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9731. begin
  9732. hp2 := tai(hp2.Next);
  9733. Continue;
  9734. end;
  9735. ait_instruction:
  9736. begin
  9737. if taicpu(hp2).opcode<>A_JMP then
  9738. InternalError(2018062912);
  9739. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9740. Break;
  9741. end
  9742. else
  9743. begin
  9744. { Might be a comment or temporary allocation entry }
  9745. if not (hp2.typ in SkipInstr) then
  9746. InternalError(2018062911);
  9747. hp2 := tai(hp2.Next);
  9748. Continue;
  9749. end;
  9750. end;
  9751. until False;
  9752. { Now we can safely decrement the reference count }
  9753. tasmlabel(symbol).decrefs;
  9754. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9755. { Remove the original jump }
  9756. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9757. if hp2.typ=ait_instruction then
  9758. begin
  9759. p:=hp2;
  9760. Result:=True;
  9761. end
  9762. else
  9763. begin
  9764. UpdateUsedRegs(tai(hp2.next));
  9765. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9766. { Remove the label if this is its final reference }
  9767. if (tasmlabel(symbol).getrefs=0) then
  9768. StripLabelFast(hp1);
  9769. end;
  9770. exit;
  9771. end;
  9772. end
  9773. else
  9774. begin
  9775. { check further for
  9776. jCC xxx
  9777. <several movs 1>
  9778. jmp yyy
  9779. xxx:
  9780. <several movs 2>
  9781. yyy:
  9782. }
  9783. { hp2 points to jmp yyy }
  9784. hp2:=hp1;
  9785. { skip hp1 to xxx (or an align right before it) }
  9786. GetNextInstruction(hp1, hp1);
  9787. if assigned(hp2) and
  9788. assigned(hp1) and
  9789. (l<=3) and
  9790. (hp2.typ=ait_instruction) and
  9791. (taicpu(hp2).is_jmp) and
  9792. (taicpu(hp2).condition=C_None) and
  9793. { real label and jump, no further references to the
  9794. label are allowed }
  9795. (tasmlabel(symbol).getrefs=1) and
  9796. FindLabel(tasmlabel(symbol),hp1) then
  9797. begin
  9798. l:=0;
  9799. { skip hp1 to <several moves 2> }
  9800. if (hp1.typ = ait_align) then
  9801. GetNextInstruction(hp1, hp1);
  9802. GetNextInstruction(hp1, hpmov2);
  9803. hp1 := hpmov2;
  9804. while assigned(hp1) and
  9805. CanBeCMOV(hp1) do
  9806. begin
  9807. inc(l);
  9808. hp5 := hp1;
  9809. GetNextInstruction(hp1, hp1);
  9810. end;
  9811. { hp1 points to yyy (or an align right before it) }
  9812. hp3 := hp1;
  9813. if assigned(hp1) and
  9814. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9815. begin
  9816. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9817. condition:=inverse_cond(taicpu(p).condition);
  9818. UpdateUsedRegs(tai(p.next));
  9819. GetNextInstruction(p,hp1);
  9820. repeat
  9821. taicpu(hp1).opcode:=A_CMOVcc;
  9822. taicpu(hp1).condition:=condition;
  9823. UpdateUsedRegs(tai(hp1.next));
  9824. GetNextInstruction(hp1,hp1);
  9825. until not(assigned(hp1)) or
  9826. not(CanBeCMOV(hp1));
  9827. condition:=inverse_cond(condition);
  9828. if GetLastInstruction(hpmov2,hp1) then
  9829. UpdateUsedRegs(tai(hp1.next));
  9830. hp1 := hpmov2;
  9831. { hp1 is now at <several movs 2> }
  9832. while Assigned(hp1) and CanBeCMOV(hp1) do
  9833. begin
  9834. taicpu(hp1).opcode:=A_CMOVcc;
  9835. taicpu(hp1).condition:=condition;
  9836. UpdateUsedRegs(tai(hp1.next));
  9837. GetNextInstruction(hp1,hp1);
  9838. end;
  9839. hp1 := p;
  9840. { Get first instruction after label }
  9841. UpdateUsedRegs(tai(hp3.next));
  9842. GetNextInstruction(hp3, p);
  9843. if assigned(p) and (hp3.typ = ait_align) then
  9844. GetNextInstruction(p, p);
  9845. { Don't dereference yet, as doing so will cause
  9846. GetNextInstruction to skip the label and
  9847. optional align marker. [Kit] }
  9848. GetNextInstruction(hp2, hp4);
  9849. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9850. { remove jCC }
  9851. RemoveInstruction(hp1);
  9852. { Now we can safely decrement it }
  9853. tasmlabel(symbol).decrefs;
  9854. { Remove label xxx (it will have a ref of zero due to the initial check }
  9855. StripLabelFast(hp4);
  9856. { remove jmp }
  9857. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9858. RemoveInstruction(hp2);
  9859. { As before, now we can safely decrement it }
  9860. tasmlabel(symbol).decrefs;
  9861. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9862. if tasmlabel(symbol).getrefs = 0 then
  9863. StripLabelFast(hp3);
  9864. if Assigned(p) then
  9865. result:=true;
  9866. exit;
  9867. end;
  9868. end;
  9869. end;
  9870. end;
  9871. {$endif i8086}
  9872. end;
  9873. end;
  9874. end;
  9875. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9876. var
  9877. hp1,hp2,hp3: tai;
  9878. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9879. NewSize: TOpSize;
  9880. NewRegSize: TSubRegister;
  9881. Limit: TCgInt;
  9882. SwapOper: POper;
  9883. begin
  9884. result:=false;
  9885. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9886. GetNextInstruction(p,hp1) and
  9887. (hp1.typ = ait_instruction);
  9888. if reg_and_hp1_is_instr and
  9889. (
  9890. (taicpu(hp1).opcode <> A_LEA) or
  9891. { If the LEA instruction can be converted into an arithmetic instruction,
  9892. it may be possible to then fold it. }
  9893. (
  9894. { If the flags register is in use, don't change the instruction
  9895. to an ADD otherwise this will scramble the flags. [Kit] }
  9896. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9897. ConvertLEA(taicpu(hp1))
  9898. )
  9899. ) and
  9900. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9901. GetNextInstruction(hp1,hp2) and
  9902. MatchInstruction(hp2,A_MOV,[]) and
  9903. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9904. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9905. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9906. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9907. {$ifdef i386}
  9908. { not all registers have byte size sub registers on i386 }
  9909. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9910. {$endif i386}
  9911. (((taicpu(hp1).ops=2) and
  9912. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9913. ((taicpu(hp1).ops=1) and
  9914. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9915. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9916. begin
  9917. { change movsX/movzX reg/ref, reg2
  9918. add/sub/or/... reg3/$const, reg2
  9919. mov reg2 reg/ref
  9920. to add/sub/or/... reg3/$const, reg/ref }
  9921. { by example:
  9922. movswl %si,%eax movswl %si,%eax p
  9923. decl %eax addl %edx,%eax hp1
  9924. movw %ax,%si movw %ax,%si hp2
  9925. ->
  9926. movswl %si,%eax movswl %si,%eax p
  9927. decw %eax addw %edx,%eax hp1
  9928. movw %ax,%si movw %ax,%si hp2
  9929. }
  9930. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9931. {
  9932. ->
  9933. movswl %si,%eax movswl %si,%eax p
  9934. decw %si addw %dx,%si hp1
  9935. movw %ax,%si movw %ax,%si hp2
  9936. }
  9937. case taicpu(hp1).ops of
  9938. 1:
  9939. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9940. 2:
  9941. begin
  9942. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9943. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9944. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9945. end;
  9946. else
  9947. internalerror(2008042702);
  9948. end;
  9949. {
  9950. ->
  9951. decw %si addw %dx,%si p
  9952. }
  9953. DebugMsg(SPeepholeOptimization + 'var3',p);
  9954. RemoveCurrentP(p, hp1);
  9955. RemoveInstruction(hp2);
  9956. Result := True;
  9957. Exit;
  9958. end;
  9959. if reg_and_hp1_is_instr and
  9960. (taicpu(hp1).opcode = A_MOV) and
  9961. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9962. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9963. {$ifdef x86_64}
  9964. { check for implicit extension to 64 bit }
  9965. or
  9966. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9967. (taicpu(hp1).opsize=S_Q) and
  9968. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9969. )
  9970. {$endif x86_64}
  9971. )
  9972. then
  9973. begin
  9974. { change
  9975. movx %reg1,%reg2
  9976. mov %reg2,%reg3
  9977. dealloc %reg2
  9978. into
  9979. movx %reg,%reg3
  9980. }
  9981. TransferUsedRegs(TmpUsedRegs);
  9982. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9983. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9984. begin
  9985. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9986. {$ifdef x86_64}
  9987. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9988. (taicpu(hp1).opsize=S_Q) then
  9989. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9990. else
  9991. {$endif x86_64}
  9992. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9993. RemoveInstruction(hp1);
  9994. Result := True;
  9995. Exit;
  9996. end;
  9997. end;
  9998. if reg_and_hp1_is_instr and
  9999. ((taicpu(hp1).opcode=A_MOV) or
  10000. (taicpu(hp1).opcode=A_ADD) or
  10001. (taicpu(hp1).opcode=A_SUB) or
  10002. (taicpu(hp1).opcode=A_CMP) or
  10003. (taicpu(hp1).opcode=A_OR) or
  10004. (taicpu(hp1).opcode=A_XOR) or
  10005. (taicpu(hp1).opcode=A_AND)
  10006. ) and
  10007. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10008. begin
  10009. AndTest := (taicpu(hp1).opcode=A_AND) and
  10010. GetNextInstruction(hp1, hp2) and
  10011. (hp2.typ = ait_instruction) and
  10012. (
  10013. (
  10014. (taicpu(hp2).opcode=A_TEST) and
  10015. (
  10016. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10017. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10018. (
  10019. { If the AND and TEST instructions share a constant, this is also valid }
  10020. (taicpu(hp1).oper[0]^.typ = top_const) and
  10021. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10022. )
  10023. ) and
  10024. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10025. ) or
  10026. (
  10027. (taicpu(hp2).opcode=A_CMP) and
  10028. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10029. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10030. )
  10031. );
  10032. { change
  10033. movx (oper),%reg2
  10034. and $x,%reg2
  10035. test %reg2,%reg2
  10036. dealloc %reg2
  10037. into
  10038. op %reg1,%reg3
  10039. if the second op accesses only the bits stored in reg1
  10040. }
  10041. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10042. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10043. (taicpu(hp1).oper[0]^.typ = top_const) and
  10044. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10045. AndTest then
  10046. begin
  10047. { Check if the AND constant is in range }
  10048. case taicpu(p).opsize of
  10049. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10050. begin
  10051. NewSize := S_B;
  10052. Limit := $FF;
  10053. end;
  10054. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10055. begin
  10056. NewSize := S_W;
  10057. Limit := $FFFF;
  10058. end;
  10059. {$ifdef x86_64}
  10060. S_LQ:
  10061. begin
  10062. NewSize := S_L;
  10063. Limit := $FFFFFFFF;
  10064. end;
  10065. {$endif x86_64}
  10066. else
  10067. InternalError(2021120303);
  10068. end;
  10069. if (
  10070. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10071. { Check for negative operands }
  10072. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10073. ) and
  10074. GetNextInstruction(hp2,hp3) and
  10075. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10076. (taicpu(hp3).condition in [C_E,C_NE]) then
  10077. begin
  10078. TransferUsedRegs(TmpUsedRegs);
  10079. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10080. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10081. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10082. begin
  10083. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10084. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10085. taicpu(hp1).opcode := A_TEST;
  10086. taicpu(hp1).opsize := NewSize;
  10087. RemoveInstruction(hp2);
  10088. RemoveCurrentP(p, hp1);
  10089. Result:=true;
  10090. exit;
  10091. end;
  10092. end;
  10093. end;
  10094. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10095. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10096. (taicpu(hp1).opsize=S_B)) or
  10097. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10098. (taicpu(hp1).opsize=S_W))
  10099. {$ifdef x86_64}
  10100. or ((taicpu(p).opsize=S_LQ) and
  10101. (taicpu(hp1).opsize=S_L))
  10102. {$endif x86_64}
  10103. ) and
  10104. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10105. begin
  10106. { change
  10107. movx %reg1,%reg2
  10108. op %reg2,%reg3
  10109. dealloc %reg2
  10110. into
  10111. op %reg1,%reg3
  10112. if the second op accesses only the bits stored in reg1
  10113. }
  10114. TransferUsedRegs(TmpUsedRegs);
  10115. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10116. if AndTest then
  10117. begin
  10118. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10119. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10120. end
  10121. else
  10122. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10123. if not RegUsed then
  10124. begin
  10125. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10126. if taicpu(p).oper[0]^.typ=top_reg then
  10127. begin
  10128. case taicpu(hp1).opsize of
  10129. S_B:
  10130. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10131. S_W:
  10132. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10133. S_L:
  10134. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10135. else
  10136. Internalerror(2020102301);
  10137. end;
  10138. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10139. end
  10140. else
  10141. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10142. RemoveCurrentP(p);
  10143. if AndTest then
  10144. RemoveInstruction(hp2);
  10145. result:=true;
  10146. exit;
  10147. end;
  10148. end
  10149. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10150. (
  10151. { Bitwise operations only }
  10152. (taicpu(hp1).opcode=A_AND) or
  10153. (taicpu(hp1).opcode=A_TEST) or
  10154. (
  10155. (taicpu(hp1).oper[0]^.typ = top_const) and
  10156. (
  10157. (taicpu(hp1).opcode=A_OR) or
  10158. (taicpu(hp1).opcode=A_XOR)
  10159. )
  10160. )
  10161. ) and
  10162. (
  10163. (taicpu(hp1).oper[0]^.typ = top_const) or
  10164. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10165. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10166. ) then
  10167. begin
  10168. { change
  10169. movx %reg2,%reg2
  10170. op const,%reg2
  10171. into
  10172. op const,%reg2 (smaller version)
  10173. movx %reg2,%reg2
  10174. also change
  10175. movx %reg1,%reg2
  10176. and/test (oper),%reg2
  10177. dealloc %reg2
  10178. into
  10179. and/test (oper),%reg1
  10180. }
  10181. case taicpu(p).opsize of
  10182. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10183. begin
  10184. NewSize := S_B;
  10185. NewRegSize := R_SUBL;
  10186. Limit := $FF;
  10187. end;
  10188. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10189. begin
  10190. NewSize := S_W;
  10191. NewRegSize := R_SUBW;
  10192. Limit := $FFFF;
  10193. end;
  10194. {$ifdef x86_64}
  10195. S_LQ:
  10196. begin
  10197. NewSize := S_L;
  10198. NewRegSize := R_SUBD;
  10199. Limit := $FFFFFFFF;
  10200. end;
  10201. {$endif x86_64}
  10202. else
  10203. Internalerror(2021120302);
  10204. end;
  10205. TransferUsedRegs(TmpUsedRegs);
  10206. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10207. if AndTest then
  10208. begin
  10209. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10210. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10211. end
  10212. else
  10213. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10214. if
  10215. (
  10216. (taicpu(p).opcode = A_MOVZX) and
  10217. (
  10218. (taicpu(hp1).opcode=A_AND) or
  10219. (taicpu(hp1).opcode=A_TEST)
  10220. ) and
  10221. not (
  10222. { If both are references, then the final instruction will have
  10223. both operands as references, which is not allowed }
  10224. (taicpu(p).oper[0]^.typ = top_ref) and
  10225. (taicpu(hp1).oper[0]^.typ = top_ref)
  10226. ) and
  10227. not RegUsed
  10228. ) or
  10229. (
  10230. (
  10231. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10232. not RegUsed
  10233. ) and
  10234. (taicpu(p).oper[0]^.typ = top_reg) and
  10235. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10236. (taicpu(hp1).oper[0]^.typ = top_const) and
  10237. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10238. ) then
  10239. begin
  10240. {$if defined(i386) or defined(i8086)}
  10241. { If the target size is 8-bit, make sure we can actually encode it }
  10242. 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
  10243. Exit;
  10244. {$endif i386 or i8086}
  10245. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10246. taicpu(hp1).opsize := NewSize;
  10247. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10248. if AndTest then
  10249. begin
  10250. RemoveInstruction(hp2);
  10251. if not RegUsed then
  10252. begin
  10253. taicpu(hp1).opcode := A_TEST;
  10254. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10255. begin
  10256. { Make sure the reference is the second operand }
  10257. SwapOper := taicpu(hp1).oper[0];
  10258. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10259. taicpu(hp1).oper[1] := SwapOper;
  10260. end;
  10261. end;
  10262. end;
  10263. case taicpu(hp1).oper[0]^.typ of
  10264. top_reg:
  10265. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10266. top_const:
  10267. { For the AND/TEST case }
  10268. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10269. else
  10270. ;
  10271. end;
  10272. if RegUsed then
  10273. begin
  10274. AsmL.Remove(p);
  10275. AsmL.InsertAfter(p, hp1);
  10276. p := hp1;
  10277. end
  10278. else
  10279. RemoveCurrentP(p, hp1);
  10280. result:=true;
  10281. exit;
  10282. end;
  10283. end;
  10284. end;
  10285. if reg_and_hp1_is_instr and
  10286. (taicpu(p).oper[0]^.typ = top_reg) and
  10287. (
  10288. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10289. ) and
  10290. (taicpu(hp1).oper[0]^.typ = top_const) and
  10291. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10292. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10293. { Minimum shift value allowed is the bit difference between the sizes }
  10294. (taicpu(hp1).oper[0]^.val >=
  10295. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10296. 8 * (
  10297. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10298. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10299. )
  10300. ) then
  10301. begin
  10302. { For:
  10303. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10304. shl/sal ##, %reg1
  10305. Remove the movsx/movzx instruction if the shift overwrites the
  10306. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10307. }
  10308. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10309. RemoveCurrentP(p, hp1);
  10310. Result := True;
  10311. Exit;
  10312. end
  10313. else if reg_and_hp1_is_instr and
  10314. (taicpu(p).oper[0]^.typ = top_reg) and
  10315. (
  10316. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10317. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10318. ) and
  10319. (taicpu(hp1).oper[0]^.typ = top_const) and
  10320. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10321. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10322. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10323. (taicpu(hp1).oper[0]^.val <
  10324. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10325. 8 * (
  10326. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10327. )
  10328. ) then
  10329. begin
  10330. { For:
  10331. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10332. sar ##, %reg1 shr ##, %reg1
  10333. Move the shift to before the movx instruction if the shift value
  10334. is not too large.
  10335. }
  10336. asml.Remove(hp1);
  10337. asml.InsertBefore(hp1, p);
  10338. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10339. case taicpu(p).opsize of
  10340. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10341. taicpu(hp1).opsize := S_B;
  10342. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10343. taicpu(hp1).opsize := S_W;
  10344. {$ifdef x86_64}
  10345. S_LQ:
  10346. taicpu(hp1).opsize := S_L;
  10347. {$endif}
  10348. else
  10349. InternalError(2020112401);
  10350. end;
  10351. if (taicpu(hp1).opcode = A_SHR) then
  10352. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10353. else
  10354. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10355. Result := True;
  10356. end;
  10357. if reg_and_hp1_is_instr and
  10358. (taicpu(p).oper[0]^.typ = top_reg) and
  10359. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10360. (
  10361. (taicpu(hp1).opcode = taicpu(p).opcode)
  10362. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10363. {$ifdef x86_64}
  10364. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10365. {$endif x86_64}
  10366. ) then
  10367. begin
  10368. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10369. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10370. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10371. begin
  10372. {
  10373. For example:
  10374. movzbw %al,%ax
  10375. movzwl %ax,%eax
  10376. Compress into:
  10377. movzbl %al,%eax
  10378. }
  10379. RegUsed := False;
  10380. case taicpu(p).opsize of
  10381. S_BW:
  10382. case taicpu(hp1).opsize of
  10383. S_WL:
  10384. begin
  10385. taicpu(p).opsize := S_BL;
  10386. RegUsed := True;
  10387. end;
  10388. {$ifdef x86_64}
  10389. S_WQ:
  10390. begin
  10391. if taicpu(p).opcode = A_MOVZX then
  10392. begin
  10393. taicpu(p).opsize := S_BL;
  10394. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10395. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10396. end
  10397. else
  10398. taicpu(p).opsize := S_BQ;
  10399. RegUsed := True;
  10400. end;
  10401. {$endif x86_64}
  10402. else
  10403. ;
  10404. end;
  10405. {$ifdef x86_64}
  10406. S_BL:
  10407. case taicpu(hp1).opsize of
  10408. S_LQ:
  10409. begin
  10410. if taicpu(p).opcode = A_MOVZX then
  10411. begin
  10412. taicpu(p).opsize := S_BL;
  10413. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10414. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10415. end
  10416. else
  10417. taicpu(p).opsize := S_BQ;
  10418. RegUsed := True;
  10419. end;
  10420. else
  10421. ;
  10422. end;
  10423. S_WL:
  10424. case taicpu(hp1).opsize of
  10425. S_LQ:
  10426. begin
  10427. if taicpu(p).opcode = A_MOVZX then
  10428. begin
  10429. taicpu(p).opsize := S_WL;
  10430. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10431. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10432. end
  10433. else
  10434. taicpu(p).opsize := S_WQ;
  10435. RegUsed := True;
  10436. end;
  10437. else
  10438. ;
  10439. end;
  10440. {$endif x86_64}
  10441. else
  10442. ;
  10443. end;
  10444. if RegUsed then
  10445. begin
  10446. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10447. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10448. RemoveInstruction(hp1);
  10449. Result := True;
  10450. Exit;
  10451. end;
  10452. end;
  10453. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10454. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10455. GetNextInstruction(hp1, hp2) and
  10456. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10457. (
  10458. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10459. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10460. {$ifdef x86_64}
  10461. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10462. {$endif x86_64}
  10463. ) and
  10464. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10465. (
  10466. (
  10467. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10468. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10469. ) or
  10470. (
  10471. { Only allow the operands in reverse order for TEST instructions }
  10472. (taicpu(hp2).opcode = A_TEST) and
  10473. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10474. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10475. )
  10476. ) then
  10477. begin
  10478. {
  10479. For example:
  10480. movzbl %al,%eax
  10481. movzbl (ref),%edx
  10482. andl %edx,%eax
  10483. (%edx deallocated)
  10484. Change to:
  10485. andb (ref),%al
  10486. movzbl %al,%eax
  10487. Rules are:
  10488. - First two instructions have the same opcode and opsize
  10489. - First instruction's operands are the same super-register
  10490. - Second instruction operates on a different register
  10491. - Third instruction is AND, OR, XOR or TEST
  10492. - Third instruction's operands are the destination registers of the first two instructions
  10493. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10494. - Second instruction's destination register is deallocated afterwards
  10495. }
  10496. TransferUsedRegs(TmpUsedRegs);
  10497. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10498. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10499. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10500. begin
  10501. case taicpu(p).opsize of
  10502. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10503. NewSize := S_B;
  10504. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10505. NewSize := S_W;
  10506. {$ifdef x86_64}
  10507. S_LQ:
  10508. NewSize := S_L;
  10509. {$endif x86_64}
  10510. else
  10511. InternalError(2021120301);
  10512. end;
  10513. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10514. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10515. taicpu(hp2).opsize := NewSize;
  10516. RemoveInstruction(hp1);
  10517. { With TEST, it's best to keep the MOVX instruction at the top }
  10518. if (taicpu(hp2).opcode <> A_TEST) then
  10519. begin
  10520. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10521. asml.Remove(p);
  10522. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10523. asml.InsertAfter(p, hp2);
  10524. p := hp2;
  10525. end
  10526. else
  10527. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10528. Result := True;
  10529. Exit;
  10530. end;
  10531. end;
  10532. end;
  10533. if taicpu(p).opcode=A_MOVZX then
  10534. begin
  10535. { removes superfluous And's after movzx's }
  10536. if reg_and_hp1_is_instr and
  10537. (taicpu(hp1).opcode = A_AND) and
  10538. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10539. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10540. {$ifdef x86_64}
  10541. { check for implicit extension to 64 bit }
  10542. or
  10543. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10544. (taicpu(hp1).opsize=S_Q) and
  10545. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10546. )
  10547. {$endif x86_64}
  10548. )
  10549. then
  10550. begin
  10551. case taicpu(p).opsize Of
  10552. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10553. if (taicpu(hp1).oper[0]^.val = $ff) then
  10554. begin
  10555. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10556. RemoveInstruction(hp1);
  10557. Result:=true;
  10558. exit;
  10559. end;
  10560. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10561. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10562. begin
  10563. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10564. RemoveInstruction(hp1);
  10565. Result:=true;
  10566. exit;
  10567. end;
  10568. {$ifdef x86_64}
  10569. S_LQ:
  10570. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10571. begin
  10572. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10573. RemoveInstruction(hp1);
  10574. Result:=true;
  10575. exit;
  10576. end;
  10577. {$endif x86_64}
  10578. else
  10579. ;
  10580. end;
  10581. { we cannot get rid of the and, but can we get rid of the movz ?}
  10582. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10583. begin
  10584. case taicpu(p).opsize Of
  10585. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10586. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10587. begin
  10588. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10589. RemoveCurrentP(p,hp1);
  10590. Result:=true;
  10591. exit;
  10592. end;
  10593. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10594. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10595. begin
  10596. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10597. RemoveCurrentP(p,hp1);
  10598. Result:=true;
  10599. exit;
  10600. end;
  10601. {$ifdef x86_64}
  10602. S_LQ:
  10603. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10604. begin
  10605. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10606. RemoveCurrentP(p,hp1);
  10607. Result:=true;
  10608. exit;
  10609. end;
  10610. {$endif x86_64}
  10611. else
  10612. ;
  10613. end;
  10614. end;
  10615. end;
  10616. { changes some movzx constructs to faster synonyms (all examples
  10617. are given with eax/ax, but are also valid for other registers)}
  10618. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10619. begin
  10620. case taicpu(p).opsize of
  10621. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10622. (the machine code is equivalent to movzbl %al,%eax), but the
  10623. code generator still generates that assembler instruction and
  10624. it is silently converted. This should probably be checked.
  10625. [Kit] }
  10626. S_BW:
  10627. begin
  10628. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10629. (
  10630. not IsMOVZXAcceptable
  10631. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10632. or (
  10633. (cs_opt_size in current_settings.optimizerswitches) and
  10634. (taicpu(p).oper[1]^.reg = NR_AX)
  10635. )
  10636. ) then
  10637. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10638. begin
  10639. DebugMsg(SPeepholeOptimization + 'var7',p);
  10640. taicpu(p).opcode := A_AND;
  10641. taicpu(p).changeopsize(S_W);
  10642. taicpu(p).loadConst(0,$ff);
  10643. Result := True;
  10644. end
  10645. else if not IsMOVZXAcceptable and
  10646. GetNextInstruction(p, hp1) and
  10647. (tai(hp1).typ = ait_instruction) and
  10648. (taicpu(hp1).opcode = A_AND) and
  10649. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10650. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10651. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10652. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10653. begin
  10654. DebugMsg(SPeepholeOptimization + 'var8',p);
  10655. taicpu(p).opcode := A_MOV;
  10656. taicpu(p).changeopsize(S_W);
  10657. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10658. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10659. Result := True;
  10660. end;
  10661. end;
  10662. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10663. S_BL:
  10664. begin
  10665. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10666. (
  10667. not IsMOVZXAcceptable
  10668. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10669. or (
  10670. (cs_opt_size in current_settings.optimizerswitches) and
  10671. (taicpu(p).oper[1]^.reg = NR_EAX)
  10672. )
  10673. ) then
  10674. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10675. begin
  10676. DebugMsg(SPeepholeOptimization + 'var9',p);
  10677. taicpu(p).opcode := A_AND;
  10678. taicpu(p).changeopsize(S_L);
  10679. taicpu(p).loadConst(0,$ff);
  10680. Result := True;
  10681. end
  10682. else if not IsMOVZXAcceptable and
  10683. GetNextInstruction(p, hp1) and
  10684. (tai(hp1).typ = ait_instruction) and
  10685. (taicpu(hp1).opcode = A_AND) and
  10686. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10687. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10688. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10689. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10690. begin
  10691. DebugMsg(SPeepholeOptimization + 'var10',p);
  10692. taicpu(p).opcode := A_MOV;
  10693. taicpu(p).changeopsize(S_L);
  10694. { do not use R_SUBWHOLE
  10695. as movl %rdx,%eax
  10696. is invalid in assembler PM }
  10697. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10698. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10699. Result := True;
  10700. end;
  10701. end;
  10702. {$endif i8086}
  10703. S_WL:
  10704. if not IsMOVZXAcceptable then
  10705. begin
  10706. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10707. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10708. begin
  10709. DebugMsg(SPeepholeOptimization + 'var11',p);
  10710. taicpu(p).opcode := A_AND;
  10711. taicpu(p).changeopsize(S_L);
  10712. taicpu(p).loadConst(0,$ffff);
  10713. Result := True;
  10714. end
  10715. else if GetNextInstruction(p, hp1) and
  10716. (tai(hp1).typ = ait_instruction) and
  10717. (taicpu(hp1).opcode = A_AND) and
  10718. (taicpu(hp1).oper[0]^.typ = top_const) and
  10719. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10720. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10721. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10722. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10723. begin
  10724. DebugMsg(SPeepholeOptimization + 'var12',p);
  10725. taicpu(p).opcode := A_MOV;
  10726. taicpu(p).changeopsize(S_L);
  10727. { do not use R_SUBWHOLE
  10728. as movl %rdx,%eax
  10729. is invalid in assembler PM }
  10730. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10731. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10732. Result := True;
  10733. end;
  10734. end;
  10735. else
  10736. InternalError(2017050705);
  10737. end;
  10738. end
  10739. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10740. begin
  10741. if GetNextInstruction(p, hp1) and
  10742. (tai(hp1).typ = ait_instruction) and
  10743. (taicpu(hp1).opcode = A_AND) and
  10744. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10745. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10746. begin
  10747. //taicpu(p).opcode := A_MOV;
  10748. case taicpu(p).opsize Of
  10749. S_BL:
  10750. begin
  10751. DebugMsg(SPeepholeOptimization + 'var13',p);
  10752. taicpu(hp1).changeopsize(S_L);
  10753. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10754. end;
  10755. S_WL:
  10756. begin
  10757. DebugMsg(SPeepholeOptimization + 'var14',p);
  10758. taicpu(hp1).changeopsize(S_L);
  10759. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10760. end;
  10761. S_BW:
  10762. begin
  10763. DebugMsg(SPeepholeOptimization + 'var15',p);
  10764. taicpu(hp1).changeopsize(S_W);
  10765. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10766. end;
  10767. else
  10768. Internalerror(2017050704)
  10769. end;
  10770. Result := True;
  10771. end;
  10772. end;
  10773. end;
  10774. end;
  10775. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10776. var
  10777. hp1, hp2 : tai;
  10778. MaskLength : Cardinal;
  10779. MaskedBits : TCgInt;
  10780. ActiveReg : TRegister;
  10781. begin
  10782. Result:=false;
  10783. { There are no optimisations for reference targets }
  10784. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10785. Exit;
  10786. while GetNextInstruction(p, hp1) and
  10787. (hp1.typ = ait_instruction) do
  10788. begin
  10789. if (taicpu(p).oper[0]^.typ = top_const) then
  10790. begin
  10791. case taicpu(hp1).opcode of
  10792. A_AND:
  10793. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10794. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10795. { the second register must contain the first one, so compare their subreg types }
  10796. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10797. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10798. { change
  10799. and const1, reg
  10800. and const2, reg
  10801. to
  10802. and (const1 and const2), reg
  10803. }
  10804. begin
  10805. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10806. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10807. RemoveCurrentP(p, hp1);
  10808. Result:=true;
  10809. exit;
  10810. end;
  10811. A_CMP:
  10812. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10813. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10814. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10815. { Just check that the condition on the next instruction is compatible }
  10816. GetNextInstruction(hp1, hp2) and
  10817. (hp2.typ = ait_instruction) and
  10818. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10819. then
  10820. { change
  10821. and 2^n, reg
  10822. cmp 2^n, reg
  10823. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10824. to
  10825. and 2^n, reg
  10826. test reg, reg
  10827. j(~c) / set(~c) / cmov(~c)
  10828. }
  10829. begin
  10830. { Keep TEST instruction in, rather than remove it, because
  10831. it may trigger other optimisations such as MovAndTest2Test }
  10832. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10833. taicpu(hp1).opcode := A_TEST;
  10834. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10835. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10836. Result := True;
  10837. Exit;
  10838. end;
  10839. A_MOVZX:
  10840. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10841. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10842. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10843. (
  10844. (
  10845. (taicpu(p).opsize=S_W) and
  10846. (taicpu(hp1).opsize=S_BW)
  10847. ) or
  10848. (
  10849. (taicpu(p).opsize=S_L) and
  10850. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10851. )
  10852. {$ifdef x86_64}
  10853. or
  10854. (
  10855. (taicpu(p).opsize=S_Q) and
  10856. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10857. )
  10858. {$endif x86_64}
  10859. ) then
  10860. begin
  10861. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10862. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10863. ) or
  10864. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10865. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10866. then
  10867. begin
  10868. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10869. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10870. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10871. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10872. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10873. }
  10874. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10875. RemoveInstruction(hp1);
  10876. { See if there are other optimisations possible }
  10877. Continue;
  10878. end;
  10879. end;
  10880. A_SHL:
  10881. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10882. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10883. begin
  10884. {$ifopt R+}
  10885. {$define RANGE_WAS_ON}
  10886. {$R-}
  10887. {$endif}
  10888. { get length of potential and mask }
  10889. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10890. { really a mask? }
  10891. {$ifdef RANGE_WAS_ON}
  10892. {$R+}
  10893. {$endif}
  10894. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10895. { unmasked part shifted out? }
  10896. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10897. begin
  10898. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10899. RemoveCurrentP(p, hp1);
  10900. Result:=true;
  10901. exit;
  10902. end;
  10903. end;
  10904. A_SHR:
  10905. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10906. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10907. (taicpu(hp1).oper[0]^.val <= 63) then
  10908. begin
  10909. { Does SHR combined with the AND cover all the bits?
  10910. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10911. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10912. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10913. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10914. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10915. begin
  10916. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10917. RemoveCurrentP(p, hp1);
  10918. Result := True;
  10919. Exit;
  10920. end;
  10921. end;
  10922. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10923. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10924. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10925. begin
  10926. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10927. (
  10928. (
  10929. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10930. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10931. ) or (
  10932. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10933. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10934. {$ifdef x86_64}
  10935. ) or (
  10936. (taicpu(hp1).opsize = S_LQ) and
  10937. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10938. {$endif x86_64}
  10939. )
  10940. ) then
  10941. begin
  10942. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10943. begin
  10944. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10945. RemoveInstruction(hp1);
  10946. { See if there are other optimisations possible }
  10947. Continue;
  10948. end;
  10949. { The super-registers are the same though.
  10950. Note that this change by itself doesn't improve
  10951. code speed, but it opens up other optimisations. }
  10952. {$ifdef x86_64}
  10953. { Convert 64-bit register to 32-bit }
  10954. case taicpu(hp1).opsize of
  10955. S_BQ:
  10956. begin
  10957. taicpu(hp1).opsize := S_BL;
  10958. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10959. end;
  10960. S_WQ:
  10961. begin
  10962. taicpu(hp1).opsize := S_WL;
  10963. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10964. end
  10965. else
  10966. ;
  10967. end;
  10968. {$endif x86_64}
  10969. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10970. taicpu(hp1).opcode := A_MOVZX;
  10971. { See if there are other optimisations possible }
  10972. Continue;
  10973. end;
  10974. end;
  10975. else
  10976. ;
  10977. end;
  10978. end
  10979. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10980. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10981. begin
  10982. {$ifdef x86_64}
  10983. if (taicpu(p).opsize = S_Q) then
  10984. begin
  10985. { Never necessary }
  10986. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10987. RemoveCurrentP(p, hp1);
  10988. Result := True;
  10989. Exit;
  10990. end;
  10991. {$endif x86_64}
  10992. { Forward check to determine necessity of and %reg,%reg }
  10993. TransferUsedRegs(TmpUsedRegs);
  10994. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10995. { Saves on a bunch of dereferences }
  10996. ActiveReg := taicpu(p).oper[1]^.reg;
  10997. case taicpu(hp1).opcode of
  10998. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10999. if (
  11000. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11001. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11002. ) and
  11003. (
  11004. (taicpu(hp1).opcode <> A_MOV) or
  11005. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11006. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11007. ) and
  11008. not (
  11009. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11010. (taicpu(hp1).opcode = A_MOV) and
  11011. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11012. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11013. ) and
  11014. (
  11015. (
  11016. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11017. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11018. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11019. ) or
  11020. (
  11021. {$ifdef x86_64}
  11022. (
  11023. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11024. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11025. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11026. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11027. ) and
  11028. {$endif x86_64}
  11029. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11030. )
  11031. ) then
  11032. begin
  11033. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11034. RemoveCurrentP(p, hp1);
  11035. Result := True;
  11036. Exit;
  11037. end;
  11038. A_ADD,
  11039. A_AND,
  11040. A_BSF,
  11041. A_BSR,
  11042. A_BTC,
  11043. A_BTR,
  11044. A_BTS,
  11045. A_OR,
  11046. A_SUB,
  11047. A_XOR:
  11048. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11049. if (
  11050. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11051. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11052. ) and
  11053. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11054. begin
  11055. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11056. RemoveCurrentP(p, hp1);
  11057. Result := True;
  11058. Exit;
  11059. end;
  11060. A_CMP,
  11061. A_TEST:
  11062. if (
  11063. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11064. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11065. ) and
  11066. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11067. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11068. begin
  11069. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11070. RemoveCurrentP(p, hp1);
  11071. Result := True;
  11072. Exit;
  11073. end;
  11074. A_BSWAP,
  11075. A_NEG,
  11076. A_NOT:
  11077. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11078. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11079. begin
  11080. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11081. RemoveCurrentP(p, hp1);
  11082. Result := True;
  11083. Exit;
  11084. end;
  11085. else
  11086. ;
  11087. end;
  11088. end;
  11089. if (taicpu(hp1).is_jmp) and
  11090. (taicpu(hp1).opcode<>A_JMP) and
  11091. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11092. begin
  11093. { change
  11094. and x, reg
  11095. jxx
  11096. to
  11097. test x, reg
  11098. jxx
  11099. if reg is deallocated before the
  11100. jump, but only if it's a conditional jump (PFV)
  11101. }
  11102. taicpu(p).opcode := A_TEST;
  11103. Exit;
  11104. end;
  11105. Break;
  11106. end;
  11107. { Lone AND tests }
  11108. if (taicpu(p).oper[0]^.typ = top_const) then
  11109. begin
  11110. {
  11111. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11112. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11113. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11114. }
  11115. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11116. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11117. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11118. begin
  11119. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11120. if taicpu(p).opsize = S_L then
  11121. begin
  11122. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11123. Result := True;
  11124. end;
  11125. end;
  11126. end;
  11127. { Backward check to determine necessity of and %reg,%reg }
  11128. if (taicpu(p).oper[0]^.typ = top_reg) and
  11129. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11130. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11131. GetLastInstruction(p, hp2) and
  11132. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11133. { Check size of adjacent instruction to determine if the AND is
  11134. effectively a null operation }
  11135. (
  11136. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11137. { Note: Don't include S_Q }
  11138. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11139. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11140. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11141. ) then
  11142. begin
  11143. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11144. { If GetNextInstruction returned False, hp1 will be nil }
  11145. RemoveCurrentP(p, hp1);
  11146. Result := True;
  11147. Exit;
  11148. end;
  11149. end;
  11150. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11151. var
  11152. hp1: tai; NewRef: TReference;
  11153. { This entire nested function is used in an if-statement below, but we
  11154. want to avoid all the used reg transfers and GetNextInstruction calls
  11155. until we really have to check }
  11156. function MemRegisterNotUsedLater: Boolean; inline;
  11157. var
  11158. hp2: tai;
  11159. begin
  11160. TransferUsedRegs(TmpUsedRegs);
  11161. hp2 := p;
  11162. repeat
  11163. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11164. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11165. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11166. end;
  11167. begin
  11168. Result := False;
  11169. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  11170. Exit;
  11171. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  11172. begin
  11173. { Change:
  11174. add %reg2,%reg1
  11175. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11176. To:
  11177. mov/s/z #(%reg1,%reg2),%reg1
  11178. }
  11179. if MatchOpType(taicpu(p), top_reg, top_reg) and
  11180. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11181. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11182. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11183. (
  11184. (
  11185. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11186. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11187. { r/esp cannot be an index }
  11188. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11189. ) or (
  11190. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11191. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11192. )
  11193. ) and (
  11194. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11195. (
  11196. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11197. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11198. MemRegisterNotUsedLater
  11199. )
  11200. ) then
  11201. begin
  11202. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11203. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11204. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11205. RemoveCurrentp(p, hp1);
  11206. Result := True;
  11207. Exit;
  11208. end;
  11209. { Change:
  11210. addl/q $x,%reg1
  11211. movl/q %reg1,%reg2
  11212. To:
  11213. leal/q $x(%reg1),%reg2
  11214. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11215. Breaks the dependency chain.
  11216. }
  11217. if MatchOpType(taicpu(p),top_const,top_reg) and
  11218. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11219. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11220. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11221. (
  11222. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11223. not (cs_opt_size in current_settings.optimizerswitches) or
  11224. (
  11225. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11226. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11227. )
  11228. ) then
  11229. begin
  11230. { Change the MOV instruction to a LEA instruction, and update the
  11231. first operand }
  11232. reference_reset(NewRef, 1, []);
  11233. NewRef.base := taicpu(p).oper[1]^.reg;
  11234. NewRef.scalefactor := 1;
  11235. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11236. taicpu(hp1).opcode := A_LEA;
  11237. taicpu(hp1).loadref(0, NewRef);
  11238. TransferUsedRegs(TmpUsedRegs);
  11239. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11240. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11241. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11242. begin
  11243. { Move what is now the LEA instruction to before the SUB instruction }
  11244. Asml.Remove(hp1);
  11245. Asml.InsertBefore(hp1, p);
  11246. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11247. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11248. p := hp1;
  11249. end
  11250. else
  11251. begin
  11252. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11253. RemoveCurrentP(p, hp1);
  11254. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  11255. end;
  11256. Result := True;
  11257. end;
  11258. end;
  11259. end;
  11260. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11261. var
  11262. SubReg: TSubRegister;
  11263. begin
  11264. Result:=false;
  11265. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11266. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11267. with taicpu(p).oper[0]^.ref^ do
  11268. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11269. begin
  11270. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11271. begin
  11272. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11273. taicpu(p).opcode := A_ADD;
  11274. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11275. Result := True;
  11276. end
  11277. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11278. begin
  11279. if (base <> NR_NO) then
  11280. begin
  11281. if (scalefactor <= 1) then
  11282. begin
  11283. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11284. taicpu(p).opcode := A_ADD;
  11285. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11286. Result := True;
  11287. end;
  11288. end
  11289. else
  11290. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11291. if (scalefactor in [2, 4, 8]) then
  11292. begin
  11293. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11294. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11295. taicpu(p).opcode := A_SHL;
  11296. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11297. Result := True;
  11298. end;
  11299. end;
  11300. end;
  11301. end;
  11302. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11303. var
  11304. hp1: tai; NewRef: TReference;
  11305. begin
  11306. { Change:
  11307. subl/q $x,%reg1
  11308. movl/q %reg1,%reg2
  11309. To:
  11310. leal/q $-x(%reg1),%reg2
  11311. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11312. Breaks the dependency chain and potentially permits the removal of
  11313. a CMP instruction if one follows.
  11314. }
  11315. Result := False;
  11316. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11317. MatchOpType(taicpu(p),top_const,top_reg) and
  11318. GetNextInstruction(p, hp1) and
  11319. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11320. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11321. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11322. (
  11323. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11324. not (cs_opt_size in current_settings.optimizerswitches) or
  11325. (
  11326. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11327. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11328. )
  11329. ) then
  11330. begin
  11331. { Change the MOV instruction to a LEA instruction, and update the
  11332. first operand }
  11333. reference_reset(NewRef, 1, []);
  11334. NewRef.base := taicpu(p).oper[1]^.reg;
  11335. NewRef.scalefactor := 1;
  11336. NewRef.offset := -taicpu(p).oper[0]^.val;
  11337. taicpu(hp1).opcode := A_LEA;
  11338. taicpu(hp1).loadref(0, NewRef);
  11339. TransferUsedRegs(TmpUsedRegs);
  11340. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11341. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11342. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11343. begin
  11344. { Move what is now the LEA instruction to before the SUB instruction }
  11345. Asml.Remove(hp1);
  11346. Asml.InsertBefore(hp1, p);
  11347. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11348. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11349. p := hp1;
  11350. end
  11351. else
  11352. begin
  11353. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11354. RemoveCurrentP(p, hp1);
  11355. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11356. end;
  11357. Result := True;
  11358. end;
  11359. end;
  11360. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11361. begin
  11362. { we can skip all instructions not messing with the stack pointer }
  11363. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11364. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11365. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11366. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11367. ({(taicpu(hp1).ops=0) or }
  11368. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11369. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11370. ) and }
  11371. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11372. )
  11373. ) do
  11374. GetNextInstruction(hp1,hp1);
  11375. Result:=assigned(hp1);
  11376. end;
  11377. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11378. var
  11379. hp1, hp2, hp3, hp4, hp5: tai;
  11380. begin
  11381. Result:=false;
  11382. hp5:=nil;
  11383. { replace
  11384. leal(q) x(<stackpointer>),<stackpointer>
  11385. call procname
  11386. leal(q) -x(<stackpointer>),<stackpointer>
  11387. ret
  11388. by
  11389. jmp procname
  11390. but do it only on level 4 because it destroys stack back traces
  11391. }
  11392. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11393. MatchOpType(taicpu(p),top_ref,top_reg) and
  11394. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11395. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11396. { the -8 or -24 are not required, but bail out early if possible,
  11397. higher values are unlikely }
  11398. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11399. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11400. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11401. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11402. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11403. GetNextInstruction(p, hp1) and
  11404. { Take a copy of hp1 }
  11405. SetAndTest(hp1, hp4) and
  11406. { trick to skip label }
  11407. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11408. SkipSimpleInstructions(hp1) and
  11409. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11410. GetNextInstruction(hp1, hp2) and
  11411. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11412. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11413. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11414. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11415. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11416. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11417. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11418. { Segment register will be NR_NO }
  11419. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11420. GetNextInstruction(hp2, hp3) and
  11421. { trick to skip label }
  11422. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11423. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11424. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11425. SetAndTest(hp3,hp5) and
  11426. GetNextInstruction(hp3,hp3) and
  11427. MatchInstruction(hp3,A_RET,[S_NO])
  11428. )
  11429. ) and
  11430. (taicpu(hp3).ops=0) then
  11431. begin
  11432. taicpu(hp1).opcode := A_JMP;
  11433. taicpu(hp1).is_jmp := true;
  11434. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11435. RemoveCurrentP(p, hp4);
  11436. RemoveInstruction(hp2);
  11437. RemoveInstruction(hp3);
  11438. if Assigned(hp5) then
  11439. begin
  11440. AsmL.Remove(hp5);
  11441. ASmL.InsertBefore(hp5,hp1)
  11442. end;
  11443. Result:=true;
  11444. end;
  11445. end;
  11446. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11447. {$ifdef x86_64}
  11448. var
  11449. hp1, hp2, hp3, hp4, hp5: tai;
  11450. {$endif x86_64}
  11451. begin
  11452. Result:=false;
  11453. {$ifdef x86_64}
  11454. hp5:=nil;
  11455. { replace
  11456. push %rax
  11457. call procname
  11458. pop %rcx
  11459. ret
  11460. by
  11461. jmp procname
  11462. but do it only on level 4 because it destroys stack back traces
  11463. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11464. for all supported calling conventions
  11465. }
  11466. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11467. MatchOpType(taicpu(p),top_reg) and
  11468. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11469. GetNextInstruction(p, hp1) and
  11470. { Take a copy of hp1 }
  11471. SetAndTest(hp1, hp4) and
  11472. { trick to skip label }
  11473. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11474. SkipSimpleInstructions(hp1) and
  11475. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11476. GetNextInstruction(hp1, hp2) and
  11477. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11478. MatchOpType(taicpu(hp2),top_reg) and
  11479. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11480. GetNextInstruction(hp2, hp3) and
  11481. { trick to skip label }
  11482. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11483. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11484. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11485. SetAndTest(hp3,hp5) and
  11486. GetNextInstruction(hp3,hp3) and
  11487. MatchInstruction(hp3,A_RET,[S_NO])
  11488. )
  11489. ) and
  11490. (taicpu(hp3).ops=0) then
  11491. begin
  11492. taicpu(hp1).opcode := A_JMP;
  11493. taicpu(hp1).is_jmp := true;
  11494. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11495. RemoveCurrentP(p, hp4);
  11496. RemoveInstruction(hp2);
  11497. RemoveInstruction(hp3);
  11498. if Assigned(hp5) then
  11499. begin
  11500. AsmL.Remove(hp5);
  11501. ASmL.InsertBefore(hp5,hp1)
  11502. end;
  11503. Result:=true;
  11504. end;
  11505. {$endif x86_64}
  11506. end;
  11507. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11508. var
  11509. Value, RegName: string;
  11510. begin
  11511. Result:=false;
  11512. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11513. begin
  11514. case taicpu(p).oper[0]^.val of
  11515. 0:
  11516. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11517. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11518. begin
  11519. { change "mov $0,%reg" into "xor %reg,%reg" }
  11520. taicpu(p).opcode := A_XOR;
  11521. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11522. Result := True;
  11523. {$ifdef x86_64}
  11524. end
  11525. else if (taicpu(p).opsize = S_Q) then
  11526. begin
  11527. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11528. { The actual optimization }
  11529. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11530. taicpu(p).changeopsize(S_L);
  11531. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11532. Result := True;
  11533. end;
  11534. $1..$FFFFFFFF:
  11535. begin
  11536. { Code size reduction by J. Gareth "Kit" Moreton }
  11537. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11538. case taicpu(p).opsize of
  11539. S_Q:
  11540. begin
  11541. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11542. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11543. { The actual optimization }
  11544. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11545. taicpu(p).changeopsize(S_L);
  11546. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11547. Result := True;
  11548. end;
  11549. else
  11550. { Do nothing };
  11551. end;
  11552. {$endif x86_64}
  11553. end;
  11554. -1:
  11555. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11556. if (cs_opt_size in current_settings.optimizerswitches) and
  11557. (taicpu(p).opsize <> S_B) and
  11558. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11559. begin
  11560. { change "mov $-1,%reg" into "or $-1,%reg" }
  11561. { NOTES:
  11562. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11563. - This operation creates a false dependency on the register, so only do it when optimising for size
  11564. - 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
  11565. }
  11566. taicpu(p).opcode := A_OR;
  11567. Result := True;
  11568. end;
  11569. else
  11570. { Do nothing };
  11571. end;
  11572. end;
  11573. end;
  11574. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11575. var
  11576. hp1: tai;
  11577. begin
  11578. { Detect:
  11579. andw x, %ax (0 <= x < $8000)
  11580. ...
  11581. movzwl %ax,%eax
  11582. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11583. }
  11584. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11585. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11586. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11587. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11588. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11589. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11590. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11591. begin
  11592. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11593. taicpu(hp1).opcode := A_CWDE;
  11594. taicpu(hp1).clearop(0);
  11595. taicpu(hp1).clearop(1);
  11596. taicpu(hp1).ops := 0;
  11597. { A change was made, but not with p, so move forward 1 }
  11598. p := tai(p.Next);
  11599. Result := True;
  11600. end;
  11601. end;
  11602. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11603. begin
  11604. Result := False;
  11605. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11606. Exit;
  11607. { Convert:
  11608. movswl %ax,%eax -> cwtl
  11609. movslq %eax,%rax -> cdqe
  11610. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11611. refer to the same opcode and depends only on the assembler's
  11612. current operand-size attribute. [Kit]
  11613. }
  11614. with taicpu(p) do
  11615. case opsize of
  11616. S_WL:
  11617. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11618. begin
  11619. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11620. opcode := A_CWDE;
  11621. clearop(0);
  11622. clearop(1);
  11623. ops := 0;
  11624. Result := True;
  11625. end;
  11626. {$ifdef x86_64}
  11627. S_LQ:
  11628. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11629. begin
  11630. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11631. opcode := A_CDQE;
  11632. clearop(0);
  11633. clearop(1);
  11634. ops := 0;
  11635. Result := True;
  11636. end;
  11637. {$endif x86_64}
  11638. else
  11639. ;
  11640. end;
  11641. end;
  11642. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11643. var
  11644. hp1: tai;
  11645. begin
  11646. { Detect:
  11647. shr x, %ax (x > 0)
  11648. ...
  11649. movzwl %ax,%eax
  11650. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11651. }
  11652. Result := False;
  11653. if MatchOpType(taicpu(p), top_const, top_reg) and
  11654. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11655. (taicpu(p).oper[0]^.val > 0) and
  11656. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11657. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11658. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11659. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11660. begin
  11661. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11662. taicpu(hp1).opcode := A_CWDE;
  11663. taicpu(hp1).clearop(0);
  11664. taicpu(hp1).clearop(1);
  11665. taicpu(hp1).ops := 0;
  11666. { A change was made, but not with p, so move forward 1 }
  11667. p := tai(p.Next);
  11668. Result := True;
  11669. end;
  11670. end;
  11671. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11672. var
  11673. hp1, hp2: tai;
  11674. Opposite, SecondOpposite: TAsmOp;
  11675. NewCond: TAsmCond;
  11676. begin
  11677. Result := False;
  11678. { Change:
  11679. add/sub 128,(dest)
  11680. To:
  11681. sub/add -128,(dest)
  11682. This generaally takes fewer bytes to encode because -128 can be stored
  11683. in a signed byte, whereas +128 cannot.
  11684. }
  11685. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11686. begin
  11687. if taicpu(p).opcode = A_ADD then
  11688. Opposite := A_SUB
  11689. else
  11690. Opposite := A_ADD;
  11691. { Be careful if the flags are in use, because the CF flag inverts
  11692. when changing from ADD to SUB and vice versa }
  11693. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11694. GetNextInstruction(p, hp1) then
  11695. begin
  11696. TransferUsedRegs(TmpUsedRegs);
  11697. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11698. hp2 := hp1;
  11699. { Scan ahead to check if everything's safe }
  11700. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11701. begin
  11702. if (hp1.typ <> ait_instruction) then
  11703. { Probably unsafe since the flags are still in use }
  11704. Exit;
  11705. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11706. { Stop searching at an unconditional jump }
  11707. Break;
  11708. if not
  11709. (
  11710. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11711. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11712. ) and
  11713. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11714. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11715. Exit;
  11716. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11717. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11718. { Move to the next instruction }
  11719. GetNextInstruction(hp1, hp1);
  11720. end;
  11721. while Assigned(hp2) and (hp2 <> hp1) do
  11722. begin
  11723. NewCond := C_None;
  11724. case taicpu(hp2).condition of
  11725. C_A, C_NBE:
  11726. NewCond := C_BE;
  11727. C_B, C_C, C_NAE:
  11728. NewCond := C_AE;
  11729. C_AE, C_NB, C_NC:
  11730. NewCond := C_B;
  11731. C_BE, C_NA:
  11732. NewCond := C_A;
  11733. else
  11734. { No change needed };
  11735. end;
  11736. if NewCond <> C_None then
  11737. begin
  11738. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11739. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11740. taicpu(hp2).condition := NewCond;
  11741. end
  11742. else
  11743. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11744. begin
  11745. { Because of the flipping of the carry bit, to ensure
  11746. the operation remains equivalent, ADC becomes SBB
  11747. and vice versa, and the constant is not-inverted.
  11748. If multiple ADCs or SBBs appear in a row, each one
  11749. changed causes the carry bit to invert, so they all
  11750. need to be flipped }
  11751. if taicpu(hp2).opcode = A_ADC then
  11752. SecondOpposite := A_SBB
  11753. else
  11754. SecondOpposite := A_ADC;
  11755. if taicpu(hp2).oper[0]^.typ <> top_const then
  11756. { Should have broken out of this optimisation already }
  11757. InternalError(2021112901);
  11758. 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]^) + ' -> ' +
  11759. 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);
  11760. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11761. taicpu(hp2).opcode := SecondOpposite;
  11762. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11763. end;
  11764. { Move to the next instruction }
  11765. GetNextInstruction(hp2, hp2);
  11766. end;
  11767. if (hp2 <> hp1) then
  11768. InternalError(2021111501);
  11769. end;
  11770. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11771. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11772. taicpu(p).opcode := Opposite;
  11773. taicpu(p).oper[0]^.val := -128;
  11774. { No further optimisations can be made on this instruction, so move
  11775. onto the next one to save time }
  11776. p := tai(p.Next);
  11777. UpdateUsedRegs(p);
  11778. Result := True;
  11779. Exit;
  11780. end;
  11781. { Detect:
  11782. add/sub %reg2,(dest)
  11783. add/sub x, (dest)
  11784. (dest can be a register or a reference)
  11785. Swap the instructions to minimise a pipeline stall. This reverses the
  11786. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11787. optimisations could be made.
  11788. }
  11789. if (taicpu(p).oper[0]^.typ = top_reg) and
  11790. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11791. (
  11792. (
  11793. (taicpu(p).oper[1]^.typ = top_reg) and
  11794. { We can try searching further ahead if we're writing to a register }
  11795. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11796. ) or
  11797. (
  11798. (taicpu(p).oper[1]^.typ = top_ref) and
  11799. GetNextInstruction(p, hp1)
  11800. )
  11801. ) and
  11802. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11803. (taicpu(hp1).oper[0]^.typ = top_const) and
  11804. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11805. begin
  11806. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11807. TransferUsedRegs(TmpUsedRegs);
  11808. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11809. hp2 := p;
  11810. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11811. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11812. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11813. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11814. begin
  11815. asml.remove(hp1);
  11816. asml.InsertBefore(hp1, p);
  11817. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11818. Result := True;
  11819. end;
  11820. end;
  11821. end;
  11822. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11823. begin
  11824. Result:=false;
  11825. { change "cmp $0, %reg" to "test %reg, %reg" }
  11826. if MatchOpType(taicpu(p),top_const,top_reg) and
  11827. (taicpu(p).oper[0]^.val = 0) then
  11828. begin
  11829. taicpu(p).opcode := A_TEST;
  11830. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11831. Result:=true;
  11832. end;
  11833. end;
  11834. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11835. var
  11836. IsTestConstX : Boolean;
  11837. hp1,hp2 : tai;
  11838. begin
  11839. Result:=false;
  11840. { removes the line marked with (x) from the sequence
  11841. and/or/xor/add/sub/... $x, %y
  11842. test/or %y, %y | test $-1, %y (x)
  11843. j(n)z _Label
  11844. as the first instruction already adjusts the ZF
  11845. %y operand may also be a reference }
  11846. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11847. MatchOperand(taicpu(p).oper[0]^,-1);
  11848. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11849. GetLastInstruction(p, hp1) and
  11850. (tai(hp1).typ = ait_instruction) and
  11851. GetNextInstruction(p,hp2) and
  11852. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11853. case taicpu(hp1).opcode Of
  11854. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11855. { These two instructions set the zero flag if the result is zero }
  11856. A_POPCNT, A_LZCNT:
  11857. begin
  11858. if (
  11859. { With POPCNT, an input of zero will set the zero flag
  11860. because the population count of zero is zero }
  11861. (taicpu(hp1).opcode = A_POPCNT) and
  11862. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11863. (
  11864. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11865. { Faster than going through the second half of the 'or'
  11866. condition below }
  11867. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11868. )
  11869. ) or (
  11870. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11871. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11872. { and in case of carry for A(E)/B(E)/C/NC }
  11873. (
  11874. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11875. (
  11876. (taicpu(hp1).opcode <> A_ADD) and
  11877. (taicpu(hp1).opcode <> A_SUB) and
  11878. (taicpu(hp1).opcode <> A_LZCNT)
  11879. )
  11880. )
  11881. ) then
  11882. begin
  11883. RemoveCurrentP(p, hp2);
  11884. Result:=true;
  11885. Exit;
  11886. end;
  11887. end;
  11888. A_SHL, A_SAL, A_SHR, A_SAR:
  11889. begin
  11890. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11891. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11892. { therefore, it's only safe to do this optimization for }
  11893. { shifts by a (nonzero) constant }
  11894. (taicpu(hp1).oper[0]^.typ = top_const) and
  11895. (taicpu(hp1).oper[0]^.val <> 0) and
  11896. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11897. { and in case of carry for A(E)/B(E)/C/NC }
  11898. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11899. begin
  11900. RemoveCurrentP(p, hp2);
  11901. Result:=true;
  11902. Exit;
  11903. end;
  11904. end;
  11905. A_DEC, A_INC, A_NEG:
  11906. begin
  11907. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11908. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11909. { and in case of carry for A(E)/B(E)/C/NC }
  11910. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11911. begin
  11912. RemoveCurrentP(p, hp2);
  11913. Result:=true;
  11914. Exit;
  11915. end;
  11916. end
  11917. else
  11918. ;
  11919. end; { case }
  11920. { change "test $-1,%reg" into "test %reg,%reg" }
  11921. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11922. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11923. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11924. if MatchInstruction(p, A_OR, []) and
  11925. { Can only match if they're both registers }
  11926. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11927. begin
  11928. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11929. taicpu(p).opcode := A_TEST;
  11930. { No need to set Result to True, as we've done all the optimisations we can }
  11931. end;
  11932. end;
  11933. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11934. var
  11935. hp1,hp3 : tai;
  11936. {$ifndef x86_64}
  11937. hp2 : taicpu;
  11938. {$endif x86_64}
  11939. begin
  11940. Result:=false;
  11941. hp3:=nil;
  11942. {$ifndef x86_64}
  11943. { don't do this on modern CPUs, this really hurts them due to
  11944. broken call/ret pairing }
  11945. if (current_settings.optimizecputype < cpu_Pentium2) and
  11946. not(cs_create_pic in current_settings.moduleswitches) and
  11947. GetNextInstruction(p, hp1) and
  11948. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11949. MatchOpType(taicpu(hp1),top_ref) and
  11950. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11951. begin
  11952. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11953. InsertLLItem(p.previous, p, hp2);
  11954. taicpu(p).opcode := A_JMP;
  11955. taicpu(p).is_jmp := true;
  11956. RemoveInstruction(hp1);
  11957. Result:=true;
  11958. end
  11959. else
  11960. {$endif x86_64}
  11961. { replace
  11962. call procname
  11963. ret
  11964. by
  11965. jmp procname
  11966. but do it only on level 4 because it destroys stack back traces
  11967. else if the subroutine is marked as no return, remove the ret
  11968. }
  11969. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11970. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11971. GetNextInstruction(p, hp1) and
  11972. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11973. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11974. SetAndTest(hp1,hp3) and
  11975. GetNextInstruction(hp1,hp1) and
  11976. MatchInstruction(hp1,A_RET,[S_NO])
  11977. )
  11978. ) and
  11979. (taicpu(hp1).ops=0) then
  11980. begin
  11981. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11982. { we might destroy stack alignment here if we do not do a call }
  11983. (target_info.stackalign<=sizeof(SizeUInt)) then
  11984. begin
  11985. taicpu(p).opcode := A_JMP;
  11986. taicpu(p).is_jmp := true;
  11987. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11988. end
  11989. else
  11990. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11991. RemoveInstruction(hp1);
  11992. if Assigned(hp3) then
  11993. begin
  11994. AsmL.Remove(hp3);
  11995. AsmL.InsertBefore(hp3,p)
  11996. end;
  11997. Result:=true;
  11998. end;
  11999. end;
  12000. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  12001. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  12002. begin
  12003. case OpSize of
  12004. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12005. Result := (Val <= $FF) and (Val >= -128);
  12006. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12007. Result := (Val <= $FFFF) and (Val >= -32768);
  12008. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  12009. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  12010. else
  12011. Result := True;
  12012. end;
  12013. end;
  12014. var
  12015. hp1, hp2 : tai;
  12016. SizeChange: Boolean;
  12017. PreMessage: string;
  12018. begin
  12019. Result := False;
  12020. if (taicpu(p).oper[0]^.typ = top_reg) and
  12021. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12022. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  12023. begin
  12024. { Change (using movzbl %al,%eax as an example):
  12025. movzbl %al, %eax movzbl %al, %eax
  12026. cmpl x, %eax testl %eax,%eax
  12027. To:
  12028. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  12029. movzbl %al, %eax movzbl %al, %eax
  12030. Smaller instruction and minimises pipeline stall as the CPU
  12031. doesn't have to wait for the register to get zero-extended. [Kit]
  12032. Also allow if the smaller of the two registers is being checked,
  12033. as this still removes the false dependency.
  12034. }
  12035. if
  12036. (
  12037. (
  12038. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  12039. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  12040. ) or (
  12041. { If MatchOperand returns True, they must both be registers }
  12042. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  12043. )
  12044. ) and
  12045. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  12046. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  12047. begin
  12048. 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);
  12049. asml.Remove(hp1);
  12050. asml.InsertBefore(hp1, p);
  12051. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  12052. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  12053. begin
  12054. taicpu(hp1).opcode := A_TEST;
  12055. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  12056. end;
  12057. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12058. case taicpu(p).opsize of
  12059. S_BW, S_BL:
  12060. begin
  12061. SizeChange := taicpu(hp1).opsize <> S_B;
  12062. taicpu(hp1).changeopsize(S_B);
  12063. end;
  12064. S_WL:
  12065. begin
  12066. SizeChange := taicpu(hp1).opsize <> S_W;
  12067. taicpu(hp1).changeopsize(S_W);
  12068. end
  12069. else
  12070. InternalError(2020112701);
  12071. end;
  12072. UpdateUsedRegs(tai(p.Next));
  12073. { Check if the register is used aferwards - if not, we can
  12074. remove the movzx instruction completely }
  12075. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  12076. begin
  12077. { Hp1 is a better position than p for debugging purposes }
  12078. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  12079. RemoveCurrentp(p, hp1);
  12080. Result := True;
  12081. end;
  12082. if SizeChange then
  12083. DebugMsg(SPeepholeOptimization + PreMessage +
  12084. 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)
  12085. else
  12086. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  12087. Exit;
  12088. end;
  12089. { Change (using movzwl %ax,%eax as an example):
  12090. movzwl %ax, %eax
  12091. movb %al, (dest) (Register is smaller than read register in movz)
  12092. To:
  12093. movb %al, (dest) (Move one back to avoid a false dependency)
  12094. movzwl %ax, %eax
  12095. }
  12096. if (taicpu(hp1).opcode = A_MOV) and
  12097. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12098. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  12099. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  12100. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  12101. begin
  12102. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  12103. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  12104. asml.Remove(hp1);
  12105. asml.InsertBefore(hp1, p);
  12106. if taicpu(hp1).oper[1]^.typ = top_reg then
  12107. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12108. { Check if the register is used aferwards - if not, we can
  12109. remove the movzx instruction completely }
  12110. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  12111. begin
  12112. { Hp1 is a better position than p for debugging purposes }
  12113. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  12114. RemoveCurrentp(p, hp1);
  12115. Result := True;
  12116. end;
  12117. Exit;
  12118. end;
  12119. end;
  12120. end;
  12121. {$ifdef x86_64}
  12122. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  12123. var
  12124. PreMessage, RegName: string;
  12125. begin
  12126. { Code size reduction by J. Gareth "Kit" Moreton }
  12127. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  12128. as this removes the REX prefix }
  12129. Result := False;
  12130. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  12131. Exit;
  12132. if taicpu(p).oper[0]^.typ <> top_reg then
  12133. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  12134. InternalError(2018011500);
  12135. case taicpu(p).opsize of
  12136. S_Q:
  12137. begin
  12138. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  12139. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  12140. { The actual optimization }
  12141. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12142. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12143. taicpu(p).changeopsize(S_L);
  12144. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  12145. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  12146. end;
  12147. else
  12148. ;
  12149. end;
  12150. end;
  12151. {$endif}
  12152. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  12153. var
  12154. XReg: TRegister;
  12155. begin
  12156. Result := False;
  12157. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  12158. Smaller encoding and slightly faster on some platforms (also works for
  12159. ZMM-sized registers) }
  12160. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  12161. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  12162. begin
  12163. XReg := taicpu(p).oper[0]^.reg;
  12164. if (taicpu(p).oper[1]^.reg = XReg) then
  12165. begin
  12166. taicpu(p).changeopsize(S_XMM);
  12167. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  12168. if (cs_opt_size in current_settings.optimizerswitches) then
  12169. begin
  12170. { Change input registers to %xmm0 to reduce size. Note that
  12171. there's a risk of a false dependency doing this, so only
  12172. optimise for size here }
  12173. XReg := NR_XMM0;
  12174. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  12175. end
  12176. else
  12177. begin
  12178. setsubreg(XReg, R_SUBMMX);
  12179. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  12180. end;
  12181. taicpu(p).oper[0]^.reg := XReg;
  12182. taicpu(p).oper[1]^.reg := XReg;
  12183. Result := True;
  12184. end;
  12185. end;
  12186. end;
  12187. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  12188. var
  12189. OperIdx: Integer;
  12190. begin
  12191. for OperIdx := 0 to p.ops - 1 do
  12192. if p.oper[OperIdx]^.typ = top_ref then
  12193. optimize_ref(p.oper[OperIdx]^.ref^, False);
  12194. end;
  12195. end.