aoptx86.pas 564 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180
  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,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3
  33. );
  34. TX86AsmOptimizer = class(TAsmOptimizer)
  35. { some optimizations are very expensive to check, so the
  36. pre opt pass can be used to set some flags, depending on the found
  37. instructions if it is worth to check a certain optimization }
  38. OptsToCheck : set of TOptsToCheck;
  39. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  40. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  41. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  42. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  43. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  44. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  45. potentially allowing further optimisation (although it might need to know if
  46. it crossed a conditional jump. }
  47. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  48. {
  49. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  50. the use of a register by allocs/dealloc, so it can ignore calls.
  51. In the following example, GetNextInstructionUsingReg will return the second movq,
  52. GetNextInstructionUsingRegTrackingUse won't.
  53. movq %rdi,%rax
  54. # Register rdi released
  55. # Register rdi allocated
  56. movq %rax,%rdi
  57. While in this example:
  58. movq %rdi,%rax
  59. call proc
  60. movq %rdi,%rax
  61. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  62. won't.
  63. }
  64. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  65. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  66. private
  67. function SkipSimpleInstructions(var hp1: tai): Boolean;
  68. protected
  69. class function IsMOVZXAcceptable: Boolean; static; inline;
  70. { Attempts to allocate a volatile integer register for use between p and hp,
  71. using AUsedRegs for the current register usage information. Returns NR_NO
  72. if no free register could be found }
  73. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  74. { Attempts to allocate a volatile MM register for use between p and hp,
  75. using AUsedRegs for the current register usage information. Returns NR_NO
  76. if no free register could be found }
  77. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  78. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  79. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  80. { checks whether reading the value in reg1 depends on the value of reg2. This
  81. is very similar to SuperRegisterEquals, except it takes into account that
  82. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  83. depend on the value in AH). }
  84. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  85. { Replaces all references to AOldReg in a memory reference to ANewReg }
  86. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  87. { Replaces all references to AOldReg in an operand to ANewReg }
  88. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  89. { Replaces all references to AOldReg in an instruction to ANewReg,
  90. except where the register is being written }
  91. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  93. or writes to a global symbol }
  94. class function IsRefSafe(const ref: PReference): Boolean; static;
  95. { Returns true if the given MOV instruction can be safely converted to CMOV }
  96. class function CanBeCMOV(p : tai) : boolean; static;
  97. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  98. conversion was successful }
  99. function ConvertLEA(const p : taicpu): Boolean;
  100. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  101. procedure DebugMsg(const s : string; p : tai);inline;
  102. class function IsExitCode(p : tai) : boolean; static;
  103. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  104. procedure RemoveLastDeallocForFuncRes(p : tai);
  105. function DoSubAddOpt(var p : tai) : Boolean;
  106. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  107. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  108. function PrePeepholeOptSxx(var p : tai) : boolean;
  109. function PrePeepholeOptIMUL(var p : tai) : boolean;
  110. function PrePeepholeOptAND(var p : tai) : boolean;
  111. function OptPass1Test(var p: tai): boolean;
  112. function OptPass1Add(var p: tai): boolean;
  113. function OptPass1AND(var p : tai) : boolean;
  114. function OptPass1_V_MOVAP(var p : tai) : boolean;
  115. function OptPass1VOP(var p : tai) : boolean;
  116. function OptPass1MOV(var p : tai) : boolean;
  117. function OptPass1Movx(var p : tai) : boolean;
  118. function OptPass1MOVXX(var p : tai) : boolean;
  119. function OptPass1OP(var p : tai) : boolean;
  120. function OptPass1LEA(var p : tai) : boolean;
  121. function OptPass1Sub(var p : tai) : boolean;
  122. function OptPass1SHLSAL(var p : tai) : boolean;
  123. function OptPass1FSTP(var p : tai) : boolean;
  124. function OptPass1FLD(var p : tai) : boolean;
  125. function OptPass1Cmp(var p : tai) : boolean;
  126. function OptPass1PXor(var p : tai) : boolean;
  127. function OptPass1VPXor(var p: tai): boolean;
  128. function OptPass1Imul(var p : tai) : boolean;
  129. function OptPass1Jcc(var p : tai) : boolean;
  130. function OptPass1SHXX(var p: tai): boolean;
  131. function OptPass1VMOVDQ(var p: tai): Boolean;
  132. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  133. function OptPass2Movx(var p : tai): Boolean;
  134. function OptPass2MOV(var p : tai) : boolean;
  135. function OptPass2Imul(var p : tai) : boolean;
  136. function OptPass2Jmp(var p : tai) : boolean;
  137. function OptPass2Jcc(var p : tai) : boolean;
  138. function OptPass2Lea(var p: tai): Boolean;
  139. function OptPass2SUB(var p: tai): Boolean;
  140. function OptPass2ADD(var p : tai): Boolean;
  141. function OptPass2SETcc(var p : tai) : boolean;
  142. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  143. function PostPeepholeOptMov(var p : tai) : Boolean;
  144. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  145. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  146. function PostPeepholeOptXor(var p : tai) : Boolean;
  147. {$endif x86_64}
  148. function PostPeepholeOptAnd(var p : tai) : boolean;
  149. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  150. function PostPeepholeOptCmp(var p : tai) : Boolean;
  151. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  152. function PostPeepholeOptCall(var p : tai) : Boolean;
  153. function PostPeepholeOptLea(var p : tai) : Boolean;
  154. function PostPeepholeOptPush(var p: tai): Boolean;
  155. function PostPeepholeOptShr(var p : tai) : boolean;
  156. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  157. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  158. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  159. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  160. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  161. { Processor-dependent reference optimisation }
  162. class procedure OptimizeRefs(var p: taicpu); static;
  163. end;
  164. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  165. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  168. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  169. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  170. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  171. {$if max_operands>2}
  172. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  173. {$endif max_operands>2}
  174. function RefsEqual(const r1, r2: treference): boolean;
  175. { Note that Result is set to True if the references COULD overlap but the
  176. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  177. might still overlap because %reg2 could be equal to %reg1-4 }
  178. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  179. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  180. { returns true, if ref is a reference using only the registers passed as base and index
  181. and having an offset }
  182. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  183. implementation
  184. uses
  185. cutils,verbose,
  186. systems,
  187. globals,
  188. cpuinfo,
  189. procinfo,
  190. paramgr,
  191. aasmbase,
  192. aoptbase,aoptutils,
  193. symconst,symsym,
  194. cgx86,
  195. itcpugas;
  196. {$ifdef DEBUG_AOPTCPU}
  197. const
  198. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  199. {$else DEBUG_AOPTCPU}
  200. { Empty strings help the optimizer to remove string concatenations that won't
  201. ever appear to the user on release builds. [Kit] }
  202. const
  203. SPeepholeOptimization = '';
  204. {$endif DEBUG_AOPTCPU}
  205. LIST_STEP_SIZE = 4;
  206. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  207. begin
  208. result :=
  209. (instr.typ = ait_instruction) and
  210. (taicpu(instr).opcode = op) and
  211. ((opsize = []) or (taicpu(instr).opsize in opsize));
  212. end;
  213. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  214. begin
  215. result :=
  216. (instr.typ = ait_instruction) and
  217. ((taicpu(instr).opcode = op1) or
  218. (taicpu(instr).opcode = op2)
  219. ) and
  220. ((opsize = []) or (taicpu(instr).opsize in opsize));
  221. end;
  222. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  223. begin
  224. result :=
  225. (instr.typ = ait_instruction) and
  226. ((taicpu(instr).opcode = op1) or
  227. (taicpu(instr).opcode = op2) or
  228. (taicpu(instr).opcode = op3)
  229. ) and
  230. ((opsize = []) or (taicpu(instr).opsize in opsize));
  231. end;
  232. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  233. const opsize : topsizes) : boolean;
  234. var
  235. op : TAsmOp;
  236. begin
  237. result:=false;
  238. if (instr.typ <> ait_instruction) or
  239. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  240. exit;
  241. for op in ops do
  242. begin
  243. if taicpu(instr).opcode = op then
  244. begin
  245. result:=true;
  246. exit;
  247. end;
  248. end;
  249. end;
  250. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  251. begin
  252. result := (oper.typ = top_reg) and (oper.reg = reg);
  253. end;
  254. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  255. begin
  256. result := (oper.typ = top_const) and (oper.val = a);
  257. end;
  258. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  259. begin
  260. result := oper1.typ = oper2.typ;
  261. if result then
  262. case oper1.typ of
  263. top_const:
  264. Result:=oper1.val = oper2.val;
  265. top_reg:
  266. Result:=oper1.reg = oper2.reg;
  267. top_ref:
  268. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  269. else
  270. internalerror(2013102801);
  271. end
  272. end;
  273. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  274. begin
  275. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  276. if result then
  277. case oper1.typ of
  278. top_const:
  279. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  280. top_reg:
  281. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  282. top_ref:
  283. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  284. else
  285. internalerror(2020052401);
  286. end
  287. end;
  288. function RefsEqual(const r1, r2: treference): boolean;
  289. begin
  290. RefsEqual :=
  291. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  292. (r1.relsymbol = r2.relsymbol) and
  293. (r1.segment = r2.segment) and (r1.base = r2.base) and
  294. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  295. (r1.offset = r2.offset) and
  296. (r1.volatility + r2.volatility = []);
  297. end;
  298. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  299. begin
  300. if (r1.symbol<>r2.symbol) then
  301. { If the index registers are different, there's a chance one could
  302. be set so it equals the other symbol }
  303. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  304. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  305. (r1.relsymbol = r2.relsymbol) and
  306. (r1.segment = r2.segment) and (r1.base = r2.base) and
  307. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  308. (r1.volatility + r2.volatility = []) then
  309. { In this case, it all depends on the offsets }
  310. Exit(abs(r1.offset - r2.offset) < Range);
  311. { There's a chance things MIGHT overlap, so take no chances }
  312. Result := True;
  313. end;
  314. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  315. begin
  316. Result:=(ref.offset=0) and
  317. (ref.scalefactor in [0,1]) and
  318. (ref.segment=NR_NO) and
  319. (ref.symbol=nil) and
  320. (ref.relsymbol=nil) and
  321. ((base=NR_INVALID) or
  322. (ref.base=base)) and
  323. ((index=NR_INVALID) or
  324. (ref.index=index)) and
  325. (ref.volatility=[]);
  326. end;
  327. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  328. begin
  329. Result:=(ref.scalefactor in [0,1]) and
  330. (ref.segment=NR_NO) and
  331. (ref.symbol=nil) and
  332. (ref.relsymbol=nil) and
  333. ((base=NR_INVALID) or
  334. (ref.base=base)) and
  335. ((index=NR_INVALID) or
  336. (ref.index=index)) and
  337. (ref.volatility=[]);
  338. end;
  339. function InstrReadsFlags(p: tai): boolean;
  340. begin
  341. InstrReadsFlags := true;
  342. case p.typ of
  343. ait_instruction:
  344. if InsProp[taicpu(p).opcode].Ch*
  345. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  346. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  347. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  348. exit;
  349. ait_label:
  350. exit;
  351. else
  352. ;
  353. end;
  354. InstrReadsFlags := false;
  355. end;
  356. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  357. begin
  358. Next:=Current;
  359. repeat
  360. Result:=GetNextInstruction(Next,Next);
  361. until not (Result) or
  362. not(cs_opt_level3 in current_settings.optimizerswitches) or
  363. (Next.typ<>ait_instruction) or
  364. RegInInstruction(reg,Next) or
  365. is_calljmp(taicpu(Next).opcode);
  366. end;
  367. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  368. begin
  369. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  370. Next := Current;
  371. repeat
  372. Result := GetNextInstruction(Next,Next);
  373. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  374. if is_calljmpuncondret(taicpu(Next).opcode) then
  375. begin
  376. Result := False;
  377. Exit;
  378. end
  379. else
  380. CrossJump := True;
  381. until not Result or
  382. not (cs_opt_level3 in current_settings.optimizerswitches) or
  383. (Next.typ <> ait_instruction) or
  384. RegInInstruction(reg,Next);
  385. end;
  386. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  387. begin
  388. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  389. begin
  390. Result:=GetNextInstruction(Current,Next);
  391. exit;
  392. end;
  393. Next:=tai(Current.Next);
  394. Result:=false;
  395. while assigned(Next) do
  396. begin
  397. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  398. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  399. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  400. exit
  401. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  402. begin
  403. Result:=true;
  404. exit;
  405. end;
  406. Next:=tai(Next.Next);
  407. end;
  408. end;
  409. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  410. begin
  411. Result:=RegReadByInstruction(reg,hp);
  412. end;
  413. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  414. var
  415. p: taicpu;
  416. opcount: longint;
  417. begin
  418. RegReadByInstruction := false;
  419. if hp.typ <> ait_instruction then
  420. exit;
  421. p := taicpu(hp);
  422. case p.opcode of
  423. A_CALL:
  424. regreadbyinstruction := true;
  425. A_IMUL:
  426. case p.ops of
  427. 1:
  428. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  429. (
  430. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  431. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  432. );
  433. 2,3:
  434. regReadByInstruction :=
  435. reginop(reg,p.oper[0]^) or
  436. reginop(reg,p.oper[1]^);
  437. else
  438. InternalError(2019112801);
  439. end;
  440. A_MUL:
  441. begin
  442. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  443. (
  444. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  445. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  446. );
  447. end;
  448. A_IDIV,A_DIV:
  449. begin
  450. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  451. (
  452. (getregtype(reg)=R_INTREGISTER) and
  453. (
  454. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  455. )
  456. );
  457. end;
  458. else
  459. begin
  460. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  461. begin
  462. RegReadByInstruction := false;
  463. exit;
  464. end;
  465. for opcount := 0 to p.ops-1 do
  466. if (p.oper[opCount]^.typ = top_ref) and
  467. RegInRef(reg,p.oper[opcount]^.ref^) then
  468. begin
  469. RegReadByInstruction := true;
  470. exit
  471. end;
  472. { special handling for SSE MOVSD }
  473. if (p.opcode=A_MOVSD) and (p.ops>0) then
  474. begin
  475. if p.ops<>2 then
  476. internalerror(2017042702);
  477. regReadByInstruction := reginop(reg,p.oper[0]^) or
  478. (
  479. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  480. );
  481. exit;
  482. end;
  483. with insprop[p.opcode] do
  484. begin
  485. case getregtype(reg) of
  486. R_INTREGISTER:
  487. begin
  488. case getsupreg(reg) of
  489. RS_EAX:
  490. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  491. begin
  492. RegReadByInstruction := true;
  493. exit
  494. end;
  495. RS_ECX:
  496. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  497. begin
  498. RegReadByInstruction := true;
  499. exit
  500. end;
  501. RS_EDX:
  502. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  503. begin
  504. RegReadByInstruction := true;
  505. exit
  506. end;
  507. RS_EBX:
  508. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  509. begin
  510. RegReadByInstruction := true;
  511. exit
  512. end;
  513. RS_ESP:
  514. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  515. begin
  516. RegReadByInstruction := true;
  517. exit
  518. end;
  519. RS_EBP:
  520. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  521. begin
  522. RegReadByInstruction := true;
  523. exit
  524. end;
  525. RS_ESI:
  526. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  527. begin
  528. RegReadByInstruction := true;
  529. exit
  530. end;
  531. RS_EDI:
  532. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  533. begin
  534. RegReadByInstruction := true;
  535. exit
  536. end;
  537. end;
  538. end;
  539. R_MMREGISTER:
  540. begin
  541. case getsupreg(reg) of
  542. RS_XMM0:
  543. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  544. begin
  545. RegReadByInstruction := true;
  546. exit
  547. end;
  548. end;
  549. end;
  550. else
  551. ;
  552. end;
  553. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  554. begin
  555. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  556. begin
  557. case p.condition of
  558. C_A,C_NBE, { CF=0 and ZF=0 }
  559. C_BE,C_NA: { CF=1 or ZF=1 }
  560. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  561. C_AE,C_NB,C_NC, { CF=0 }
  562. C_B,C_NAE,C_C: { CF=1 }
  563. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  564. C_NE,C_NZ, { ZF=0 }
  565. C_E,C_Z: { ZF=1 }
  566. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  567. C_G,C_NLE, { ZF=0 and SF=OF }
  568. C_LE,C_NG: { ZF=1 or SF<>OF }
  569. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  570. C_GE,C_NL, { SF=OF }
  571. C_L,C_NGE: { SF<>OF }
  572. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  573. C_NO, { OF=0 }
  574. C_O: { OF=1 }
  575. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  576. C_NP,C_PO, { PF=0 }
  577. C_P,C_PE: { PF=1 }
  578. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  579. C_NS, { SF=0 }
  580. C_S: { SF=1 }
  581. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  582. else
  583. internalerror(2017042701);
  584. end;
  585. if RegReadByInstruction then
  586. exit;
  587. end;
  588. case getsubreg(reg) of
  589. R_SUBW,R_SUBD,R_SUBQ:
  590. RegReadByInstruction :=
  591. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  592. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  593. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  594. R_SUBFLAGCARRY:
  595. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  596. R_SUBFLAGPARITY:
  597. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  598. R_SUBFLAGAUXILIARY:
  599. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  600. R_SUBFLAGZERO:
  601. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  602. R_SUBFLAGSIGN:
  603. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  604. R_SUBFLAGOVERFLOW:
  605. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  606. R_SUBFLAGINTERRUPT:
  607. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  608. R_SUBFLAGDIRECTION:
  609. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  610. else
  611. internalerror(2017042601);
  612. end;
  613. exit;
  614. end;
  615. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  616. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  617. (p.oper[0]^.reg=p.oper[1]^.reg) then
  618. exit;
  619. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  620. begin
  621. RegReadByInstruction := true;
  622. exit
  623. end;
  624. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  625. begin
  626. RegReadByInstruction := true;
  627. exit
  628. end;
  629. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  630. begin
  631. RegReadByInstruction := true;
  632. exit
  633. end;
  634. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  635. begin
  636. RegReadByInstruction := true;
  637. exit
  638. end;
  639. end;
  640. end;
  641. end;
  642. end;
  643. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  644. begin
  645. result:=false;
  646. if p1.typ<>ait_instruction then
  647. exit;
  648. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  649. exit(true);
  650. if (getregtype(reg)=R_INTREGISTER) and
  651. { change information for xmm movsd are not correct }
  652. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  653. begin
  654. case getsupreg(reg) of
  655. { RS_EAX = RS_RAX on x86-64 }
  656. RS_EAX:
  657. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  658. RS_ECX:
  659. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  660. RS_EDX:
  661. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  662. RS_EBX:
  663. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  664. RS_ESP:
  665. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  666. RS_EBP:
  667. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  668. RS_ESI:
  669. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  670. RS_EDI:
  671. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  672. else
  673. ;
  674. end;
  675. if result then
  676. exit;
  677. end
  678. else if getregtype(reg)=R_MMREGISTER then
  679. begin
  680. case getsupreg(reg) of
  681. RS_XMM0:
  682. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  683. else
  684. ;
  685. end;
  686. if result then
  687. exit;
  688. end
  689. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  690. begin
  691. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  692. exit(true);
  693. case getsubreg(reg) of
  694. R_SUBFLAGCARRY:
  695. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  696. R_SUBFLAGPARITY:
  697. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  698. R_SUBFLAGAUXILIARY:
  699. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  700. R_SUBFLAGZERO:
  701. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  702. R_SUBFLAGSIGN:
  703. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  704. R_SUBFLAGOVERFLOW:
  705. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  706. R_SUBFLAGINTERRUPT:
  707. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  708. R_SUBFLAGDIRECTION:
  709. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  710. R_SUBW,R_SUBD,R_SUBQ:
  711. { Everything except the direction bits }
  712. Result:=
  713. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  714. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  715. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  716. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  717. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  718. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  719. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  720. else
  721. ;
  722. end;
  723. if result then
  724. exit;
  725. end
  726. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  727. exit(true);
  728. Result:=inherited RegInInstruction(Reg, p1);
  729. end;
  730. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  731. const
  732. WriteOps: array[0..3] of set of TInsChange =
  733. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  734. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  735. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  736. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  737. var
  738. OperIdx: Integer;
  739. begin
  740. Result := False;
  741. if p1.typ <> ait_instruction then
  742. exit;
  743. with insprop[taicpu(p1).opcode] do
  744. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  745. begin
  746. case getsubreg(reg) of
  747. R_SUBW,R_SUBD,R_SUBQ:
  748. Result :=
  749. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  750. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  751. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  752. R_SUBFLAGCARRY:
  753. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  754. R_SUBFLAGPARITY:
  755. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  756. R_SUBFLAGAUXILIARY:
  757. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  758. R_SUBFLAGZERO:
  759. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  760. R_SUBFLAGSIGN:
  761. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  762. R_SUBFLAGOVERFLOW:
  763. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  764. R_SUBFLAGINTERRUPT:
  765. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  766. R_SUBFLAGDIRECTION:
  767. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  768. else
  769. internalerror(2017042602);
  770. end;
  771. exit;
  772. end;
  773. case taicpu(p1).opcode of
  774. A_CALL:
  775. { We could potentially set Result to False if the register in
  776. question is non-volatile for the subroutine's calling convention,
  777. but this would require detecting the calling convention in use and
  778. also assuming that the routine doesn't contain malformed assembly
  779. language, for example... so it could only be done under -O4 as it
  780. would be considered a side-effect. [Kit] }
  781. Result := True;
  782. A_MOVSD:
  783. { special handling for SSE MOVSD }
  784. if (taicpu(p1).ops>0) then
  785. begin
  786. if taicpu(p1).ops<>2 then
  787. internalerror(2017042703);
  788. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  789. end;
  790. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  791. so fix it here (FK)
  792. }
  793. A_VMOVSS,
  794. A_VMOVSD:
  795. begin
  796. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  797. exit;
  798. end;
  799. A_IMUL:
  800. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  801. else
  802. ;
  803. end;
  804. if Result then
  805. exit;
  806. with insprop[taicpu(p1).opcode] do
  807. begin
  808. if getregtype(reg)=R_INTREGISTER then
  809. begin
  810. case getsupreg(reg) of
  811. RS_EAX:
  812. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  813. begin
  814. Result := True;
  815. exit
  816. end;
  817. RS_ECX:
  818. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  819. begin
  820. Result := True;
  821. exit
  822. end;
  823. RS_EDX:
  824. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  825. begin
  826. Result := True;
  827. exit
  828. end;
  829. RS_EBX:
  830. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  831. begin
  832. Result := True;
  833. exit
  834. end;
  835. RS_ESP:
  836. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  837. begin
  838. Result := True;
  839. exit
  840. end;
  841. RS_EBP:
  842. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  843. begin
  844. Result := True;
  845. exit
  846. end;
  847. RS_ESI:
  848. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  849. begin
  850. Result := True;
  851. exit
  852. end;
  853. RS_EDI:
  854. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  855. begin
  856. Result := True;
  857. exit
  858. end;
  859. end;
  860. end;
  861. for OperIdx := 0 to taicpu(p1).ops - 1 do
  862. if (WriteOps[OperIdx]*Ch<>[]) and
  863. { The register doesn't get modified inside a reference }
  864. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  865. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  866. begin
  867. Result := true;
  868. exit
  869. end;
  870. end;
  871. end;
  872. {$ifdef DEBUG_AOPTCPU}
  873. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  874. begin
  875. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  876. end;
  877. function debug_tostr(i: tcgint): string; inline;
  878. begin
  879. Result := tostr(i);
  880. end;
  881. function debug_regname(r: TRegister): string; inline;
  882. begin
  883. Result := '%' + std_regname(r);
  884. end;
  885. { Debug output function - creates a string representation of an operator }
  886. function debug_operstr(oper: TOper): string;
  887. begin
  888. case oper.typ of
  889. top_const:
  890. Result := '$' + debug_tostr(oper.val);
  891. top_reg:
  892. Result := debug_regname(oper.reg);
  893. top_ref:
  894. begin
  895. if oper.ref^.offset <> 0 then
  896. Result := debug_tostr(oper.ref^.offset) + '('
  897. else
  898. Result := '(';
  899. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  900. begin
  901. Result := Result + debug_regname(oper.ref^.base);
  902. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  903. Result := Result + ',' + debug_regname(oper.ref^.index);
  904. end
  905. else
  906. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  907. Result := Result + debug_regname(oper.ref^.index);
  908. if (oper.ref^.scalefactor > 1) then
  909. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  910. else
  911. Result := Result + ')';
  912. end;
  913. else
  914. Result := '[UNKNOWN]';
  915. end;
  916. end;
  917. function debug_op2str(opcode: tasmop): string; inline;
  918. begin
  919. Result := std_op2str[opcode];
  920. end;
  921. function debug_opsize2str(opsize: topsize): string; inline;
  922. begin
  923. Result := gas_opsize2str[opsize];
  924. end;
  925. {$else DEBUG_AOPTCPU}
  926. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  927. begin
  928. end;
  929. function debug_tostr(i: tcgint): string; inline;
  930. begin
  931. Result := '';
  932. end;
  933. function debug_regname(r: TRegister): string; inline;
  934. begin
  935. Result := '';
  936. end;
  937. function debug_operstr(oper: TOper): string; inline;
  938. begin
  939. Result := '';
  940. end;
  941. function debug_op2str(opcode: tasmop): string; inline;
  942. begin
  943. Result := '';
  944. end;
  945. function debug_opsize2str(opsize: topsize): string; inline;
  946. begin
  947. Result := '';
  948. end;
  949. {$endif DEBUG_AOPTCPU}
  950. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  951. begin
  952. {$ifdef x86_64}
  953. { Always fine on x86-64 }
  954. Result := True;
  955. {$else x86_64}
  956. Result :=
  957. {$ifdef i8086}
  958. (current_settings.cputype >= cpu_386) and
  959. {$endif i8086}
  960. (
  961. { Always accept if optimising for size }
  962. (cs_opt_size in current_settings.optimizerswitches) or
  963. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  964. (current_settings.optimizecputype >= cpu_Pentium2)
  965. );
  966. {$endif x86_64}
  967. end;
  968. { Attempts to allocate a volatile integer register for use between p and hp,
  969. using AUsedRegs for the current register usage information. Returns NR_NO
  970. if no free register could be found }
  971. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  972. var
  973. RegSet: TCPURegisterSet;
  974. CurrentSuperReg: Integer;
  975. CurrentReg: TRegister;
  976. Currentp: tai;
  977. Breakout: Boolean;
  978. begin
  979. Result := NR_NO;
  980. RegSet :=
  981. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  982. current_procinfo.saved_regs_int;
  983. for CurrentSuperReg in RegSet do
  984. begin
  985. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  986. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  987. {$if defined(i386) or defined(i8086)}
  988. { If the target size is 8-bit, make sure we can actually encode it }
  989. and (
  990. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  991. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  992. )
  993. {$endif i386 or i8086}
  994. then
  995. begin
  996. Currentp := p;
  997. Breakout := False;
  998. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  999. begin
  1000. case Currentp.typ of
  1001. ait_instruction:
  1002. begin
  1003. if RegInInstruction(CurrentReg, Currentp) then
  1004. begin
  1005. Breakout := True;
  1006. Break;
  1007. end;
  1008. { Cannot allocate across an unconditional jump }
  1009. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1010. Exit;
  1011. end;
  1012. ait_marker:
  1013. { Don't try anything more if a marker is hit }
  1014. Exit;
  1015. ait_regalloc:
  1016. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1017. begin
  1018. Breakout := True;
  1019. Break;
  1020. end;
  1021. else
  1022. ;
  1023. end;
  1024. end;
  1025. if Breakout then
  1026. { Try the next register }
  1027. Continue;
  1028. { We have a free register available }
  1029. Result := CurrentReg;
  1030. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1031. Exit;
  1032. end;
  1033. end;
  1034. end;
  1035. { Attempts to allocate a volatile MM register for use between p and hp,
  1036. using AUsedRegs for the current register usage information. Returns NR_NO
  1037. if no free register could be found }
  1038. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1039. var
  1040. RegSet: TCPURegisterSet;
  1041. CurrentSuperReg: Integer;
  1042. CurrentReg: TRegister;
  1043. Currentp: tai;
  1044. Breakout: Boolean;
  1045. begin
  1046. Result := NR_NO;
  1047. RegSet :=
  1048. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1049. current_procinfo.saved_regs_mm;
  1050. for CurrentSuperReg in RegSet do
  1051. begin
  1052. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1053. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1054. begin
  1055. Currentp := p;
  1056. Breakout := False;
  1057. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1058. begin
  1059. case Currentp.typ of
  1060. ait_instruction:
  1061. begin
  1062. if RegInInstruction(CurrentReg, Currentp) then
  1063. begin
  1064. Breakout := True;
  1065. Break;
  1066. end;
  1067. { Cannot allocate across an unconditional jump }
  1068. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1069. Exit;
  1070. end;
  1071. ait_marker:
  1072. { Don't try anything more if a marker is hit }
  1073. Exit;
  1074. ait_regalloc:
  1075. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1076. begin
  1077. Breakout := True;
  1078. Break;
  1079. end;
  1080. else
  1081. ;
  1082. end;
  1083. end;
  1084. if Breakout then
  1085. { Try the next register }
  1086. Continue;
  1087. { We have a free register available }
  1088. Result := CurrentReg;
  1089. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1090. Exit;
  1091. end;
  1092. end;
  1093. end;
  1094. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1095. begin
  1096. if not SuperRegistersEqual(reg1,reg2) then
  1097. exit(false);
  1098. if getregtype(reg1)<>R_INTREGISTER then
  1099. exit(true); {because SuperRegisterEqual is true}
  1100. case getsubreg(reg1) of
  1101. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1102. higher, it preserves the high bits, so the new value depends on
  1103. reg2's previous value. In other words, it is equivalent to doing:
  1104. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1105. R_SUBL:
  1106. exit(getsubreg(reg2)=R_SUBL);
  1107. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1108. higher, it actually does a:
  1109. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1110. R_SUBH:
  1111. exit(getsubreg(reg2)=R_SUBH);
  1112. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1113. bits of reg2:
  1114. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1115. R_SUBW:
  1116. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1117. { a write to R_SUBD always overwrites every other subregister,
  1118. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1119. R_SUBD,
  1120. R_SUBQ:
  1121. exit(true);
  1122. else
  1123. internalerror(2017042801);
  1124. end;
  1125. end;
  1126. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1127. begin
  1128. if not SuperRegistersEqual(reg1,reg2) then
  1129. exit(false);
  1130. if getregtype(reg1)<>R_INTREGISTER then
  1131. exit(true); {because SuperRegisterEqual is true}
  1132. case getsubreg(reg1) of
  1133. R_SUBL:
  1134. exit(getsubreg(reg2)<>R_SUBH);
  1135. R_SUBH:
  1136. exit(getsubreg(reg2)<>R_SUBL);
  1137. R_SUBW,
  1138. R_SUBD,
  1139. R_SUBQ:
  1140. exit(true);
  1141. else
  1142. internalerror(2017042802);
  1143. end;
  1144. end;
  1145. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1146. var
  1147. hp1 : tai;
  1148. l : TCGInt;
  1149. begin
  1150. result:=false;
  1151. { changes the code sequence
  1152. shr/sar const1, x
  1153. shl const2, x
  1154. to
  1155. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1156. if GetNextInstruction(p, hp1) and
  1157. MatchInstruction(hp1,A_SHL,[]) and
  1158. (taicpu(p).oper[0]^.typ = top_const) and
  1159. (taicpu(hp1).oper[0]^.typ = top_const) and
  1160. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1161. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1162. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1163. begin
  1164. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1165. not(cs_opt_size in current_settings.optimizerswitches) then
  1166. begin
  1167. { shr/sar const1, %reg
  1168. shl const2, %reg
  1169. with const1 > const2 }
  1170. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1171. taicpu(hp1).opcode := A_AND;
  1172. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1173. case taicpu(p).opsize Of
  1174. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1175. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1176. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1177. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1178. else
  1179. Internalerror(2017050703)
  1180. end;
  1181. end
  1182. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1183. not(cs_opt_size in current_settings.optimizerswitches) then
  1184. begin
  1185. { shr/sar const1, %reg
  1186. shl const2, %reg
  1187. with const1 < const2 }
  1188. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1189. taicpu(p).opcode := A_AND;
  1190. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1191. case taicpu(p).opsize Of
  1192. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1193. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1194. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1195. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1196. else
  1197. Internalerror(2017050702)
  1198. end;
  1199. end
  1200. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1201. begin
  1202. { shr/sar const1, %reg
  1203. shl const2, %reg
  1204. with const1 = const2 }
  1205. taicpu(p).opcode := A_AND;
  1206. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1207. case taicpu(p).opsize Of
  1208. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1209. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1210. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1211. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1212. else
  1213. Internalerror(2017050701)
  1214. end;
  1215. RemoveInstruction(hp1);
  1216. end;
  1217. end;
  1218. end;
  1219. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1220. var
  1221. opsize : topsize;
  1222. hp1 : tai;
  1223. tmpref : treference;
  1224. ShiftValue : Cardinal;
  1225. BaseValue : TCGInt;
  1226. begin
  1227. result:=false;
  1228. opsize:=taicpu(p).opsize;
  1229. { changes certain "imul const, %reg"'s to lea sequences }
  1230. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1231. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1232. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1233. if (taicpu(p).oper[0]^.val = 1) then
  1234. if (taicpu(p).ops = 2) then
  1235. { remove "imul $1, reg" }
  1236. begin
  1237. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1238. Result := RemoveCurrentP(p);
  1239. end
  1240. else
  1241. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1242. begin
  1243. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1244. InsertLLItem(p.previous, p.next, hp1);
  1245. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1246. p.free;
  1247. p := hp1;
  1248. end
  1249. else if ((taicpu(p).ops <= 2) or
  1250. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1251. not(cs_opt_size in current_settings.optimizerswitches) and
  1252. (not(GetNextInstruction(p, hp1)) or
  1253. not((tai(hp1).typ = ait_instruction) and
  1254. ((taicpu(hp1).opcode=A_Jcc) and
  1255. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1256. begin
  1257. {
  1258. imul X, reg1, reg2 to
  1259. lea (reg1,reg1,Y), reg2
  1260. shl ZZ,reg2
  1261. imul XX, reg1 to
  1262. lea (reg1,reg1,YY), reg1
  1263. shl ZZ,reg2
  1264. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1265. it does not exist as a separate optimization target in FPC though.
  1266. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1267. at most two zeros
  1268. }
  1269. reference_reset(tmpref,1,[]);
  1270. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1271. begin
  1272. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1273. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1274. TmpRef.base := taicpu(p).oper[1]^.reg;
  1275. TmpRef.index := taicpu(p).oper[1]^.reg;
  1276. if not(BaseValue in [3,5,9]) then
  1277. Internalerror(2018110101);
  1278. TmpRef.ScaleFactor := BaseValue-1;
  1279. if (taicpu(p).ops = 2) then
  1280. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1281. else
  1282. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1283. AsmL.InsertAfter(hp1,p);
  1284. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1285. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1286. RemoveCurrentP(p, hp1);
  1287. if ShiftValue>0 then
  1288. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1289. end;
  1290. end;
  1291. end;
  1292. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1293. begin
  1294. Result := False;
  1295. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1296. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1297. begin
  1298. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1299. taicpu(p).opcode := A_MOV;
  1300. Result := True;
  1301. end;
  1302. end;
  1303. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1304. var
  1305. p: taicpu absolute hp; { Implicit typecast }
  1306. i: Integer;
  1307. begin
  1308. Result := False;
  1309. if not assigned(hp) or
  1310. (hp.typ <> ait_instruction) then
  1311. Exit;
  1312. Prefetch(insprop[p.opcode]);
  1313. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1314. with insprop[p.opcode] do
  1315. begin
  1316. case getsubreg(reg) of
  1317. R_SUBW,R_SUBD,R_SUBQ:
  1318. Result:=
  1319. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1320. uncommon flags are checked first }
  1321. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1322. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1323. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1324. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1325. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1326. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1327. R_SUBFLAGCARRY:
  1328. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1329. R_SUBFLAGPARITY:
  1330. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1331. R_SUBFLAGAUXILIARY:
  1332. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1333. R_SUBFLAGZERO:
  1334. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1335. R_SUBFLAGSIGN:
  1336. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1337. R_SUBFLAGOVERFLOW:
  1338. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1339. R_SUBFLAGINTERRUPT:
  1340. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1341. R_SUBFLAGDIRECTION:
  1342. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1343. else
  1344. internalerror(2017050501);
  1345. end;
  1346. exit;
  1347. end;
  1348. { Handle special cases first }
  1349. case p.opcode of
  1350. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1351. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1352. begin
  1353. Result :=
  1354. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1355. (p.oper[1]^.typ = top_reg) and
  1356. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1357. (
  1358. (p.oper[0]^.typ = top_const) or
  1359. (
  1360. (p.oper[0]^.typ = top_reg) and
  1361. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1362. ) or (
  1363. (p.oper[0]^.typ = top_ref) and
  1364. not RegInRef(reg,p.oper[0]^.ref^)
  1365. )
  1366. );
  1367. end;
  1368. A_MUL, A_IMUL:
  1369. Result :=
  1370. (
  1371. (p.ops=3) and { IMUL only }
  1372. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1373. (
  1374. (
  1375. (p.oper[1]^.typ=top_reg) and
  1376. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1377. ) or (
  1378. (p.oper[1]^.typ=top_ref) and
  1379. not RegInRef(reg,p.oper[1]^.ref^)
  1380. )
  1381. )
  1382. ) or (
  1383. (
  1384. (p.ops=1) and
  1385. (
  1386. (
  1387. (
  1388. (p.oper[0]^.typ=top_reg) and
  1389. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1390. )
  1391. ) or (
  1392. (p.oper[0]^.typ=top_ref) and
  1393. not RegInRef(reg,p.oper[0]^.ref^)
  1394. )
  1395. ) and (
  1396. (
  1397. (p.opsize=S_B) and
  1398. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1399. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1400. ) or (
  1401. (p.opsize=S_W) and
  1402. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1403. ) or (
  1404. (p.opsize=S_L) and
  1405. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1406. {$ifdef x86_64}
  1407. ) or (
  1408. (p.opsize=S_Q) and
  1409. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1410. {$endif x86_64}
  1411. )
  1412. )
  1413. )
  1414. );
  1415. A_CBW:
  1416. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1417. {$ifndef x86_64}
  1418. A_LDS:
  1419. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1420. A_LES:
  1421. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1422. {$endif not x86_64}
  1423. A_LFS:
  1424. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1425. A_LGS:
  1426. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1427. A_LSS:
  1428. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1429. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1430. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1431. A_LODSB:
  1432. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1433. A_LODSW:
  1434. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1435. {$ifdef x86_64}
  1436. A_LODSQ:
  1437. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1438. {$endif x86_64}
  1439. A_LODSD:
  1440. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1441. A_FSTSW, A_FNSTSW:
  1442. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1443. else
  1444. begin
  1445. with insprop[p.opcode] do
  1446. begin
  1447. if (
  1448. { xor %reg,%reg etc. is classed as a new value }
  1449. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1450. MatchOpType(p, top_reg, top_reg) and
  1451. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1452. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1453. ) then
  1454. begin
  1455. Result := True;
  1456. Exit;
  1457. end;
  1458. { Make sure the entire register is overwritten }
  1459. if (getregtype(reg) = R_INTREGISTER) then
  1460. begin
  1461. if (p.ops > 0) then
  1462. begin
  1463. if RegInOp(reg, p.oper[0]^) then
  1464. begin
  1465. if (p.oper[0]^.typ = top_ref) then
  1466. begin
  1467. if RegInRef(reg, p.oper[0]^.ref^) then
  1468. begin
  1469. Result := False;
  1470. Exit;
  1471. end;
  1472. end
  1473. else if (p.oper[0]^.typ = top_reg) then
  1474. begin
  1475. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1476. begin
  1477. Result := False;
  1478. Exit;
  1479. end
  1480. else if ([Ch_WOp1]*Ch<>[]) then
  1481. begin
  1482. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1483. Result := True
  1484. else
  1485. begin
  1486. Result := False;
  1487. Exit;
  1488. end;
  1489. end;
  1490. end;
  1491. end;
  1492. if (p.ops > 1) then
  1493. begin
  1494. if RegInOp(reg, p.oper[1]^) then
  1495. begin
  1496. if (p.oper[1]^.typ = top_ref) then
  1497. begin
  1498. if RegInRef(reg, p.oper[1]^.ref^) then
  1499. begin
  1500. Result := False;
  1501. Exit;
  1502. end;
  1503. end
  1504. else if (p.oper[1]^.typ = top_reg) then
  1505. begin
  1506. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1507. begin
  1508. Result := False;
  1509. Exit;
  1510. end
  1511. else if ([Ch_WOp2]*Ch<>[]) then
  1512. begin
  1513. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1514. Result := True
  1515. else
  1516. begin
  1517. Result := False;
  1518. Exit;
  1519. end;
  1520. end;
  1521. end;
  1522. end;
  1523. if (p.ops > 2) then
  1524. begin
  1525. if RegInOp(reg, p.oper[2]^) then
  1526. begin
  1527. if (p.oper[2]^.typ = top_ref) then
  1528. begin
  1529. if RegInRef(reg, p.oper[2]^.ref^) then
  1530. begin
  1531. Result := False;
  1532. Exit;
  1533. end;
  1534. end
  1535. else if (p.oper[2]^.typ = top_reg) then
  1536. begin
  1537. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1538. begin
  1539. Result := False;
  1540. Exit;
  1541. end
  1542. else if ([Ch_WOp3]*Ch<>[]) then
  1543. begin
  1544. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1545. Result := True
  1546. else
  1547. begin
  1548. Result := False;
  1549. Exit;
  1550. end;
  1551. end;
  1552. end;
  1553. end;
  1554. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1555. begin
  1556. if (p.oper[3]^.typ = top_ref) then
  1557. begin
  1558. if RegInRef(reg, p.oper[3]^.ref^) then
  1559. begin
  1560. Result := False;
  1561. Exit;
  1562. end;
  1563. end
  1564. else if (p.oper[3]^.typ = top_reg) then
  1565. begin
  1566. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1567. begin
  1568. Result := False;
  1569. Exit;
  1570. end
  1571. else if ([Ch_WOp4]*Ch<>[]) then
  1572. begin
  1573. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1574. Result := True
  1575. else
  1576. begin
  1577. Result := False;
  1578. Exit;
  1579. end;
  1580. end;
  1581. end;
  1582. end;
  1583. end;
  1584. end;
  1585. end;
  1586. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1587. case getsupreg(reg) of
  1588. RS_EAX:
  1589. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1590. begin
  1591. Result := True;
  1592. Exit;
  1593. end;
  1594. RS_ECX:
  1595. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1596. begin
  1597. Result := True;
  1598. Exit;
  1599. end;
  1600. RS_EDX:
  1601. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1602. begin
  1603. Result := True;
  1604. Exit;
  1605. end;
  1606. RS_EBX:
  1607. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1608. begin
  1609. Result := True;
  1610. Exit;
  1611. end;
  1612. RS_ESP:
  1613. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1614. begin
  1615. Result := True;
  1616. Exit;
  1617. end;
  1618. RS_EBP:
  1619. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1620. begin
  1621. Result := True;
  1622. Exit;
  1623. end;
  1624. RS_ESI:
  1625. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1626. begin
  1627. Result := True;
  1628. Exit;
  1629. end;
  1630. RS_EDI:
  1631. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1632. begin
  1633. Result := True;
  1634. Exit;
  1635. end;
  1636. else
  1637. ;
  1638. end;
  1639. end;
  1640. end;
  1641. end;
  1642. end;
  1643. end;
  1644. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1645. var
  1646. hp2,hp3 : tai;
  1647. begin
  1648. { some x86-64 issue a NOP before the real exit code }
  1649. if MatchInstruction(p,A_NOP,[]) then
  1650. GetNextInstruction(p,p);
  1651. result:=assigned(p) and (p.typ=ait_instruction) and
  1652. ((taicpu(p).opcode = A_RET) or
  1653. ((taicpu(p).opcode=A_LEAVE) and
  1654. GetNextInstruction(p,hp2) and
  1655. MatchInstruction(hp2,A_RET,[S_NO])
  1656. ) or
  1657. (((taicpu(p).opcode=A_LEA) and
  1658. MatchOpType(taicpu(p),top_ref,top_reg) and
  1659. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1660. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1661. ) and
  1662. GetNextInstruction(p,hp2) and
  1663. MatchInstruction(hp2,A_RET,[S_NO])
  1664. ) or
  1665. ((((taicpu(p).opcode=A_MOV) and
  1666. MatchOpType(taicpu(p),top_reg,top_reg) and
  1667. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1668. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1669. ((taicpu(p).opcode=A_LEA) and
  1670. MatchOpType(taicpu(p),top_ref,top_reg) and
  1671. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1672. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1673. )
  1674. ) and
  1675. GetNextInstruction(p,hp2) and
  1676. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1677. MatchOpType(taicpu(hp2),top_reg) and
  1678. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1679. GetNextInstruction(hp2,hp3) and
  1680. MatchInstruction(hp3,A_RET,[S_NO])
  1681. )
  1682. );
  1683. end;
  1684. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1685. begin
  1686. isFoldableArithOp := False;
  1687. case hp1.opcode of
  1688. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1689. isFoldableArithOp :=
  1690. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1691. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1692. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1693. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1694. (taicpu(hp1).oper[1]^.reg = reg);
  1695. A_INC,A_DEC,A_NEG,A_NOT:
  1696. isFoldableArithOp :=
  1697. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1698. (taicpu(hp1).oper[0]^.reg = reg);
  1699. else
  1700. ;
  1701. end;
  1702. end;
  1703. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1704. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1705. var
  1706. hp2: tai;
  1707. begin
  1708. hp2 := p;
  1709. repeat
  1710. hp2 := tai(hp2.previous);
  1711. if assigned(hp2) and
  1712. (hp2.typ = ait_regalloc) and
  1713. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1714. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1715. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1716. begin
  1717. RemoveInstruction(hp2);
  1718. break;
  1719. end;
  1720. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1721. end;
  1722. begin
  1723. case current_procinfo.procdef.returndef.typ of
  1724. arraydef,recorddef,pointerdef,
  1725. stringdef,enumdef,procdef,objectdef,errordef,
  1726. filedef,setdef,procvardef,
  1727. classrefdef,forwarddef:
  1728. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1729. orddef:
  1730. if current_procinfo.procdef.returndef.size <> 0 then
  1731. begin
  1732. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1733. { for int64/qword }
  1734. if current_procinfo.procdef.returndef.size = 8 then
  1735. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1736. end;
  1737. else
  1738. ;
  1739. end;
  1740. end;
  1741. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1742. var
  1743. hp1,hp2 : tai;
  1744. begin
  1745. result:=false;
  1746. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1747. begin
  1748. { vmova* reg1,reg1
  1749. =>
  1750. <nop> }
  1751. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1752. begin
  1753. RemoveCurrentP(p);
  1754. result:=true;
  1755. exit;
  1756. end
  1757. else if GetNextInstruction(p,hp1) then
  1758. begin
  1759. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1760. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1761. begin
  1762. { vmova* reg1,reg2
  1763. vmova* reg2,reg3
  1764. dealloc reg2
  1765. =>
  1766. vmova* reg1,reg3 }
  1767. TransferUsedRegs(TmpUsedRegs);
  1768. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1769. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1770. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1771. begin
  1772. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1773. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1774. RemoveInstruction(hp1);
  1775. result:=true;
  1776. exit;
  1777. end
  1778. { special case:
  1779. vmova* reg1,<op>
  1780. vmova* <op>,reg1
  1781. =>
  1782. vmova* reg1,<op> }
  1783. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1784. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1785. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1786. ) then
  1787. begin
  1788. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1789. RemoveInstruction(hp1);
  1790. result:=true;
  1791. exit;
  1792. end
  1793. end
  1794. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1795. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1796. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1797. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1798. ) and
  1799. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1800. begin
  1801. { vmova* reg1,reg2
  1802. vmovs* reg2,<op>
  1803. dealloc reg2
  1804. =>
  1805. vmovs* reg1,reg3 }
  1806. TransferUsedRegs(TmpUsedRegs);
  1807. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1808. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1809. begin
  1810. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1811. taicpu(p).opcode:=taicpu(hp1).opcode;
  1812. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1813. RemoveInstruction(hp1);
  1814. result:=true;
  1815. exit;
  1816. end
  1817. end;
  1818. end;
  1819. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1820. begin
  1821. if MatchInstruction(hp1,[A_VFMADDPD,
  1822. A_VFMADD132PD,
  1823. A_VFMADD132PS,
  1824. A_VFMADD132SD,
  1825. A_VFMADD132SS,
  1826. A_VFMADD213PD,
  1827. A_VFMADD213PS,
  1828. A_VFMADD213SD,
  1829. A_VFMADD213SS,
  1830. A_VFMADD231PD,
  1831. A_VFMADD231PS,
  1832. A_VFMADD231SD,
  1833. A_VFMADD231SS,
  1834. A_VFMADDSUB132PD,
  1835. A_VFMADDSUB132PS,
  1836. A_VFMADDSUB213PD,
  1837. A_VFMADDSUB213PS,
  1838. A_VFMADDSUB231PD,
  1839. A_VFMADDSUB231PS,
  1840. A_VFMSUB132PD,
  1841. A_VFMSUB132PS,
  1842. A_VFMSUB132SD,
  1843. A_VFMSUB132SS,
  1844. A_VFMSUB213PD,
  1845. A_VFMSUB213PS,
  1846. A_VFMSUB213SD,
  1847. A_VFMSUB213SS,
  1848. A_VFMSUB231PD,
  1849. A_VFMSUB231PS,
  1850. A_VFMSUB231SD,
  1851. A_VFMSUB231SS,
  1852. A_VFMSUBADD132PD,
  1853. A_VFMSUBADD132PS,
  1854. A_VFMSUBADD213PD,
  1855. A_VFMSUBADD213PS,
  1856. A_VFMSUBADD231PD,
  1857. A_VFMSUBADD231PS,
  1858. A_VFNMADD132PD,
  1859. A_VFNMADD132PS,
  1860. A_VFNMADD132SD,
  1861. A_VFNMADD132SS,
  1862. A_VFNMADD213PD,
  1863. A_VFNMADD213PS,
  1864. A_VFNMADD213SD,
  1865. A_VFNMADD213SS,
  1866. A_VFNMADD231PD,
  1867. A_VFNMADD231PS,
  1868. A_VFNMADD231SD,
  1869. A_VFNMADD231SS,
  1870. A_VFNMSUB132PD,
  1871. A_VFNMSUB132PS,
  1872. A_VFNMSUB132SD,
  1873. A_VFNMSUB132SS,
  1874. A_VFNMSUB213PD,
  1875. A_VFNMSUB213PS,
  1876. A_VFNMSUB213SD,
  1877. A_VFNMSUB213SS,
  1878. A_VFNMSUB231PD,
  1879. A_VFNMSUB231PS,
  1880. A_VFNMSUB231SD,
  1881. A_VFNMSUB231SS],[S_NO]) and
  1882. { we mix single and double opperations here because we assume that the compiler
  1883. generates vmovapd only after double operations and vmovaps only after single operations }
  1884. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1885. GetNextInstruction(hp1,hp2) and
  1886. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1887. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1888. begin
  1889. TransferUsedRegs(TmpUsedRegs);
  1890. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1891. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1892. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1893. begin
  1894. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1895. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1896. RemoveInstruction(hp2);
  1897. end;
  1898. end
  1899. else if (hp1.typ = ait_instruction) and
  1900. GetNextInstruction(hp1, hp2) and
  1901. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1902. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1903. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1904. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1905. (((taicpu(p).opcode=A_MOVAPS) and
  1906. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1907. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1908. ((taicpu(p).opcode=A_MOVAPD) and
  1909. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1910. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1911. ) then
  1912. { change
  1913. movapX reg,reg2
  1914. addsX/subsX/... reg3, reg2
  1915. movapX reg2,reg
  1916. to
  1917. addsX/subsX/... reg3,reg
  1918. }
  1919. begin
  1920. TransferUsedRegs(TmpUsedRegs);
  1921. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1922. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1923. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1924. begin
  1925. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1926. debug_op2str(taicpu(p).opcode)+' '+
  1927. debug_op2str(taicpu(hp1).opcode)+' '+
  1928. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1929. { we cannot eliminate the first move if
  1930. the operations uses the same register for source and dest }
  1931. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1932. RemoveCurrentP(p, nil);
  1933. p:=hp1;
  1934. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1935. RemoveInstruction(hp2);
  1936. result:=true;
  1937. end;
  1938. end
  1939. else if (hp1.typ = ait_instruction) and
  1940. (((taicpu(p).opcode=A_VMOVAPD) and
  1941. (taicpu(hp1).opcode=A_VCOMISD)) or
  1942. ((taicpu(p).opcode=A_VMOVAPS) and
  1943. ((taicpu(hp1).opcode=A_VCOMISS))
  1944. )
  1945. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1946. { change
  1947. movapX reg,reg1
  1948. vcomisX reg1,reg1
  1949. to
  1950. vcomisX reg,reg
  1951. }
  1952. begin
  1953. TransferUsedRegs(TmpUsedRegs);
  1954. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1955. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1956. begin
  1957. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  1958. debug_op2str(taicpu(p).opcode)+' '+
  1959. debug_op2str(taicpu(hp1).opcode)+') done',p);
  1960. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1961. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  1962. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  1963. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  1964. RemoveCurrentP(p, nil);
  1965. result:=true;
  1966. exit;
  1967. end;
  1968. end
  1969. end;
  1970. end;
  1971. end;
  1972. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1973. var
  1974. hp1 : tai;
  1975. begin
  1976. result:=false;
  1977. { replace
  1978. V<Op>X %mreg1,%mreg2,%mreg3
  1979. VMovX %mreg3,%mreg4
  1980. dealloc %mreg3
  1981. by
  1982. V<Op>X %mreg1,%mreg2,%mreg4
  1983. ?
  1984. }
  1985. if GetNextInstruction(p,hp1) and
  1986. { we mix single and double operations here because we assume that the compiler
  1987. generates vmovapd only after double operations and vmovaps only after single operations }
  1988. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1989. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1990. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1991. begin
  1992. TransferUsedRegs(TmpUsedRegs);
  1993. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1994. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1995. begin
  1996. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1997. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1998. RemoveInstruction(hp1);
  1999. result:=true;
  2000. end;
  2001. end;
  2002. end;
  2003. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2004. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2005. begin
  2006. Result := False;
  2007. { For safety reasons, only check for exact register matches }
  2008. { Check base register }
  2009. if (ref.base = AOldReg) then
  2010. begin
  2011. ref.base := ANewReg;
  2012. Result := True;
  2013. end;
  2014. { Check index register }
  2015. if (ref.index = AOldReg) then
  2016. begin
  2017. ref.index := ANewReg;
  2018. Result := True;
  2019. end;
  2020. end;
  2021. { Replaces all references to AOldReg in an operand to ANewReg }
  2022. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2023. var
  2024. OldSupReg, NewSupReg: TSuperRegister;
  2025. OldSubReg, NewSubReg: TSubRegister;
  2026. OldRegType: TRegisterType;
  2027. ThisOper: POper;
  2028. begin
  2029. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2030. Result := False;
  2031. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2032. InternalError(2020011801);
  2033. OldSupReg := getsupreg(AOldReg);
  2034. OldSubReg := getsubreg(AOldReg);
  2035. OldRegType := getregtype(AOldReg);
  2036. NewSupReg := getsupreg(ANewReg);
  2037. NewSubReg := getsubreg(ANewReg);
  2038. if OldRegType <> getregtype(ANewReg) then
  2039. InternalError(2020011802);
  2040. if OldSubReg <> NewSubReg then
  2041. InternalError(2020011803);
  2042. case ThisOper^.typ of
  2043. top_reg:
  2044. if (
  2045. (ThisOper^.reg = AOldReg) or
  2046. (
  2047. (OldRegType = R_INTREGISTER) and
  2048. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2049. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2050. (
  2051. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2052. {$ifndef x86_64}
  2053. and (
  2054. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2055. don't have an 8-bit representation }
  2056. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2057. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2058. )
  2059. {$endif x86_64}
  2060. )
  2061. )
  2062. ) then
  2063. begin
  2064. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2065. Result := True;
  2066. end;
  2067. top_ref:
  2068. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2069. Result := True;
  2070. else
  2071. ;
  2072. end;
  2073. end;
  2074. { Replaces all references to AOldReg in an instruction to ANewReg }
  2075. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2076. const
  2077. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2078. var
  2079. OperIdx: Integer;
  2080. begin
  2081. Result := False;
  2082. for OperIdx := 0 to p.ops - 1 do
  2083. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2084. begin
  2085. { The shift and rotate instructions can only use CL }
  2086. if not (
  2087. (OperIdx = 0) and
  2088. { This second condition just helps to avoid unnecessarily
  2089. calling MatchInstruction for 10 different opcodes }
  2090. (p.oper[0]^.reg = NR_CL) and
  2091. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2092. ) then
  2093. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2094. end
  2095. else if p.oper[OperIdx]^.typ = top_ref then
  2096. { It's okay to replace registers in references that get written to }
  2097. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2098. end;
  2099. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2100. begin
  2101. with ref^ do
  2102. Result :=
  2103. (index = NR_NO) and
  2104. (
  2105. {$ifdef x86_64}
  2106. (
  2107. (base = NR_RIP) and
  2108. (refaddr in [addr_pic, addr_pic_no_got])
  2109. ) or
  2110. {$endif x86_64}
  2111. (base = NR_STACK_POINTER_REG) or
  2112. (base = current_procinfo.framepointer)
  2113. );
  2114. end;
  2115. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2116. var
  2117. l: asizeint;
  2118. begin
  2119. Result := False;
  2120. { Should have been checked previously }
  2121. if p.opcode <> A_LEA then
  2122. InternalError(2020072501);
  2123. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2124. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2125. not(cs_opt_size in current_settings.optimizerswitches) then
  2126. exit;
  2127. with p.oper[0]^.ref^ do
  2128. begin
  2129. if (base <> p.oper[1]^.reg) or
  2130. (index <> NR_NO) or
  2131. assigned(symbol) then
  2132. exit;
  2133. l:=offset;
  2134. if (l=1) and UseIncDec then
  2135. begin
  2136. p.opcode:=A_INC;
  2137. p.loadreg(0,p.oper[1]^.reg);
  2138. p.ops:=1;
  2139. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2140. end
  2141. else if (l=-1) and UseIncDec then
  2142. begin
  2143. p.opcode:=A_DEC;
  2144. p.loadreg(0,p.oper[1]^.reg);
  2145. p.ops:=1;
  2146. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2147. end
  2148. else
  2149. begin
  2150. if (l<0) and (l<>-2147483648) then
  2151. begin
  2152. p.opcode:=A_SUB;
  2153. p.loadConst(0,-l);
  2154. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2155. end
  2156. else
  2157. begin
  2158. p.opcode:=A_ADD;
  2159. p.loadConst(0,l);
  2160. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2161. end;
  2162. end;
  2163. end;
  2164. Result := True;
  2165. end;
  2166. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2167. var
  2168. CurrentReg, ReplaceReg: TRegister;
  2169. begin
  2170. Result := False;
  2171. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2172. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2173. case hp.opcode of
  2174. A_FSTSW, A_FNSTSW,
  2175. A_IN, A_INS, A_OUT, A_OUTS,
  2176. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2177. { These routines have explicit operands, but they are restricted in
  2178. what they can be (e.g. IN and OUT can only read from AL, AX or
  2179. EAX. }
  2180. Exit;
  2181. A_IMUL:
  2182. begin
  2183. { The 1-operand version writes to implicit registers
  2184. The 2-operand version reads from the first operator, and reads
  2185. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2186. the 3-operand version reads from a register that it doesn't write to
  2187. }
  2188. case hp.ops of
  2189. 1:
  2190. if (
  2191. (
  2192. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2193. ) or
  2194. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2195. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2196. begin
  2197. Result := True;
  2198. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2199. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2200. end;
  2201. 2:
  2202. { Only modify the first parameter }
  2203. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2204. begin
  2205. Result := True;
  2206. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2207. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2208. end;
  2209. 3:
  2210. { Only modify the second parameter }
  2211. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2212. begin
  2213. Result := True;
  2214. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2215. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2216. end;
  2217. else
  2218. InternalError(2020012901);
  2219. end;
  2220. end;
  2221. else
  2222. if (hp.ops > 0) and
  2223. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2224. begin
  2225. Result := True;
  2226. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2227. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2228. end;
  2229. end;
  2230. end;
  2231. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2232. var
  2233. hp1, hp2, hp3: tai;
  2234. DoOptimisation, TempBool: Boolean;
  2235. {$ifdef x86_64}
  2236. NewConst: TCGInt;
  2237. {$endif x86_64}
  2238. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2239. begin
  2240. if taicpu(hp1).opcode = signed_movop then
  2241. begin
  2242. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2243. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2244. end
  2245. else
  2246. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2247. end;
  2248. function TryConstMerge(var p1, p2: tai): Boolean;
  2249. var
  2250. ThisRef: TReference;
  2251. begin
  2252. Result := False;
  2253. ThisRef := taicpu(p2).oper[1]^.ref^;
  2254. { Only permit writes to the stack, since we can guarantee alignment with that }
  2255. if (ThisRef.index = NR_NO) and
  2256. (
  2257. (ThisRef.base = NR_STACK_POINTER_REG) or
  2258. (ThisRef.base = current_procinfo.framepointer)
  2259. ) then
  2260. begin
  2261. case taicpu(p).opsize of
  2262. S_B:
  2263. begin
  2264. { Word writes must be on a 2-byte boundary }
  2265. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2266. begin
  2267. { Reduce offset of second reference to see if it is sequential with the first }
  2268. Dec(ThisRef.offset, 1);
  2269. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2270. begin
  2271. { Make sure the constants aren't represented as a
  2272. negative number, as these won't merge properly }
  2273. taicpu(p1).opsize := S_W;
  2274. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2275. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2276. RemoveInstruction(p2);
  2277. Result := True;
  2278. end;
  2279. end;
  2280. end;
  2281. S_W:
  2282. begin
  2283. { Longword writes must be on a 4-byte boundary }
  2284. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2285. begin
  2286. { Reduce offset of second reference to see if it is sequential with the first }
  2287. Dec(ThisRef.offset, 2);
  2288. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2289. begin
  2290. { Make sure the constants aren't represented as a
  2291. negative number, as these won't merge properly }
  2292. taicpu(p1).opsize := S_L;
  2293. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2294. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2295. RemoveInstruction(p2);
  2296. Result := True;
  2297. end;
  2298. end;
  2299. end;
  2300. {$ifdef x86_64}
  2301. S_L:
  2302. begin
  2303. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2304. see if the constants can be encoded this way. }
  2305. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2306. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2307. { Quadword writes must be on an 8-byte boundary }
  2308. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2309. begin
  2310. { Reduce offset of second reference to see if it is sequential with the first }
  2311. Dec(ThisRef.offset, 4);
  2312. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2313. begin
  2314. { Make sure the constants aren't represented as a
  2315. negative number, as these won't merge properly }
  2316. taicpu(p1).opsize := S_Q;
  2317. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2318. taicpu(p1).oper[0]^.val := NewConst;
  2319. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2320. RemoveInstruction(p2);
  2321. Result := True;
  2322. end;
  2323. end;
  2324. end;
  2325. {$endif x86_64}
  2326. else
  2327. ;
  2328. end;
  2329. end;
  2330. end;
  2331. var
  2332. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2333. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2334. NewSize: topsize;
  2335. CurrentReg, ActiveReg: TRegister;
  2336. SourceRef, TargetRef: TReference;
  2337. MovAligned, MovUnaligned: TAsmOp;
  2338. ThisRef: TReference;
  2339. begin
  2340. Result:=false;
  2341. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2342. { remove mov reg1,reg1? }
  2343. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2344. then
  2345. begin
  2346. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2347. { take care of the register (de)allocs following p }
  2348. RemoveCurrentP(p, hp1);
  2349. Result:=true;
  2350. exit;
  2351. end;
  2352. { All the next optimisations require a next instruction }
  2353. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2354. Exit;
  2355. { Look for:
  2356. mov %reg1,%reg2
  2357. ??? %reg2,r/m
  2358. Change to:
  2359. mov %reg1,%reg2
  2360. ??? %reg1,r/m
  2361. }
  2362. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2363. begin
  2364. CurrentReg := taicpu(p).oper[1]^.reg;
  2365. if RegReadByInstruction(CurrentReg, hp1) and
  2366. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2367. begin
  2368. { A change has occurred, just not in p }
  2369. Result := True;
  2370. TransferUsedRegs(TmpUsedRegs);
  2371. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2372. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2373. { Just in case something didn't get modified (e.g. an
  2374. implicit register) }
  2375. not RegReadByInstruction(CurrentReg, hp1) then
  2376. begin
  2377. { We can remove the original MOV }
  2378. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2379. RemoveCurrentp(p, hp1);
  2380. { UsedRegs got updated by RemoveCurrentp }
  2381. Result := True;
  2382. Exit;
  2383. end;
  2384. { If we know a MOV instruction has become a null operation, we might as well
  2385. get rid of it now to save time. }
  2386. if (taicpu(hp1).opcode = A_MOV) and
  2387. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2388. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2389. { Just being a register is enough to confirm it's a null operation }
  2390. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2391. begin
  2392. Result := True;
  2393. { Speed-up to reduce a pipeline stall... if we had something like...
  2394. movl %eax,%edx
  2395. movw %dx,%ax
  2396. ... the second instruction would change to movw %ax,%ax, but
  2397. given that it is now %ax that's active rather than %eax,
  2398. penalties might occur due to a partial register write, so instead,
  2399. change it to a MOVZX instruction when optimising for speed.
  2400. }
  2401. if not (cs_opt_size in current_settings.optimizerswitches) and
  2402. IsMOVZXAcceptable and
  2403. (taicpu(hp1).opsize < taicpu(p).opsize)
  2404. {$ifdef x86_64}
  2405. { operations already implicitly set the upper 64 bits to zero }
  2406. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2407. {$endif x86_64}
  2408. then
  2409. begin
  2410. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2411. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2412. case taicpu(p).opsize of
  2413. S_W:
  2414. if taicpu(hp1).opsize = S_B then
  2415. taicpu(hp1).opsize := S_BL
  2416. else
  2417. InternalError(2020012911);
  2418. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2419. case taicpu(hp1).opsize of
  2420. S_B:
  2421. taicpu(hp1).opsize := S_BL;
  2422. S_W:
  2423. taicpu(hp1).opsize := S_WL;
  2424. else
  2425. InternalError(2020012912);
  2426. end;
  2427. else
  2428. InternalError(2020012910);
  2429. end;
  2430. taicpu(hp1).opcode := A_MOVZX;
  2431. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2432. end
  2433. else
  2434. begin
  2435. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2436. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2437. RemoveInstruction(hp1);
  2438. { The instruction after what was hp1 is now the immediate next instruction,
  2439. so we can continue to make optimisations if it's present }
  2440. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2441. Exit;
  2442. hp1 := hp2;
  2443. end;
  2444. end;
  2445. end;
  2446. end;
  2447. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2448. overwrites the original destination register. e.g.
  2449. movl ###,%reg2d
  2450. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2451. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2452. }
  2453. if (taicpu(p).oper[1]^.typ = top_reg) and
  2454. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2455. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2456. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2457. begin
  2458. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2459. begin
  2460. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2461. case taicpu(p).oper[0]^.typ of
  2462. top_const:
  2463. { We have something like:
  2464. movb $x, %regb
  2465. movzbl %regb,%regd
  2466. Change to:
  2467. movl $x, %regd
  2468. }
  2469. begin
  2470. case taicpu(hp1).opsize of
  2471. S_BW:
  2472. begin
  2473. convert_mov_value(A_MOVSX, $FF);
  2474. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2475. taicpu(p).opsize := S_W;
  2476. end;
  2477. S_BL:
  2478. begin
  2479. convert_mov_value(A_MOVSX, $FF);
  2480. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2481. taicpu(p).opsize := S_L;
  2482. end;
  2483. S_WL:
  2484. begin
  2485. convert_mov_value(A_MOVSX, $FFFF);
  2486. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2487. taicpu(p).opsize := S_L;
  2488. end;
  2489. {$ifdef x86_64}
  2490. S_BQ:
  2491. begin
  2492. convert_mov_value(A_MOVSX, $FF);
  2493. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2494. taicpu(p).opsize := S_Q;
  2495. end;
  2496. S_WQ:
  2497. begin
  2498. convert_mov_value(A_MOVSX, $FFFF);
  2499. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2500. taicpu(p).opsize := S_Q;
  2501. end;
  2502. S_LQ:
  2503. begin
  2504. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2505. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2506. taicpu(p).opsize := S_Q;
  2507. end;
  2508. {$endif x86_64}
  2509. else
  2510. { If hp1 was a MOV instruction, it should have been
  2511. optimised already }
  2512. InternalError(2020021001);
  2513. end;
  2514. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2515. RemoveInstruction(hp1);
  2516. Result := True;
  2517. Exit;
  2518. end;
  2519. top_ref:
  2520. begin
  2521. { We have something like:
  2522. movb mem, %regb
  2523. movzbl %regb,%regd
  2524. Change to:
  2525. movzbl mem, %regd
  2526. }
  2527. ThisRef := taicpu(p).oper[0]^.ref^;
  2528. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2529. begin
  2530. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2531. taicpu(hp1).loadref(0, ThisRef);
  2532. { Make sure any registers in the references are properly tracked }
  2533. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2534. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2535. if (ThisRef.index <> NR_NO) then
  2536. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2537. RemoveCurrentP(p, hp1);
  2538. Result := True;
  2539. Exit;
  2540. end;
  2541. end;
  2542. else
  2543. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2544. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2545. Exit;
  2546. end;
  2547. end
  2548. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2549. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2550. optimised }
  2551. else
  2552. begin
  2553. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2554. RemoveCurrentP(p, hp1);
  2555. Result := True;
  2556. Exit;
  2557. end;
  2558. end;
  2559. if (taicpu(hp1).opcode = A_AND) and
  2560. (taicpu(p).oper[1]^.typ = top_reg) and
  2561. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2562. begin
  2563. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2564. begin
  2565. case taicpu(p).opsize of
  2566. S_L:
  2567. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2568. begin
  2569. { Optimize out:
  2570. mov x, %reg
  2571. and ffffffffh, %reg
  2572. }
  2573. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2574. RemoveInstruction(hp1);
  2575. Result:=true;
  2576. exit;
  2577. end;
  2578. S_Q: { TODO: Confirm if this is even possible }
  2579. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2580. begin
  2581. { Optimize out:
  2582. mov x, %reg
  2583. and ffffffffffffffffh, %reg
  2584. }
  2585. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2586. RemoveInstruction(hp1);
  2587. Result:=true;
  2588. exit;
  2589. end;
  2590. else
  2591. ;
  2592. end;
  2593. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2594. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2595. GetNextInstruction(hp1,hp2) and
  2596. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2597. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2598. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2599. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2600. GetNextInstruction(hp2,hp3) and
  2601. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2602. (taicpu(hp3).condition in [C_E,C_NE]) then
  2603. begin
  2604. TransferUsedRegs(TmpUsedRegs);
  2605. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2606. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2607. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2608. begin
  2609. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2610. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2611. taicpu(hp1).opcode:=A_TEST;
  2612. RemoveInstruction(hp2);
  2613. RemoveCurrentP(p, hp1);
  2614. Result:=true;
  2615. exit;
  2616. end;
  2617. end;
  2618. end
  2619. else if IsMOVZXAcceptable and
  2620. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2621. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2622. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2623. then
  2624. begin
  2625. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2626. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2627. case taicpu(p).opsize of
  2628. S_B:
  2629. if (taicpu(hp1).oper[0]^.val = $ff) then
  2630. begin
  2631. { Convert:
  2632. movb x, %regl movb x, %regl
  2633. andw ffh, %regw andl ffh, %regd
  2634. To:
  2635. movzbw x, %regd movzbl x, %regd
  2636. (Identical registers, just different sizes)
  2637. }
  2638. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2639. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2640. case taicpu(hp1).opsize of
  2641. S_W: NewSize := S_BW;
  2642. S_L: NewSize := S_BL;
  2643. {$ifdef x86_64}
  2644. S_Q: NewSize := S_BQ;
  2645. {$endif x86_64}
  2646. else
  2647. InternalError(2018011510);
  2648. end;
  2649. end
  2650. else
  2651. NewSize := S_NO;
  2652. S_W:
  2653. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2654. begin
  2655. { Convert:
  2656. movw x, %regw
  2657. andl ffffh, %regd
  2658. To:
  2659. movzwl x, %regd
  2660. (Identical registers, just different sizes)
  2661. }
  2662. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2663. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2664. case taicpu(hp1).opsize of
  2665. S_L: NewSize := S_WL;
  2666. {$ifdef x86_64}
  2667. S_Q: NewSize := S_WQ;
  2668. {$endif x86_64}
  2669. else
  2670. InternalError(2018011511);
  2671. end;
  2672. end
  2673. else
  2674. NewSize := S_NO;
  2675. else
  2676. NewSize := S_NO;
  2677. end;
  2678. if NewSize <> S_NO then
  2679. begin
  2680. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2681. { The actual optimization }
  2682. taicpu(p).opcode := A_MOVZX;
  2683. taicpu(p).changeopsize(NewSize);
  2684. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2685. { Safeguard if "and" is followed by a conditional command }
  2686. TransferUsedRegs(TmpUsedRegs);
  2687. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2688. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2689. begin
  2690. { At this point, the "and" command is effectively equivalent to
  2691. "test %reg,%reg". This will be handled separately by the
  2692. Peephole Optimizer. [Kit] }
  2693. DebugMsg(SPeepholeOptimization + PreMessage +
  2694. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2695. end
  2696. else
  2697. begin
  2698. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2699. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2700. RemoveInstruction(hp1);
  2701. end;
  2702. Result := True;
  2703. Exit;
  2704. end;
  2705. end;
  2706. end;
  2707. if (taicpu(hp1).opcode = A_OR) and
  2708. (taicpu(p).oper[1]^.typ = top_reg) and
  2709. MatchOperand(taicpu(p).oper[0]^, 0) and
  2710. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2711. begin
  2712. { mov 0, %reg
  2713. or ###,%reg
  2714. Change to (only if the flags are not used):
  2715. mov ###,%reg
  2716. }
  2717. TransferUsedRegs(TmpUsedRegs);
  2718. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2719. DoOptimisation := True;
  2720. { Even if the flags are used, we might be able to do the optimisation
  2721. if the conditions are predictable }
  2722. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2723. begin
  2724. { Only perform if ### = %reg (the same register) or equal to 0,
  2725. so %reg is guaranteed to still have a value of zero }
  2726. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2727. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2728. begin
  2729. hp2 := hp1;
  2730. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2731. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2732. GetNextInstruction(hp2, hp3) do
  2733. begin
  2734. { Don't continue modifying if the flags state is getting changed }
  2735. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2736. Break;
  2737. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2738. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2739. begin
  2740. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2741. begin
  2742. { Condition is always true }
  2743. case taicpu(hp3).opcode of
  2744. A_Jcc:
  2745. begin
  2746. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2747. { Check for jump shortcuts before we destroy the condition }
  2748. DoJumpOptimizations(hp3, TempBool);
  2749. MakeUnconditional(taicpu(hp3));
  2750. Result := True;
  2751. end;
  2752. A_CMOVcc:
  2753. begin
  2754. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2755. taicpu(hp3).opcode := A_MOV;
  2756. taicpu(hp3).condition := C_None;
  2757. Result := True;
  2758. end;
  2759. A_SETcc:
  2760. begin
  2761. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2762. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2763. taicpu(hp3).opcode := A_MOV;
  2764. taicpu(hp3).ops := 2;
  2765. taicpu(hp3).condition := C_None;
  2766. taicpu(hp3).opsize := S_B;
  2767. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2768. taicpu(hp3).loadconst(0, 1);
  2769. Result := True;
  2770. end;
  2771. else
  2772. InternalError(2021090701);
  2773. end;
  2774. end
  2775. 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
  2776. begin
  2777. { Condition is always false }
  2778. case taicpu(hp3).opcode of
  2779. A_Jcc:
  2780. begin
  2781. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2782. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2783. RemoveInstruction(hp3);
  2784. Result := True;
  2785. { Since hp3 was deleted, hp2 must not be updated }
  2786. Continue;
  2787. end;
  2788. A_CMOVcc:
  2789. begin
  2790. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2791. RemoveInstruction(hp3);
  2792. Result := True;
  2793. { Since hp3 was deleted, hp2 must not be updated }
  2794. Continue;
  2795. end;
  2796. A_SETcc:
  2797. begin
  2798. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2799. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2800. taicpu(hp3).opcode := A_MOV;
  2801. taicpu(hp3).ops := 2;
  2802. taicpu(hp3).condition := C_None;
  2803. taicpu(hp3).opsize := S_B;
  2804. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2805. taicpu(hp3).loadconst(0, 0);
  2806. Result := True;
  2807. end;
  2808. else
  2809. InternalError(2021090702);
  2810. end;
  2811. end
  2812. else
  2813. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2814. DoOptimisation := False;
  2815. end;
  2816. hp2 := hp3;
  2817. end;
  2818. { Flags are still in use - don't optimise }
  2819. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2820. DoOptimisation := False;
  2821. end
  2822. else
  2823. DoOptimisation := False;
  2824. end;
  2825. if DoOptimisation then
  2826. begin
  2827. {$ifdef x86_64}
  2828. { OR only supports 32-bit sign-extended constants for 64-bit
  2829. instructions, so compensate for this if the constant is
  2830. encoded as a value greater than or equal to 2^31 }
  2831. if (taicpu(hp1).opsize = S_Q) and
  2832. (taicpu(hp1).oper[0]^.typ = top_const) and
  2833. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2834. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2835. {$endif x86_64}
  2836. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2837. taicpu(hp1).opcode := A_MOV;
  2838. RemoveCurrentP(p, hp1);
  2839. Result := True;
  2840. Exit;
  2841. end;
  2842. end;
  2843. { Next instruction is also a MOV ? }
  2844. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2845. begin
  2846. if MatchOpType(taicpu(p), top_const, top_ref) and
  2847. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2848. TryConstMerge(p, hp1) then
  2849. begin
  2850. Result := True;
  2851. { In case we have four byte writes in a row, check for 2 more
  2852. right now so we don't have to wait for another iteration of
  2853. pass 1
  2854. }
  2855. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  2856. case taicpu(p).opsize of
  2857. S_W:
  2858. begin
  2859. if GetNextInstruction(p, hp1) and
  2860. MatchInstruction(hp1, A_MOV, [S_B]) and
  2861. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2862. GetNextInstruction(hp1, hp2) and
  2863. MatchInstruction(hp2, A_MOV, [S_B]) and
  2864. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2865. { Try to merge the two bytes }
  2866. TryConstMerge(hp1, hp2) then
  2867. { Now try to merge the two words (hp2 will get deleted) }
  2868. TryConstMerge(p, hp1);
  2869. end;
  2870. S_L:
  2871. begin
  2872. { Though this only really benefits x86_64 and not i386, it
  2873. gets a potential optimisation done faster and hence
  2874. reduces the number of times OptPass1MOV is entered }
  2875. if GetNextInstruction(p, hp1) and
  2876. MatchInstruction(hp1, A_MOV, [S_W]) and
  2877. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2878. GetNextInstruction(hp1, hp2) and
  2879. MatchInstruction(hp2, A_MOV, [S_W]) and
  2880. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2881. { Try to merge the two words }
  2882. TryConstMerge(hp1, hp2) then
  2883. { This will always fail on i386, so don't bother
  2884. calling it unless we're doing x86_64 }
  2885. {$ifdef x86_64}
  2886. { Now try to merge the two longwords (hp2 will get deleted) }
  2887. TryConstMerge(p, hp1)
  2888. {$endif x86_64}
  2889. ;
  2890. end;
  2891. else
  2892. ;
  2893. end;
  2894. Exit;
  2895. end;
  2896. if (taicpu(p).oper[1]^.typ = top_reg) and
  2897. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2898. begin
  2899. CurrentReg := taicpu(p).oper[1]^.reg;
  2900. TransferUsedRegs(TmpUsedRegs);
  2901. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2902. { we have
  2903. mov x, %treg
  2904. mov %treg, y
  2905. }
  2906. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2907. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2908. { we've got
  2909. mov x, %treg
  2910. mov %treg, y
  2911. with %treg is not used after }
  2912. case taicpu(p).oper[0]^.typ Of
  2913. { top_reg is covered by DeepMOVOpt }
  2914. top_const:
  2915. begin
  2916. { change
  2917. mov const, %treg
  2918. mov %treg, y
  2919. to
  2920. mov const, y
  2921. }
  2922. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2923. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2924. begin
  2925. if taicpu(hp1).oper[1]^.typ=top_reg then
  2926. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2927. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2928. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2929. RemoveInstruction(hp1);
  2930. Result:=true;
  2931. Exit;
  2932. end;
  2933. end;
  2934. top_ref:
  2935. case taicpu(hp1).oper[1]^.typ of
  2936. top_reg:
  2937. begin
  2938. { change
  2939. mov mem, %treg
  2940. mov %treg, %reg
  2941. to
  2942. mov mem, %reg"
  2943. }
  2944. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2945. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2946. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2947. RemoveInstruction(hp1);
  2948. Result:=true;
  2949. Exit;
  2950. end;
  2951. top_ref:
  2952. begin
  2953. {$ifdef x86_64}
  2954. { Look for the following to simplify:
  2955. mov x(mem1), %reg
  2956. mov %reg, y(mem2)
  2957. mov x+8(mem1), %reg
  2958. mov %reg, y+8(mem2)
  2959. Change to:
  2960. movdqu x(mem1), %xmmreg
  2961. movdqu %xmmreg, y(mem2)
  2962. ...but only as long as the memory blocks don't overlap
  2963. }
  2964. SourceRef := taicpu(p).oper[0]^.ref^;
  2965. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2966. if (taicpu(p).opsize = S_Q) and
  2967. GetNextInstruction(hp1, hp2) and
  2968. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2969. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2970. begin
  2971. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2972. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2973. Inc(SourceRef.offset, 8);
  2974. if UseAVX then
  2975. begin
  2976. MovAligned := A_VMOVDQA;
  2977. MovUnaligned := A_VMOVDQU;
  2978. end
  2979. else
  2980. begin
  2981. MovAligned := A_MOVDQA;
  2982. MovUnaligned := A_MOVDQU;
  2983. end;
  2984. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  2985. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  2986. begin
  2987. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2988. Inc(TargetRef.offset, 8);
  2989. if GetNextInstruction(hp2, hp3) and
  2990. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2991. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2992. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2993. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2994. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2995. begin
  2996. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2997. if CurrentReg <> NR_NO then
  2998. begin
  2999. { Remember that the offsets are 8 ahead }
  3000. if ((SourceRef.offset mod 16) = 8) and
  3001. (
  3002. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3003. (SourceRef.base = current_procinfo.framepointer) or
  3004. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3005. ) then
  3006. taicpu(p).opcode := MovAligned
  3007. else
  3008. taicpu(p).opcode := MovUnaligned;
  3009. taicpu(p).opsize := S_XMM;
  3010. taicpu(p).oper[1]^.reg := CurrentReg;
  3011. if ((TargetRef.offset mod 16) = 8) and
  3012. (
  3013. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3014. (TargetRef.base = current_procinfo.framepointer) or
  3015. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3016. ) then
  3017. taicpu(hp1).opcode := MovAligned
  3018. else
  3019. taicpu(hp1).opcode := MovUnaligned;
  3020. taicpu(hp1).opsize := S_XMM;
  3021. taicpu(hp1).oper[0]^.reg := CurrentReg;
  3022. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3023. RemoveInstruction(hp2);
  3024. RemoveInstruction(hp3);
  3025. Result := True;
  3026. Exit;
  3027. end;
  3028. end;
  3029. end
  3030. else
  3031. begin
  3032. { See if the next references are 8 less rather than 8 greater }
  3033. Dec(SourceRef.offset, 16); { -8 the other way }
  3034. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3035. begin
  3036. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3037. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3038. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3039. GetNextInstruction(hp2, hp3) and
  3040. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3041. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3042. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3043. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3044. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3045. begin
  3046. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3047. if CurrentReg <> NR_NO then
  3048. begin
  3049. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3050. if ((SourceRef.offset mod 16) = 0) and
  3051. (
  3052. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3053. (SourceRef.base = current_procinfo.framepointer) or
  3054. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3055. ) then
  3056. taicpu(hp2).opcode := MovAligned
  3057. else
  3058. taicpu(hp2).opcode := MovUnaligned;
  3059. taicpu(hp2).opsize := S_XMM;
  3060. taicpu(hp2).oper[1]^.reg := CurrentReg;
  3061. if ((TargetRef.offset mod 16) = 0) and
  3062. (
  3063. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3064. (TargetRef.base = current_procinfo.framepointer) or
  3065. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3066. ) then
  3067. taicpu(hp3).opcode := MovAligned
  3068. else
  3069. taicpu(hp3).opcode := MovUnaligned;
  3070. taicpu(hp3).opsize := S_XMM;
  3071. taicpu(hp3).oper[0]^.reg := CurrentReg;
  3072. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3073. RemoveInstruction(hp1);
  3074. RemoveCurrentP(p, hp2);
  3075. Result := True;
  3076. Exit;
  3077. end;
  3078. end;
  3079. end;
  3080. end;
  3081. end;
  3082. {$endif x86_64}
  3083. end;
  3084. else
  3085. { The write target should be a reg or a ref }
  3086. InternalError(2021091601);
  3087. end;
  3088. else
  3089. ;
  3090. end
  3091. else
  3092. { %treg is used afterwards, but all eventualities
  3093. other than the first MOV instruction being a constant
  3094. are covered by DeepMOVOpt, so only check for that }
  3095. if (taicpu(p).oper[0]^.typ = top_const) and
  3096. (
  3097. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3098. not (cs_opt_size in current_settings.optimizerswitches) or
  3099. (taicpu(hp1).opsize = S_B)
  3100. ) and
  3101. (
  3102. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3103. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3104. ) then
  3105. begin
  3106. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3107. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3108. end;
  3109. end;
  3110. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3111. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3112. { mov reg1, mem1 or mov mem1, reg1
  3113. mov mem2, reg2 mov reg2, mem2}
  3114. begin
  3115. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3116. { mov reg1, mem1 or mov mem1, reg1
  3117. mov mem2, reg1 mov reg2, mem1}
  3118. begin
  3119. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3120. { Removes the second statement from
  3121. mov reg1, mem1/reg2
  3122. mov mem1/reg2, reg1 }
  3123. begin
  3124. if taicpu(p).oper[0]^.typ=top_reg then
  3125. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3126. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3127. RemoveInstruction(hp1);
  3128. Result:=true;
  3129. exit;
  3130. end
  3131. else
  3132. begin
  3133. TransferUsedRegs(TmpUsedRegs);
  3134. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3135. if (taicpu(p).oper[1]^.typ = top_ref) and
  3136. { mov reg1, mem1
  3137. mov mem2, reg1 }
  3138. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3139. GetNextInstruction(hp1, hp2) and
  3140. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3141. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3142. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3143. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3144. { change to
  3145. mov reg1, mem1 mov reg1, mem1
  3146. mov mem2, reg1 cmp reg1, mem2
  3147. cmp mem1, reg1
  3148. }
  3149. begin
  3150. RemoveInstruction(hp2);
  3151. taicpu(hp1).opcode := A_CMP;
  3152. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3153. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3154. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3155. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3156. end;
  3157. end;
  3158. end
  3159. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3160. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3161. begin
  3162. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3163. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3164. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3165. end
  3166. else
  3167. begin
  3168. TransferUsedRegs(TmpUsedRegs);
  3169. if GetNextInstruction(hp1, hp2) and
  3170. MatchOpType(taicpu(p),top_ref,top_reg) and
  3171. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3172. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3173. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3174. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3175. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3176. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3177. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3178. { mov mem1, %reg1
  3179. mov %reg1, mem2
  3180. mov mem2, reg2
  3181. to:
  3182. mov mem1, reg2
  3183. mov reg2, mem2}
  3184. begin
  3185. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3186. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3187. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3188. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3189. RemoveInstruction(hp2);
  3190. Result := True;
  3191. end
  3192. {$ifdef i386}
  3193. { this is enabled for i386 only, as the rules to create the reg sets below
  3194. are too complicated for x86-64, so this makes this code too error prone
  3195. on x86-64
  3196. }
  3197. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3198. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3199. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3200. { mov mem1, reg1 mov mem1, reg1
  3201. mov reg1, mem2 mov reg1, mem2
  3202. mov mem2, reg2 mov mem2, reg1
  3203. to: to:
  3204. mov mem1, reg1 mov mem1, reg1
  3205. mov mem1, reg2 mov reg1, mem2
  3206. mov reg1, mem2
  3207. or (if mem1 depends on reg1
  3208. and/or if mem2 depends on reg2)
  3209. to:
  3210. mov mem1, reg1
  3211. mov reg1, mem2
  3212. mov reg1, reg2
  3213. }
  3214. begin
  3215. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3216. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3217. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3218. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3219. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3220. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3221. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3222. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3223. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3224. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3225. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3226. end
  3227. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3228. begin
  3229. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3230. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3231. end
  3232. else
  3233. begin
  3234. RemoveInstruction(hp2);
  3235. end
  3236. {$endif i386}
  3237. ;
  3238. end;
  3239. end
  3240. { movl [mem1],reg1
  3241. movl [mem1],reg2
  3242. to
  3243. movl [mem1],reg1
  3244. movl reg1,reg2
  3245. }
  3246. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3247. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3248. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3249. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3250. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3251. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3252. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3253. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3254. begin
  3255. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3256. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3257. end;
  3258. { movl const1,[mem1]
  3259. movl [mem1],reg1
  3260. to
  3261. movl const1,reg1
  3262. movl reg1,[mem1]
  3263. }
  3264. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3265. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3266. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3267. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3268. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3269. begin
  3270. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3271. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3272. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3273. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3274. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3275. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3276. Result:=true;
  3277. exit;
  3278. end;
  3279. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3280. { Change:
  3281. movl %reg1,%reg2
  3282. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3283. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3284. To:
  3285. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3286. movl x(%reg1),%reg1
  3287. movl %reg1,%regX
  3288. }
  3289. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3290. begin
  3291. CurrentReg := taicpu(p).oper[0]^.reg;
  3292. ActiveReg := taicpu(p).oper[1]^.reg;
  3293. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3294. (taicpu(hp1).oper[1]^.reg = CurrentReg) and
  3295. RegInRef(CurrentReg, taicpu(hp1).oper[0]^.ref^) and
  3296. GetNextInstruction(hp1, hp2) and
  3297. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3298. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3299. begin
  3300. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3301. if RegInRef(ActiveReg, SourceRef) and
  3302. { If %reg1 also appears in the second reference, then it will
  3303. not refer to the same memory block as the first reference }
  3304. not RegInRef(CurrentReg, SourceRef) then
  3305. begin
  3306. { Check to see if the references match if %reg2 is changed to %reg1 }
  3307. if SourceRef.base = ActiveReg then
  3308. SourceRef.base := CurrentReg;
  3309. if SourceRef.index = ActiveReg then
  3310. SourceRef.index := CurrentReg;
  3311. { RefsEqual also checks to ensure both references are non-volatile }
  3312. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3313. begin
  3314. taicpu(hp2).loadreg(0, CurrentReg);
  3315. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3316. Result := True;
  3317. if taicpu(hp2).oper[1]^.reg = ActiveReg then
  3318. begin
  3319. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3320. RemoveCurrentP(p, hp1);
  3321. Exit;
  3322. end
  3323. else
  3324. begin
  3325. { Check to see if %reg2 is no longer in use }
  3326. TransferUsedRegs(TmpUsedRegs);
  3327. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3328. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3329. if not RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs) then
  3330. begin
  3331. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3332. RemoveCurrentP(p, hp1);
  3333. Exit;
  3334. end;
  3335. end;
  3336. { If we reach this point, p and hp1 weren't actually modified,
  3337. so we can do a bit more work on this pass }
  3338. end;
  3339. end;
  3340. end;
  3341. end;
  3342. end;
  3343. { search further than the next instruction for a mov (as long as it's not a jump) }
  3344. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3345. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3346. (taicpu(p).oper[1]^.typ = top_reg) and
  3347. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3348. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3349. begin
  3350. { we work with hp2 here, so hp1 can be still used later on when
  3351. checking for GetNextInstruction_p }
  3352. hp3 := hp1;
  3353. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3354. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3355. { Saves on a large number of dereferences }
  3356. ActiveReg := taicpu(p).oper[1]^.reg;
  3357. TransferUsedRegs(TmpUsedRegs);
  3358. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3359. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3360. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3361. (hp2.typ=ait_instruction) do
  3362. begin
  3363. case taicpu(hp2).opcode of
  3364. A_POP:
  3365. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3366. begin
  3367. if not CrossJump and
  3368. not RegUsedBetween(ActiveReg, p, hp2) then
  3369. begin
  3370. { We can remove the original MOV since the register
  3371. wasn't used between it and its popping from the stack }
  3372. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3373. RemoveCurrentp(p, hp1);
  3374. Result := True;
  3375. Exit;
  3376. end;
  3377. { Can't go any further }
  3378. Break;
  3379. end;
  3380. A_MOV:
  3381. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3382. ((taicpu(p).oper[0]^.typ=top_const) or
  3383. ((taicpu(p).oper[0]^.typ=top_reg) and
  3384. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3385. )
  3386. ) then
  3387. begin
  3388. { we have
  3389. mov x, %treg
  3390. mov %treg, y
  3391. }
  3392. { We don't need to call UpdateUsedRegs for every instruction between
  3393. p and hp2 because the register we're concerned about will not
  3394. become deallocated (otherwise GetNextInstructionUsingReg would
  3395. have stopped at an earlier instruction). [Kit] }
  3396. TempRegUsed :=
  3397. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3398. RegReadByInstruction(ActiveReg, hp3) or
  3399. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3400. case taicpu(p).oper[0]^.typ Of
  3401. top_reg:
  3402. begin
  3403. { change
  3404. mov %reg, %treg
  3405. mov %treg, y
  3406. to
  3407. mov %reg, y
  3408. }
  3409. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3410. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3411. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3412. begin
  3413. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3414. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3415. if TempRegUsed then
  3416. begin
  3417. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3418. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3419. { Set the start of the next GetNextInstructionUsingRegCond search
  3420. to start at the entry right before hp2 (which is about to be removed) }
  3421. hp3 := tai(hp2.Previous);
  3422. RemoveInstruction(hp2);
  3423. { See if there's more we can optimise }
  3424. Continue;
  3425. end
  3426. else
  3427. begin
  3428. RemoveInstruction(hp2);
  3429. { We can remove the original MOV too }
  3430. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3431. RemoveCurrentP(p, hp1);
  3432. Result:=true;
  3433. Exit;
  3434. end;
  3435. end
  3436. else
  3437. begin
  3438. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3439. taicpu(hp2).loadReg(0, CurrentReg);
  3440. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3441. { Check to see if the register also appears in the reference }
  3442. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3443. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3444. { Don't remove the first instruction if the temporary register is in use }
  3445. if not TempRegUsed and
  3446. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3447. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3448. begin
  3449. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3450. RemoveCurrentP(p, hp1);
  3451. Result:=true;
  3452. Exit;
  3453. end;
  3454. { No need to set Result to True here. If there's another instruction later
  3455. on that can be optimised, it will be detected when the main Pass 1 loop
  3456. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3457. end;
  3458. end;
  3459. top_const:
  3460. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3461. begin
  3462. { change
  3463. mov const, %treg
  3464. mov %treg, y
  3465. to
  3466. mov const, y
  3467. }
  3468. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3469. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3470. begin
  3471. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3472. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3473. if TempRegUsed then
  3474. begin
  3475. { Don't remove the first instruction if the temporary register is in use }
  3476. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3477. { No need to set Result to True. If there's another instruction later on
  3478. that can be optimised, it will be detected when the main Pass 1 loop
  3479. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3480. end
  3481. else
  3482. begin
  3483. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3484. RemoveCurrentP(p, hp1);
  3485. Result:=true;
  3486. Exit;
  3487. end;
  3488. end;
  3489. end;
  3490. else
  3491. Internalerror(2019103001);
  3492. end;
  3493. end
  3494. else
  3495. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3496. begin
  3497. if not CrossJump and
  3498. not RegUsedBetween(ActiveReg, p, hp2) and
  3499. not RegReadByInstruction(ActiveReg, hp2) then
  3500. begin
  3501. { Register is not used before it is overwritten }
  3502. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3503. RemoveCurrentp(p, hp1);
  3504. Result := True;
  3505. Exit;
  3506. end;
  3507. if (taicpu(p).oper[0]^.typ = top_const) and
  3508. (taicpu(hp2).oper[0]^.typ = top_const) then
  3509. begin
  3510. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3511. begin
  3512. { Same value - register hasn't changed }
  3513. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3514. RemoveInstruction(hp2);
  3515. Result := True;
  3516. { See if there's more we can optimise }
  3517. Continue;
  3518. end;
  3519. end;
  3520. end;
  3521. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3522. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3523. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3524. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3525. begin
  3526. {
  3527. Change from:
  3528. mov ###, %reg
  3529. ...
  3530. movs/z %reg,%reg (Same register, just different sizes)
  3531. To:
  3532. movs/z ###, %reg (Longer version)
  3533. ...
  3534. (remove)
  3535. }
  3536. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3537. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3538. { Keep the first instruction as mov if ### is a constant }
  3539. if taicpu(p).oper[0]^.typ = top_const then
  3540. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3541. else
  3542. begin
  3543. taicpu(p).opcode := taicpu(hp2).opcode;
  3544. taicpu(p).opsize := taicpu(hp2).opsize;
  3545. end;
  3546. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3547. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3548. RemoveInstruction(hp2);
  3549. Result := True;
  3550. Exit;
  3551. end;
  3552. else
  3553. { Move down to the MatchOpType if-block below };
  3554. end;
  3555. { Also catches MOV/S/Z instructions that aren't modified }
  3556. if taicpu(p).oper[0]^.typ = top_reg then
  3557. begin
  3558. CurrentReg := taicpu(p).oper[0]^.reg;
  3559. if
  3560. not RegModifiedByInstruction(CurrentReg, hp3) and
  3561. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3562. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3563. begin
  3564. Result := True;
  3565. { Just in case something didn't get modified (e.g. an
  3566. implicit register). Also, if it does read from this
  3567. register, then there's no longer an advantage to
  3568. changing the register on subsequent instructions.}
  3569. if not RegReadByInstruction(ActiveReg, hp2) then
  3570. begin
  3571. { If a conditional jump was crossed, do not delete
  3572. the original MOV no matter what }
  3573. if not CrossJump and
  3574. { RegEndOfLife returns True if the register is
  3575. deallocated before the next instruction or has
  3576. been loaded with a new value }
  3577. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3578. begin
  3579. { We can remove the original MOV }
  3580. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3581. RemoveCurrentp(p, hp1);
  3582. Exit;
  3583. end;
  3584. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3585. begin
  3586. { See if there's more we can optimise }
  3587. hp3 := hp2;
  3588. Continue;
  3589. end;
  3590. end;
  3591. end;
  3592. end;
  3593. { Break out of the while loop under normal circumstances }
  3594. Break;
  3595. end;
  3596. end;
  3597. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3598. (taicpu(p).oper[1]^.typ = top_reg) and
  3599. (taicpu(p).opsize = S_L) and
  3600. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3601. (taicpu(hp2).opcode = A_AND) and
  3602. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3603. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3604. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3605. ) then
  3606. begin
  3607. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3608. begin
  3609. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3610. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3611. begin
  3612. { Optimize out:
  3613. mov x, %reg
  3614. and ffffffffh, %reg
  3615. }
  3616. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3617. RemoveInstruction(hp2);
  3618. Result:=true;
  3619. exit;
  3620. end;
  3621. end;
  3622. end;
  3623. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3624. x >= RetOffset) as it doesn't do anything (it writes either to a
  3625. parameter or to the temporary storage room for the function
  3626. result)
  3627. }
  3628. if IsExitCode(hp1) and
  3629. (taicpu(p).oper[1]^.typ = top_ref) and
  3630. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3631. (
  3632. (
  3633. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3634. not (
  3635. assigned(current_procinfo.procdef.funcretsym) and
  3636. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3637. )
  3638. ) or
  3639. { Also discard writes to the stack that are below the base pointer,
  3640. as this is temporary storage rather than a function result on the
  3641. stack, say. }
  3642. (
  3643. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3644. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3645. )
  3646. ) then
  3647. begin
  3648. RemoveCurrentp(p, hp1);
  3649. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3650. RemoveLastDeallocForFuncRes(p);
  3651. Result:=true;
  3652. exit;
  3653. end;
  3654. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3655. begin
  3656. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3657. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3658. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3659. begin
  3660. { change
  3661. mov reg1, mem1
  3662. test/cmp x, mem1
  3663. to
  3664. mov reg1, mem1
  3665. test/cmp x, reg1
  3666. }
  3667. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3668. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3669. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3670. Result := True;
  3671. Exit;
  3672. end;
  3673. if DoMovCmpMemOpt(p, hp1, True) then
  3674. begin
  3675. Result := True;
  3676. Exit;
  3677. end;
  3678. end;
  3679. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3680. { If the flags register is in use, don't change the instruction to an
  3681. ADD otherwise this will scramble the flags. [Kit] }
  3682. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3683. begin
  3684. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3685. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3686. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3687. ) or
  3688. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3689. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3690. )
  3691. ) then
  3692. { mov reg1,ref
  3693. lea reg2,[reg1,reg2]
  3694. to
  3695. add reg2,ref}
  3696. begin
  3697. TransferUsedRegs(TmpUsedRegs);
  3698. { reg1 may not be used afterwards }
  3699. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3700. begin
  3701. Taicpu(hp1).opcode:=A_ADD;
  3702. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3703. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3704. RemoveCurrentp(p, hp1);
  3705. result:=true;
  3706. exit;
  3707. end;
  3708. end;
  3709. { If the LEA instruction can be converted into an arithmetic instruction,
  3710. it may be possible to then fold it in the next optimisation, otherwise
  3711. there's nothing more that can be optimised here. }
  3712. if not ConvertLEA(taicpu(hp1)) then
  3713. Exit;
  3714. end;
  3715. if (taicpu(p).oper[1]^.typ = top_reg) and
  3716. (hp1.typ = ait_instruction) and
  3717. GetNextInstruction(hp1, hp2) and
  3718. MatchInstruction(hp2,A_MOV,[]) and
  3719. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3720. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3721. (
  3722. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3723. {$ifdef x86_64}
  3724. or
  3725. (
  3726. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3727. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3728. )
  3729. {$endif x86_64}
  3730. ) then
  3731. begin
  3732. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3733. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3734. { change movsX/movzX reg/ref, reg2
  3735. add/sub/or/... reg3/$const, reg2
  3736. mov reg2 reg/ref
  3737. dealloc reg2
  3738. to
  3739. add/sub/or/... reg3/$const, reg/ref }
  3740. begin
  3741. TransferUsedRegs(TmpUsedRegs);
  3742. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3743. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3744. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3745. begin
  3746. { by example:
  3747. movswl %si,%eax movswl %si,%eax p
  3748. decl %eax addl %edx,%eax hp1
  3749. movw %ax,%si movw %ax,%si hp2
  3750. ->
  3751. movswl %si,%eax movswl %si,%eax p
  3752. decw %eax addw %edx,%eax hp1
  3753. movw %ax,%si movw %ax,%si hp2
  3754. }
  3755. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3756. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3757. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3758. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3759. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3760. {
  3761. ->
  3762. movswl %si,%eax movswl %si,%eax p
  3763. decw %si addw %dx,%si hp1
  3764. movw %ax,%si movw %ax,%si hp2
  3765. }
  3766. case taicpu(hp1).ops of
  3767. 1:
  3768. begin
  3769. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3770. if taicpu(hp1).oper[0]^.typ=top_reg then
  3771. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3772. end;
  3773. 2:
  3774. begin
  3775. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3776. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3777. (taicpu(hp1).opcode<>A_SHL) and
  3778. (taicpu(hp1).opcode<>A_SHR) and
  3779. (taicpu(hp1).opcode<>A_SAR) then
  3780. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3781. end;
  3782. else
  3783. internalerror(2008042701);
  3784. end;
  3785. {
  3786. ->
  3787. decw %si addw %dx,%si p
  3788. }
  3789. RemoveInstruction(hp2);
  3790. RemoveCurrentP(p, hp1);
  3791. Result:=True;
  3792. Exit;
  3793. end;
  3794. end;
  3795. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3796. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3797. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3798. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3799. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3800. )
  3801. {$ifdef i386}
  3802. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3803. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3804. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3805. {$endif i386}
  3806. then
  3807. { change movsX/movzX reg/ref, reg2
  3808. add/sub/or/... regX/$const, reg2
  3809. mov reg2, reg3
  3810. dealloc reg2
  3811. to
  3812. movsX/movzX reg/ref, reg3
  3813. add/sub/or/... reg3/$const, reg3
  3814. }
  3815. begin
  3816. TransferUsedRegs(TmpUsedRegs);
  3817. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3818. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3819. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3820. begin
  3821. { by example:
  3822. movswl %si,%eax movswl %si,%eax p
  3823. decl %eax addl %edx,%eax hp1
  3824. movw %ax,%si movw %ax,%si hp2
  3825. ->
  3826. movswl %si,%eax movswl %si,%eax p
  3827. decw %eax addw %edx,%eax hp1
  3828. movw %ax,%si movw %ax,%si hp2
  3829. }
  3830. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3831. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3832. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3833. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3834. { limit size of constants as well to avoid assembler errors, but
  3835. check opsize to avoid overflow when left shifting the 1 }
  3836. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3837. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3838. {$ifdef x86_64}
  3839. { Be careful of, for example:
  3840. movl %reg1,%reg2
  3841. addl %reg3,%reg2
  3842. movq %reg2,%reg4
  3843. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3844. }
  3845. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3846. begin
  3847. taicpu(hp2).changeopsize(S_L);
  3848. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3849. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3850. end;
  3851. {$endif x86_64}
  3852. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3853. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3854. if taicpu(p).oper[0]^.typ=top_reg then
  3855. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3856. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3857. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3858. {
  3859. ->
  3860. movswl %si,%eax movswl %si,%eax p
  3861. decw %si addw %dx,%si hp1
  3862. movw %ax,%si movw %ax,%si hp2
  3863. }
  3864. case taicpu(hp1).ops of
  3865. 1:
  3866. begin
  3867. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3868. if taicpu(hp1).oper[0]^.typ=top_reg then
  3869. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3870. end;
  3871. 2:
  3872. begin
  3873. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3874. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3875. (taicpu(hp1).opcode<>A_SHL) and
  3876. (taicpu(hp1).opcode<>A_SHR) and
  3877. (taicpu(hp1).opcode<>A_SAR) then
  3878. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3879. end;
  3880. else
  3881. internalerror(2018111801);
  3882. end;
  3883. {
  3884. ->
  3885. decw %si addw %dx,%si p
  3886. }
  3887. RemoveInstruction(hp2);
  3888. end;
  3889. end;
  3890. end;
  3891. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3892. GetNextInstruction(hp1, hp2) and
  3893. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3894. MatchOperand(Taicpu(p).oper[0]^,0) and
  3895. (Taicpu(p).oper[1]^.typ = top_reg) and
  3896. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3897. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3898. { mov reg1,0
  3899. bts reg1,operand1 --> mov reg1,operand2
  3900. or reg1,operand2 bts reg1,operand1}
  3901. begin
  3902. Taicpu(hp2).opcode:=A_MOV;
  3903. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3904. asml.remove(hp1);
  3905. insertllitem(hp2,hp2.next,hp1);
  3906. RemoveCurrentp(p, hp1);
  3907. Result:=true;
  3908. exit;
  3909. end;
  3910. {
  3911. mov ref,reg0
  3912. <op> reg0,reg1
  3913. dealloc reg0
  3914. to
  3915. <op> ref,reg1
  3916. }
  3917. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3918. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3919. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3920. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3921. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3922. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3923. begin
  3924. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3925. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3926. RemoveCurrentp(p, hp1);
  3927. Result:=true;
  3928. exit;
  3929. end;
  3930. {$ifdef x86_64}
  3931. { Convert:
  3932. movq x(ref),%reg64
  3933. shrq y,%reg64
  3934. To:
  3935. movl x+4(ref),%reg32
  3936. shrl y-32,%reg32 (Remove if y = 32)
  3937. }
  3938. if (taicpu(p).opsize = S_Q) and
  3939. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3940. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3941. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3942. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3943. (taicpu(hp1).oper[0]^.val >= 32) and
  3944. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3945. begin
  3946. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3947. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3948. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3949. { Convert to 32-bit }
  3950. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3951. taicpu(p).opsize := S_L;
  3952. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3953. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3954. if (taicpu(hp1).oper[0]^.val = 32) then
  3955. begin
  3956. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3957. RemoveInstruction(hp1);
  3958. end
  3959. else
  3960. begin
  3961. { This will potentially open up more arithmetic operations since
  3962. the peephole optimizer now has a big hint that only the lower
  3963. 32 bits are currently in use (and opcodes are smaller in size) }
  3964. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3965. taicpu(hp1).opsize := S_L;
  3966. Dec(taicpu(hp1).oper[0]^.val, 32);
  3967. DebugMsg(SPeepholeOptimization + PreMessage +
  3968. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3969. end;
  3970. Result := True;
  3971. Exit;
  3972. end;
  3973. {$endif x86_64}
  3974. { Backward optimisation. If we have:
  3975. func. %reg1,%reg2
  3976. mov %reg2,%reg3
  3977. (dealloc %reg2)
  3978. Change to:
  3979. func. %reg1,%reg3 (see comment below for what a valid func. is)
  3980. }
  3981. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3982. begin
  3983. CurrentReg := taicpu(p).oper[0]^.reg;
  3984. ActiveReg := taicpu(p).oper[1]^.reg;
  3985. TransferUsedRegs(TmpUsedRegs);
  3986. if not RegUsedAfterInstruction(CurrentReg, p, TmpUsedRegs) and
  3987. GetLastInstruction(p, hp2) and
  3988. (hp2.typ = ait_instruction) and
  3989. { Have to make sure it's an instruction that only reads from
  3990. operand 1 and only writes (not reads or modifies) from operand 2;
  3991. in essence, a one-operand pure function such as BSR or POPCNT }
  3992. (taicpu(hp2).ops = 2) and
  3993. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  3994. (taicpu(hp2).oper[1]^.typ = top_reg) and
  3995. (taicpu(hp2).oper[1]^.reg = CurrentReg) then
  3996. begin
  3997. case taicpu(hp2).opcode of
  3998. A_FSTSW, A_FNSTSW,
  3999. A_IN, A_INS, A_OUT, A_OUTS,
  4000. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS,
  4001. { These routines have explicit operands, but they are restricted in
  4002. what they can be (e.g. IN and OUT can only read from AL, AX or
  4003. EAX. }
  4004. A_CMOVcc:
  4005. { CMOV is not valid either because then CurrentReg will depend
  4006. on an unknown value if the condition is False and hence is
  4007. not a pure write }
  4008. ;
  4009. else
  4010. begin
  4011. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  4012. taicpu(hp2).oper[1]^.reg := ActiveReg;
  4013. AllocRegBetween(ActiveReg, hp2, p, TmpUsedRegs);
  4014. RemoveCurrentp(p, hp1);
  4015. Result := True;
  4016. Exit;
  4017. end;
  4018. end;
  4019. end;
  4020. end;
  4021. end;
  4022. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4023. var
  4024. hp1 : tai;
  4025. begin
  4026. Result:=false;
  4027. if taicpu(p).ops <> 2 then
  4028. exit;
  4029. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4030. GetNextInstruction(p,hp1) then
  4031. begin
  4032. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4033. (taicpu(hp1).ops = 2) then
  4034. begin
  4035. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4036. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4037. { movXX reg1, mem1 or movXX mem1, reg1
  4038. movXX mem2, reg2 movXX reg2, mem2}
  4039. begin
  4040. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4041. { movXX reg1, mem1 or movXX mem1, reg1
  4042. movXX mem2, reg1 movXX reg2, mem1}
  4043. begin
  4044. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4045. begin
  4046. { Removes the second statement from
  4047. movXX reg1, mem1/reg2
  4048. movXX mem1/reg2, reg1
  4049. }
  4050. if taicpu(p).oper[0]^.typ=top_reg then
  4051. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4052. { Removes the second statement from
  4053. movXX mem1/reg1, reg2
  4054. movXX reg2, mem1/reg1
  4055. }
  4056. if (taicpu(p).oper[1]^.typ=top_reg) and
  4057. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4058. begin
  4059. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4060. RemoveInstruction(hp1);
  4061. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4062. Result:=true;
  4063. exit;
  4064. end
  4065. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4066. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4067. begin
  4068. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4069. RemoveInstruction(hp1);
  4070. Result:=true;
  4071. exit;
  4072. end;
  4073. end
  4074. end;
  4075. end;
  4076. end;
  4077. end;
  4078. end;
  4079. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4080. var
  4081. hp1 : tai;
  4082. begin
  4083. result:=false;
  4084. { replace
  4085. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4086. MovX %mreg2,%mreg1
  4087. dealloc %mreg2
  4088. by
  4089. <Op>X %mreg2,%mreg1
  4090. ?
  4091. }
  4092. if GetNextInstruction(p,hp1) and
  4093. { we mix single and double opperations here because we assume that the compiler
  4094. generates vmovapd only after double operations and vmovaps only after single operations }
  4095. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4096. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4097. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4098. (taicpu(p).oper[0]^.typ=top_reg) then
  4099. begin
  4100. TransferUsedRegs(TmpUsedRegs);
  4101. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4102. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4103. begin
  4104. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4105. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4106. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4107. RemoveInstruction(hp1);
  4108. result:=true;
  4109. end;
  4110. end;
  4111. end;
  4112. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4113. var
  4114. hp1, p_label, p_dist, hp1_dist: tai;
  4115. JumpLabel, JumpLabel_dist: TAsmLabel;
  4116. FirstValue, SecondValue: TCGInt;
  4117. begin
  4118. Result := False;
  4119. if (taicpu(p).oper[0]^.typ = top_const) and
  4120. (taicpu(p).oper[0]^.val <> -1) then
  4121. begin
  4122. { Convert unsigned maximum constants to -1 to aid optimisation }
  4123. case taicpu(p).opsize of
  4124. S_B:
  4125. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4126. begin
  4127. taicpu(p).oper[0]^.val := -1;
  4128. Result := True;
  4129. Exit;
  4130. end;
  4131. S_W:
  4132. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4133. begin
  4134. taicpu(p).oper[0]^.val := -1;
  4135. Result := True;
  4136. Exit;
  4137. end;
  4138. S_L:
  4139. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4140. begin
  4141. taicpu(p).oper[0]^.val := -1;
  4142. Result := True;
  4143. Exit;
  4144. end;
  4145. {$ifdef x86_64}
  4146. S_Q:
  4147. { Storing anything greater than $7FFFFFFF is not possible so do
  4148. nothing };
  4149. {$endif x86_64}
  4150. else
  4151. InternalError(2021121001);
  4152. end;
  4153. end;
  4154. if GetNextInstruction(p, hp1) and
  4155. TrySwapMovCmp(p, hp1) then
  4156. begin
  4157. Result := True;
  4158. Exit;
  4159. end;
  4160. { Search for:
  4161. test $x,(reg/ref)
  4162. jne @lbl1
  4163. test $y,(reg/ref) (same register or reference)
  4164. jne @lbl1
  4165. Change to:
  4166. test $(x or y),(reg/ref)
  4167. jne @lbl1
  4168. (Note, this doesn't work with je instead of jne)
  4169. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4170. Also search for:
  4171. test $x,(reg/ref)
  4172. je @lbl1
  4173. test $y,(reg/ref)
  4174. je/jne @lbl2
  4175. If (x or y) = x, then the second jump is deterministic
  4176. }
  4177. if (
  4178. (
  4179. (taicpu(p).oper[0]^.typ = top_const) or
  4180. (
  4181. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4182. (taicpu(p).oper[0]^.typ = top_reg) and
  4183. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4184. )
  4185. ) and
  4186. MatchInstruction(hp1, A_JCC, [])
  4187. ) then
  4188. begin
  4189. if (taicpu(p).oper[0]^.typ = top_reg) and
  4190. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4191. FirstValue := -1
  4192. else
  4193. FirstValue := taicpu(p).oper[0]^.val;
  4194. { If we have several test/jne's in a row, it might be the case that
  4195. the second label doesn't go to the same location, but the one
  4196. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4197. so accommodate for this with a while loop.
  4198. }
  4199. hp1_dist := hp1;
  4200. if GetNextInstruction(hp1, p_dist) and
  4201. (p_dist.typ = ait_instruction) and
  4202. (
  4203. (
  4204. (taicpu(p_dist).opcode = A_TEST) and
  4205. (
  4206. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4207. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4208. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4209. )
  4210. ) or
  4211. (
  4212. { cmp 0,%reg = test %reg,%reg }
  4213. (taicpu(p_dist).opcode = A_CMP) and
  4214. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4215. )
  4216. ) and
  4217. { Make sure the destination operands are actually the same }
  4218. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4219. GetNextInstruction(p_dist, hp1_dist) and
  4220. MatchInstruction(hp1_dist, A_JCC, []) then
  4221. begin
  4222. if
  4223. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4224. (
  4225. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4226. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4227. ) then
  4228. SecondValue := -1
  4229. else
  4230. SecondValue := taicpu(p_dist).oper[0]^.val;
  4231. { If both of the TEST constants are identical, delete the second
  4232. TEST that is unnecessary. }
  4233. if (FirstValue = SecondValue) then
  4234. begin
  4235. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4236. RemoveInstruction(p_dist);
  4237. { Don't let the flags register become deallocated and reallocated between the jumps }
  4238. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4239. Result := True;
  4240. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4241. begin
  4242. { Since the second jump's condition is a subset of the first, we
  4243. know it will never branch because the first jump dominates it.
  4244. Get it out of the way now rather than wait for the jump
  4245. optimisations for a speed boost. }
  4246. if IsJumpToLabel(taicpu(hp1_dist)) then
  4247. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4248. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4249. RemoveInstruction(hp1_dist);
  4250. end
  4251. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4252. begin
  4253. { If the inverse of the first condition is a subset of the second,
  4254. the second one will definitely branch if the first one doesn't }
  4255. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4256. MakeUnconditional(taicpu(hp1_dist));
  4257. RemoveDeadCodeAfterJump(hp1_dist);
  4258. end;
  4259. Exit;
  4260. end;
  4261. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4262. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4263. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4264. then the second jump will never branch, so it can also be
  4265. removed regardless of where it goes }
  4266. (
  4267. (FirstValue = -1) or
  4268. (SecondValue = -1) or
  4269. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4270. ) then
  4271. begin
  4272. { Same jump location... can be a register since nothing's changed }
  4273. { If any of the entries are equivalent to test %reg,%reg, then the
  4274. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4275. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4276. if IsJumpToLabel(taicpu(hp1_dist)) then
  4277. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4278. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4279. RemoveInstruction(hp1_dist);
  4280. { Only remove the second test if no jumps or other conditional instructions follow }
  4281. TransferUsedRegs(TmpUsedRegs);
  4282. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4283. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4284. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4285. RemoveInstruction(p_dist);
  4286. Result := True;
  4287. Exit;
  4288. end;
  4289. end;
  4290. end;
  4291. { Search for:
  4292. test %reg,%reg
  4293. j(c1) @lbl1
  4294. ...
  4295. @lbl:
  4296. test %reg,%reg (same register)
  4297. j(c2) @lbl2
  4298. If c2 is a subset of c1, change to:
  4299. test %reg,%reg
  4300. j(c1) @lbl2
  4301. (@lbl1 may become a dead label as a result)
  4302. }
  4303. if (taicpu(p).oper[1]^.typ = top_reg) and
  4304. (taicpu(p).oper[0]^.typ = top_reg) and
  4305. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4306. MatchInstruction(hp1, A_JCC, []) and
  4307. IsJumpToLabel(taicpu(hp1)) then
  4308. begin
  4309. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4310. p_label := nil;
  4311. if Assigned(JumpLabel) then
  4312. p_label := getlabelwithsym(JumpLabel);
  4313. if Assigned(p_label) and
  4314. GetNextInstruction(p_label, p_dist) and
  4315. MatchInstruction(p_dist, A_TEST, []) and
  4316. { It's fine if the second test uses smaller sub-registers }
  4317. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4318. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4319. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4320. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4321. GetNextInstruction(p_dist, hp1_dist) and
  4322. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4323. begin
  4324. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4325. if JumpLabel = JumpLabel_dist then
  4326. { This is an infinite loop }
  4327. Exit;
  4328. { Best optimisation when the first condition is a subset (or equal) of the second }
  4329. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4330. begin
  4331. { Any registers used here will already be allocated }
  4332. if Assigned(JumpLabel_dist) then
  4333. JumpLabel_dist.IncRefs;
  4334. if Assigned(JumpLabel) then
  4335. JumpLabel.DecRefs;
  4336. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4337. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4338. Result := True;
  4339. Exit;
  4340. end;
  4341. end;
  4342. end;
  4343. end;
  4344. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4345. var
  4346. hp1, hp2: tai;
  4347. ActiveReg: TRegister;
  4348. OldOffset: asizeint;
  4349. ThisConst: TCGInt;
  4350. function RegDeallocated: Boolean;
  4351. begin
  4352. TransferUsedRegs(TmpUsedRegs);
  4353. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4354. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4355. end;
  4356. begin
  4357. result:=false;
  4358. hp1 := nil;
  4359. { replace
  4360. addX const,%reg1
  4361. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4362. dealloc %reg1
  4363. by
  4364. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4365. }
  4366. if MatchOpType(taicpu(p),top_const,top_reg) then
  4367. begin
  4368. ActiveReg := taicpu(p).oper[1]^.reg;
  4369. { Ensures the entire register was updated }
  4370. if (taicpu(p).opsize >= S_L) and
  4371. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4372. MatchInstruction(hp1,A_LEA,[]) and
  4373. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4374. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4375. (
  4376. { Cover the case where the register in the reference is also the destination register }
  4377. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4378. (
  4379. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4380. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4381. RegDeallocated
  4382. )
  4383. ) then
  4384. begin
  4385. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4386. {$push}
  4387. {$R-}{$Q-}
  4388. { Explicitly disable overflow checking for these offset calculation
  4389. as those do not matter for the final result }
  4390. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4391. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4392. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4393. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4394. {$pop}
  4395. {$ifdef x86_64}
  4396. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4397. begin
  4398. { Overflow; abort }
  4399. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4400. end
  4401. else
  4402. {$endif x86_64}
  4403. begin
  4404. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4405. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4406. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4407. RemoveCurrentP(p, hp1)
  4408. else
  4409. RemoveCurrentP(p);
  4410. result:=true;
  4411. Exit;
  4412. end;
  4413. end;
  4414. if (
  4415. { Save calling GetNextInstructionUsingReg again }
  4416. Assigned(hp1) or
  4417. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4418. ) and
  4419. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4420. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4421. begin
  4422. if taicpu(hp1).oper[0]^.typ = top_const then
  4423. begin
  4424. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4425. if taicpu(hp1).opcode = A_ADD then
  4426. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4427. else
  4428. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4429. Result := True;
  4430. { Handle any overflows }
  4431. case taicpu(p).opsize of
  4432. S_B:
  4433. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4434. S_W:
  4435. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4436. S_L:
  4437. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4438. {$ifdef x86_64}
  4439. S_Q:
  4440. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4441. { Overflow; abort }
  4442. Result := False
  4443. else
  4444. taicpu(p).oper[0]^.val := ThisConst;
  4445. {$endif x86_64}
  4446. else
  4447. InternalError(2021102610);
  4448. end;
  4449. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4450. if Result then
  4451. begin
  4452. if (taicpu(p).oper[0]^.val < 0) and
  4453. (
  4454. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4455. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4456. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4457. ) then
  4458. begin
  4459. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4460. taicpu(p).opcode := A_SUB;
  4461. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4462. end
  4463. else
  4464. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4465. RemoveInstruction(hp1);
  4466. end;
  4467. end
  4468. else
  4469. begin
  4470. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4471. TransferUsedRegs(TmpUsedRegs);
  4472. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4473. hp2 := p;
  4474. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4475. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4476. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4477. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4478. begin
  4479. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4480. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4481. Asml.Remove(p);
  4482. Asml.InsertAfter(p, hp1);
  4483. p := hp1;
  4484. Result := True;
  4485. end;
  4486. end;
  4487. end;
  4488. end;
  4489. end;
  4490. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4491. var
  4492. hp1: tai;
  4493. ref: Integer;
  4494. saveref: treference;
  4495. Multiple: TCGInt;
  4496. begin
  4497. Result:=false;
  4498. { play save and throw an error if LEA uses a seg register prefix,
  4499. this is most likely an error somewhere else }
  4500. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4501. internalerror(2022022001);
  4502. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4503. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4504. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4505. (
  4506. { do not mess with leas accessing the stack pointer
  4507. unless it's a null operation }
  4508. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4509. (
  4510. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4511. (taicpu(p).oper[0]^.ref^.offset = 0)
  4512. )
  4513. ) and
  4514. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4515. begin
  4516. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4517. begin
  4518. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4519. begin
  4520. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4521. taicpu(p).oper[1]^.reg);
  4522. InsertLLItem(p.previous,p.next, hp1);
  4523. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4524. p.free;
  4525. p:=hp1;
  4526. end
  4527. else
  4528. begin
  4529. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4530. RemoveCurrentP(p);
  4531. end;
  4532. Result:=true;
  4533. exit;
  4534. end
  4535. else if (
  4536. { continue to use lea to adjust the stack pointer,
  4537. it is the recommended way, but only if not optimizing for size }
  4538. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4539. (cs_opt_size in current_settings.optimizerswitches)
  4540. ) and
  4541. { If the flags register is in use, don't change the instruction
  4542. to an ADD otherwise this will scramble the flags. [Kit] }
  4543. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4544. ConvertLEA(taicpu(p)) then
  4545. begin
  4546. Result:=true;
  4547. exit;
  4548. end;
  4549. end;
  4550. { Don't optimise if the stack or frame pointer is the destination register }
  4551. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  4552. Exit;
  4553. if GetNextInstruction(p,hp1) and
  4554. (hp1.typ=ait_instruction) then
  4555. begin
  4556. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4557. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4558. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  4559. begin
  4560. TransferUsedRegs(TmpUsedRegs);
  4561. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4562. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4563. begin
  4564. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4565. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4566. RemoveInstruction(hp1);
  4567. result:=true;
  4568. exit;
  4569. end;
  4570. end;
  4571. { changes
  4572. lea <ref1>, reg1
  4573. <op> ...,<ref. with reg1>,...
  4574. to
  4575. <op> ...,<ref1>,... }
  4576. { find a reference which uses reg1 }
  4577. 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
  4578. ref:=0
  4579. 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
  4580. ref:=1
  4581. else
  4582. ref:=-1;
  4583. if (ref<>-1) and
  4584. { reg1 must be either the base or the index }
  4585. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4586. begin
  4587. { reg1 can be removed from the reference }
  4588. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4589. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4590. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4591. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4592. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4593. else
  4594. Internalerror(2019111201);
  4595. { check if the can insert all data of the lea into the second instruction }
  4596. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4597. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4598. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4599. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4600. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4601. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4602. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4603. {$ifdef x86_64}
  4604. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4605. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4606. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4607. )
  4608. {$endif x86_64}
  4609. then
  4610. begin
  4611. { reg1 might not used by the second instruction after it is remove from the reference }
  4612. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4613. begin
  4614. TransferUsedRegs(TmpUsedRegs);
  4615. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4616. { reg1 is not updated so it might not be used afterwards }
  4617. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4618. begin
  4619. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4620. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4621. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4622. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4623. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4624. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4625. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4626. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4627. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4628. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4629. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4630. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4631. RemoveCurrentP(p, hp1);
  4632. result:=true;
  4633. exit;
  4634. end
  4635. end;
  4636. end;
  4637. { recover }
  4638. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4639. end;
  4640. if RegInInstruction(DestinationReg, hp1) or
  4641. { Check further ahead (up to 2 instructions ahead for -O2) }
  4642. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  4643. begin
  4644. { Check common LEA/LEA conditions }
  4645. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4646. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4647. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4648. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4649. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4650. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4651. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4652. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4653. (
  4654. (
  4655. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4656. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4657. ) and (
  4658. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4659. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4660. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4661. )
  4662. ) then
  4663. begin
  4664. { changes
  4665. lea (regX,scale), reg1
  4666. lea offset(reg1,reg1), reg1
  4667. to
  4668. lea offset(regX,scale*2), reg1
  4669. and
  4670. lea (regX,scale1), reg1
  4671. lea offset(reg1,scale2), reg1
  4672. to
  4673. lea offset(regX,scale1*scale2), reg1
  4674. ... so long as the final scale does not exceed 8
  4675. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4676. }
  4677. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  4678. (taicpu(p).oper[0]^.ref^.offset = 0) and
  4679. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4680. (
  4681. (
  4682. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4683. ) or (
  4684. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4685. (
  4686. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4687. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4688. )
  4689. )
  4690. ) and (
  4691. (
  4692. { lea (reg1,scale2), reg1 variant }
  4693. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4694. (
  4695. (
  4696. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4697. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4698. ) or (
  4699. { lea (regX,regX), reg1 variant }
  4700. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4701. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4702. )
  4703. )
  4704. ) or (
  4705. { lea (reg1,reg1), reg1 variant }
  4706. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4707. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4708. )
  4709. ) then
  4710. begin
  4711. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4712. { Make everything homogeneous to make calculations easier }
  4713. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4714. begin
  4715. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4716. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4717. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4718. else
  4719. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4720. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4721. end;
  4722. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4723. begin
  4724. { Just to prevent miscalculations }
  4725. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4726. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4727. else
  4728. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4729. end
  4730. else
  4731. begin
  4732. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4733. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4734. end;
  4735. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4736. RemoveCurrentP(p);
  4737. result:=true;
  4738. exit;
  4739. end
  4740. { changes
  4741. lea offset1(regX), reg1
  4742. lea offset2(reg1), reg1
  4743. to
  4744. lea offset1+offset2(regX), reg1 }
  4745. else if
  4746. (
  4747. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4748. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4749. ) or (
  4750. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4751. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4752. (
  4753. (
  4754. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4755. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4756. ) or (
  4757. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4758. (
  4759. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4760. (
  4761. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4762. (
  4763. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4764. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4765. )
  4766. )
  4767. )
  4768. )
  4769. )
  4770. ) then
  4771. begin
  4772. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4773. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4774. begin
  4775. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4776. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4777. { if the register is used as index and base, we have to increase for base as well
  4778. and adapt base }
  4779. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4780. begin
  4781. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4782. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4783. end;
  4784. end
  4785. else
  4786. begin
  4787. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4788. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4789. end;
  4790. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4791. begin
  4792. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4793. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4794. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4795. end;
  4796. RemoveCurrentP(p);
  4797. result:=true;
  4798. exit;
  4799. end;
  4800. end;
  4801. { Change:
  4802. leal/q $x(%reg1),%reg2
  4803. ...
  4804. shll/q $y,%reg2
  4805. To:
  4806. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4807. }
  4808. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  4809. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4810. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4811. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  4812. (taicpu(hp1).oper[0]^.val <= 3) then
  4813. begin
  4814. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4815. TransferUsedRegs(TmpUsedRegs);
  4816. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4817. if
  4818. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4819. (this works even if scalefactor is zero) }
  4820. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4821. { Ensure offset doesn't go out of bounds }
  4822. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4823. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4824. (
  4825. (
  4826. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  4827. (
  4828. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4829. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4830. (
  4831. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4832. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4833. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4834. )
  4835. )
  4836. ) or (
  4837. (
  4838. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4839. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4840. ) and
  4841. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  4842. )
  4843. ) then
  4844. begin
  4845. repeat
  4846. with taicpu(p).oper[0]^.ref^ do
  4847. begin
  4848. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4849. if index = base then
  4850. begin
  4851. if Multiple > 4 then
  4852. { Optimisation will no longer work because resultant
  4853. scale factor will exceed 8 }
  4854. Break;
  4855. base := NR_NO;
  4856. scalefactor := 2;
  4857. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4858. end
  4859. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4860. begin
  4861. { Scale factor only works on the index register }
  4862. index := base;
  4863. base := NR_NO;
  4864. end;
  4865. { For safety }
  4866. if scalefactor <= 1 then
  4867. begin
  4868. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4869. scalefactor := Multiple;
  4870. end
  4871. else
  4872. begin
  4873. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4874. scalefactor := scalefactor * Multiple;
  4875. end;
  4876. offset := offset * Multiple;
  4877. end;
  4878. RemoveInstruction(hp1);
  4879. Result := True;
  4880. Exit;
  4881. { This repeat..until loop exists for the benefit of Break }
  4882. until True;
  4883. end;
  4884. end;
  4885. end;
  4886. end;
  4887. end;
  4888. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4889. var
  4890. hp1 : tai;
  4891. begin
  4892. DoSubAddOpt := False;
  4893. if taicpu(p).oper[0]^.typ <> top_const then
  4894. { Should have been confirmed before calling }
  4895. InternalError(2021102601);
  4896. if GetLastInstruction(p, hp1) and
  4897. (hp1.typ = ait_instruction) and
  4898. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4899. case taicpu(hp1).opcode Of
  4900. A_DEC:
  4901. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4902. begin
  4903. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4904. RemoveInstruction(hp1);
  4905. end;
  4906. A_SUB:
  4907. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4908. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4909. begin
  4910. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4911. RemoveInstruction(hp1);
  4912. end;
  4913. A_ADD:
  4914. begin
  4915. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4916. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4917. begin
  4918. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4919. RemoveInstruction(hp1);
  4920. if (taicpu(p).oper[0]^.val = 0) then
  4921. begin
  4922. hp1 := tai(p.next);
  4923. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4924. if not GetLastInstruction(hp1, p) then
  4925. p := hp1;
  4926. DoSubAddOpt := True;
  4927. end
  4928. end;
  4929. end;
  4930. else
  4931. ;
  4932. end;
  4933. end;
  4934. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  4935. begin
  4936. Result := False;
  4937. if UpdateTmpUsedRegs then
  4938. TransferUsedRegs(TmpUsedRegs);
  4939. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4940. { The x86 assemblers have difficulty comparing values against absolute addresses }
  4941. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  4942. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  4943. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  4944. (
  4945. (
  4946. (taicpu(hp1).opcode = A_TEST)
  4947. ) or (
  4948. (taicpu(hp1).opcode = A_CMP) and
  4949. { A sanity check more than anything }
  4950. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  4951. )
  4952. ) then
  4953. begin
  4954. { change
  4955. mov mem, %reg
  4956. cmp/test x, %reg / test %reg,%reg
  4957. (reg deallocated)
  4958. to
  4959. cmp/test x, mem / cmp 0, mem
  4960. }
  4961. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4962. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  4963. begin
  4964. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  4965. if (taicpu(hp1).opcode = A_TEST) and
  4966. (
  4967. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  4968. MatchOperand(taicpu(hp1).oper[0]^, -1)
  4969. ) then
  4970. begin
  4971. taicpu(hp1).opcode := A_CMP;
  4972. taicpu(hp1).loadconst(0, 0);
  4973. end;
  4974. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  4975. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  4976. RemoveCurrentP(p, hp1);
  4977. Result := True;
  4978. Exit;
  4979. end;
  4980. end;
  4981. end;
  4982. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  4983. var
  4984. hp2, hp3, hp4, hp5, hp6: tai;
  4985. ThisReg: TRegister;
  4986. JumpLoc: TAsmLabel;
  4987. begin
  4988. Result := False;
  4989. {
  4990. Convert:
  4991. j<c> .L1
  4992. .L2:
  4993. mov 1,reg
  4994. jmp .L3 (or ret, although it might not be a RET yet)
  4995. .L1:
  4996. mov 0,reg
  4997. jmp .L3 (or ret)
  4998. ( As long as .L3 <> .L1 or .L2)
  4999. To:
  5000. mov 0,reg
  5001. set<not(c)> reg
  5002. jmp .L3 (or ret)
  5003. .L2:
  5004. mov 1,reg
  5005. jmp .L3 (or ret)
  5006. .L1:
  5007. mov 0,reg
  5008. jmp .L3 (or ret)
  5009. }
  5010. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5011. Exit;
  5012. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5013. if GetNextInstruction(hp_label, hp2) and
  5014. MatchInstruction(hp2,A_MOV,[]) and
  5015. (taicpu(hp2).oper[0]^.typ = top_const) and
  5016. (
  5017. (
  5018. (taicpu(hp2).oper[1]^.typ = top_reg)
  5019. {$ifdef i386}
  5020. { Under i386, ESI, EDI, EBP and ESP
  5021. don't have an 8-bit representation }
  5022. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5023. {$endif i386}
  5024. ) or (
  5025. {$ifdef i386}
  5026. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5027. {$endif i386}
  5028. (taicpu(hp2).opsize = S_B)
  5029. )
  5030. ) and
  5031. GetNextInstruction(hp2, hp3) and
  5032. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5033. (
  5034. (taicpu(hp3).opcode=A_RET) or
  5035. (
  5036. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5037. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5038. )
  5039. ) and
  5040. GetNextInstruction(hp3, hp4) and
  5041. SkipAligns(hp4, hp4) and
  5042. (hp4.typ=ait_label) and
  5043. (tai_label(hp4).labsym=JumpLoc) and
  5044. (
  5045. not (cs_opt_size in current_settings.optimizerswitches) or
  5046. { If the initial jump is the label's only reference, then it will
  5047. become a dead label if the other conditions are met and hence
  5048. remove at least 2 instructions, including a jump }
  5049. (JumpLoc.getrefs = 1)
  5050. ) and
  5051. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5052. that will be optimised out }
  5053. GetNextInstruction(hp4, hp5) and
  5054. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5055. (taicpu(hp5).oper[0]^.typ = top_const) and
  5056. (
  5057. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5058. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5059. ) and
  5060. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5061. GetNextInstruction(hp5,hp6) and
  5062. (
  5063. (hp6.typ<>ait_label) or
  5064. SkipLabels(hp6, hp6)
  5065. ) and
  5066. (hp6.typ=ait_instruction) then
  5067. begin
  5068. { First, let's look at the two jumps that are hp3 and hp6 }
  5069. if not
  5070. (
  5071. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5072. (
  5073. (taicpu(hp6).opcode=A_RET) or
  5074. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5075. )
  5076. ) then
  5077. { If condition is False, then the JMP/RET instructions matched conventionally }
  5078. begin
  5079. { See if one of the jumps can be instantly converted into a RET }
  5080. if (taicpu(hp3).opcode=A_JMP) then
  5081. begin
  5082. { Reuse hp5 }
  5083. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5084. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5085. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5086. Exit;
  5087. if MatchInstruction(hp5, A_RET, []) then
  5088. begin
  5089. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5090. ConvertJumpToRET(hp3, hp5);
  5091. Result := True;
  5092. end
  5093. else
  5094. Exit;
  5095. end;
  5096. if (taicpu(hp6).opcode=A_JMP) then
  5097. begin
  5098. { Reuse hp5 }
  5099. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5100. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5101. Exit;
  5102. if MatchInstruction(hp5, A_RET, []) then
  5103. begin
  5104. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5105. ConvertJumpToRET(hp6, hp5);
  5106. Result := True;
  5107. end
  5108. else
  5109. Exit;
  5110. end;
  5111. if not
  5112. (
  5113. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5114. (
  5115. (taicpu(hp6).opcode=A_RET) or
  5116. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5117. )
  5118. ) then
  5119. { Still doesn't match }
  5120. Exit;
  5121. end;
  5122. if (taicpu(hp2).oper[0]^.val = 1) then
  5123. begin
  5124. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5125. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5126. end
  5127. else
  5128. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5129. if taicpu(hp2).opsize=S_B then
  5130. begin
  5131. if taicpu(hp2).oper[1]^.typ = top_reg then
  5132. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5133. else
  5134. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5135. hp2 := p;
  5136. end
  5137. else
  5138. begin
  5139. { Will be a register because the size can't be S_B otherwise }
  5140. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5141. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5142. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5143. { Inserting it right before p will guarantee that the flags are also tracked }
  5144. Asml.InsertBefore(hp2, p);
  5145. end;
  5146. taicpu(hp4).condition:=taicpu(p).condition;
  5147. asml.InsertBefore(hp4, hp2);
  5148. JumpLoc.decrefs;
  5149. if taicpu(hp3).opcode = A_JMP then
  5150. begin
  5151. MakeUnconditional(taicpu(p));
  5152. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5153. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5154. end
  5155. else
  5156. begin
  5157. taicpu(p).condition := C_None;
  5158. taicpu(p).opcode := A_RET;
  5159. taicpu(p).clearop(0);
  5160. taicpu(p).ops := 0;
  5161. end;
  5162. if (JumpLoc.getrefs = 0) then
  5163. RemoveDeadCodeAfterJump(hp3);
  5164. Result:=true;
  5165. exit;
  5166. end;
  5167. end;
  5168. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5169. var
  5170. hp1, hp2: tai;
  5171. ActiveReg: TRegister;
  5172. OldOffset: asizeint;
  5173. ThisConst: TCGInt;
  5174. function RegDeallocated: Boolean;
  5175. begin
  5176. TransferUsedRegs(TmpUsedRegs);
  5177. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5178. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5179. end;
  5180. begin
  5181. Result:=false;
  5182. hp1 := nil;
  5183. { replace
  5184. subX const,%reg1
  5185. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5186. dealloc %reg1
  5187. by
  5188. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5189. }
  5190. if MatchOpType(taicpu(p),top_const,top_reg) then
  5191. begin
  5192. ActiveReg := taicpu(p).oper[1]^.reg;
  5193. { Ensures the entire register was updated }
  5194. if (taicpu(p).opsize >= S_L) and
  5195. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5196. MatchInstruction(hp1,A_LEA,[]) and
  5197. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5198. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5199. (
  5200. { Cover the case where the register in the reference is also the destination register }
  5201. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5202. (
  5203. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5204. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5205. RegDeallocated
  5206. )
  5207. ) then
  5208. begin
  5209. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5210. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5211. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5212. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5213. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5214. {$ifdef x86_64}
  5215. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5216. begin
  5217. { Overflow; abort }
  5218. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5219. end
  5220. else
  5221. {$endif x86_64}
  5222. begin
  5223. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5224. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5225. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5226. RemoveCurrentP(p, hp1)
  5227. else
  5228. RemoveCurrentP(p);
  5229. result:=true;
  5230. Exit;
  5231. end;
  5232. end;
  5233. if (
  5234. { Save calling GetNextInstructionUsingReg again }
  5235. Assigned(hp1) or
  5236. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5237. ) and
  5238. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5239. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5240. begin
  5241. if taicpu(hp1).oper[0]^.typ = top_const then
  5242. begin
  5243. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5244. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5245. Result := True;
  5246. { Handle any overflows }
  5247. case taicpu(p).opsize of
  5248. S_B:
  5249. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5250. S_W:
  5251. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5252. S_L:
  5253. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5254. {$ifdef x86_64}
  5255. S_Q:
  5256. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5257. { Overflow; abort }
  5258. Result := False
  5259. else
  5260. taicpu(p).oper[0]^.val := ThisConst;
  5261. {$endif x86_64}
  5262. else
  5263. InternalError(2021102610);
  5264. end;
  5265. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5266. if Result then
  5267. begin
  5268. if (taicpu(p).oper[0]^.val < 0) and
  5269. (
  5270. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5271. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5272. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5273. ) then
  5274. begin
  5275. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5276. taicpu(p).opcode := A_SUB;
  5277. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5278. end
  5279. else
  5280. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5281. RemoveInstruction(hp1);
  5282. end;
  5283. end
  5284. else
  5285. begin
  5286. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5287. TransferUsedRegs(TmpUsedRegs);
  5288. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5289. hp2 := p;
  5290. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5291. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5292. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5293. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5294. begin
  5295. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5296. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5297. Asml.Remove(p);
  5298. Asml.InsertAfter(p, hp1);
  5299. p := hp1;
  5300. Result := True;
  5301. Exit;
  5302. end;
  5303. end;
  5304. end;
  5305. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5306. { * change "sub/add const1, reg" or "dec reg" followed by
  5307. "sub const2, reg" to one "sub ..., reg" }
  5308. {$ifdef i386}
  5309. if (taicpu(p).oper[0]^.val = 2) and
  5310. (ActiveReg = NR_ESP) and
  5311. { Don't do the sub/push optimization if the sub }
  5312. { comes from setting up the stack frame (JM) }
  5313. (not(GetLastInstruction(p,hp1)) or
  5314. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5315. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5316. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5317. begin
  5318. hp1 := tai(p.next);
  5319. while Assigned(hp1) and
  5320. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5321. not RegReadByInstruction(NR_ESP,hp1) and
  5322. not RegModifiedByInstruction(NR_ESP,hp1) do
  5323. hp1 := tai(hp1.next);
  5324. if Assigned(hp1) and
  5325. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5326. begin
  5327. taicpu(hp1).changeopsize(S_L);
  5328. if taicpu(hp1).oper[0]^.typ=top_reg then
  5329. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5330. hp1 := tai(p.next);
  5331. RemoveCurrentp(p, hp1);
  5332. Result:=true;
  5333. exit;
  5334. end;
  5335. end;
  5336. {$endif i386}
  5337. if DoSubAddOpt(p) then
  5338. Result:=true;
  5339. end;
  5340. end;
  5341. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5342. var
  5343. TmpBool1,TmpBool2 : Boolean;
  5344. tmpref : treference;
  5345. hp1,hp2: tai;
  5346. mask: tcgint;
  5347. begin
  5348. Result:=false;
  5349. { All these optimisations work on "shl/sal const,%reg" }
  5350. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5351. Exit;
  5352. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5353. (taicpu(p).oper[0]^.val <= 3) then
  5354. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5355. begin
  5356. { should we check the next instruction? }
  5357. TmpBool1 := True;
  5358. { have we found an add/sub which could be
  5359. integrated in the lea? }
  5360. TmpBool2 := False;
  5361. reference_reset(tmpref,2,[]);
  5362. TmpRef.index := taicpu(p).oper[1]^.reg;
  5363. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5364. while TmpBool1 and
  5365. GetNextInstruction(p, hp1) and
  5366. (tai(hp1).typ = ait_instruction) and
  5367. ((((taicpu(hp1).opcode = A_ADD) or
  5368. (taicpu(hp1).opcode = A_SUB)) and
  5369. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5370. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5371. (((taicpu(hp1).opcode = A_INC) or
  5372. (taicpu(hp1).opcode = A_DEC)) and
  5373. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5374. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5375. ((taicpu(hp1).opcode = A_LEA) and
  5376. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5377. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5378. (not GetNextInstruction(hp1,hp2) or
  5379. not instrReadsFlags(hp2)) Do
  5380. begin
  5381. TmpBool1 := False;
  5382. if taicpu(hp1).opcode=A_LEA then
  5383. begin
  5384. if (TmpRef.base = NR_NO) and
  5385. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5386. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5387. { Segment register isn't a concern here }
  5388. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5389. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5390. begin
  5391. TmpBool1 := True;
  5392. TmpBool2 := True;
  5393. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5394. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5395. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5396. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5397. RemoveInstruction(hp1);
  5398. end
  5399. end
  5400. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5401. begin
  5402. TmpBool1 := True;
  5403. TmpBool2 := True;
  5404. case taicpu(hp1).opcode of
  5405. A_ADD:
  5406. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5407. A_SUB:
  5408. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5409. else
  5410. internalerror(2019050536);
  5411. end;
  5412. RemoveInstruction(hp1);
  5413. end
  5414. else
  5415. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5416. (((taicpu(hp1).opcode = A_ADD) and
  5417. (TmpRef.base = NR_NO)) or
  5418. (taicpu(hp1).opcode = A_INC) or
  5419. (taicpu(hp1).opcode = A_DEC)) then
  5420. begin
  5421. TmpBool1 := True;
  5422. TmpBool2 := True;
  5423. case taicpu(hp1).opcode of
  5424. A_ADD:
  5425. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5426. A_INC:
  5427. inc(TmpRef.offset);
  5428. A_DEC:
  5429. dec(TmpRef.offset);
  5430. else
  5431. internalerror(2019050535);
  5432. end;
  5433. RemoveInstruction(hp1);
  5434. end;
  5435. end;
  5436. if TmpBool2
  5437. {$ifndef x86_64}
  5438. or
  5439. ((current_settings.optimizecputype < cpu_Pentium2) and
  5440. (taicpu(p).oper[0]^.val <= 3) and
  5441. not(cs_opt_size in current_settings.optimizerswitches))
  5442. {$endif x86_64}
  5443. then
  5444. begin
  5445. if not(TmpBool2) and
  5446. (taicpu(p).oper[0]^.val=1) then
  5447. begin
  5448. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5449. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5450. end
  5451. else
  5452. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5453. taicpu(p).oper[1]^.reg);
  5454. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5455. InsertLLItem(p.previous, p.next, hp1);
  5456. p.free;
  5457. p := hp1;
  5458. end;
  5459. end
  5460. {$ifndef x86_64}
  5461. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5462. begin
  5463. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5464. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5465. (unlike shl, which is only Tairable in the U pipe) }
  5466. if taicpu(p).oper[0]^.val=1 then
  5467. begin
  5468. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5469. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5470. InsertLLItem(p.previous, p.next, hp1);
  5471. p.free;
  5472. p := hp1;
  5473. end
  5474. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5475. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5476. else if (taicpu(p).opsize = S_L) and
  5477. (taicpu(p).oper[0]^.val<= 3) then
  5478. begin
  5479. reference_reset(tmpref,2,[]);
  5480. TmpRef.index := taicpu(p).oper[1]^.reg;
  5481. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5482. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5483. InsertLLItem(p.previous, p.next, hp1);
  5484. p.free;
  5485. p := hp1;
  5486. end;
  5487. end
  5488. {$endif x86_64}
  5489. else if
  5490. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5491. (
  5492. (
  5493. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5494. SetAndTest(hp1, hp2)
  5495. {$ifdef x86_64}
  5496. ) or
  5497. (
  5498. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5499. GetNextInstruction(hp1, hp2) and
  5500. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5501. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5502. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5503. {$endif x86_64}
  5504. )
  5505. ) and
  5506. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5507. begin
  5508. { Change:
  5509. shl x, %reg1
  5510. mov -(1<<x), %reg2
  5511. and %reg2, %reg1
  5512. Or:
  5513. shl x, %reg1
  5514. and -(1<<x), %reg1
  5515. To just:
  5516. shl x, %reg1
  5517. Since the and operation only zeroes bits that are already zero from the shl operation
  5518. }
  5519. case taicpu(p).oper[0]^.val of
  5520. 8:
  5521. mask:=$FFFFFFFFFFFFFF00;
  5522. 16:
  5523. mask:=$FFFFFFFFFFFF0000;
  5524. 32:
  5525. mask:=$FFFFFFFF00000000;
  5526. 63:
  5527. { Constant pre-calculated to prevent overflow errors with Int64 }
  5528. mask:=$8000000000000000;
  5529. else
  5530. begin
  5531. if taicpu(p).oper[0]^.val >= 64 then
  5532. { Shouldn't happen realistically, since the register
  5533. is guaranteed to be set to zero at this point }
  5534. mask := 0
  5535. else
  5536. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5537. end;
  5538. end;
  5539. if taicpu(hp1).oper[0]^.val = mask then
  5540. begin
  5541. { Everything checks out, perform the optimisation, as long as
  5542. the FLAGS register isn't being used}
  5543. TransferUsedRegs(TmpUsedRegs);
  5544. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5545. {$ifdef x86_64}
  5546. if (hp1 <> hp2) then
  5547. begin
  5548. { "shl/mov/and" version }
  5549. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5550. { Don't do the optimisation if the FLAGS register is in use }
  5551. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5552. begin
  5553. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5554. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5555. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5556. begin
  5557. RemoveInstruction(hp1);
  5558. Result := True;
  5559. end;
  5560. { Only set Result to True if the 'mov' instruction was removed }
  5561. RemoveInstruction(hp2);
  5562. end;
  5563. end
  5564. else
  5565. {$endif x86_64}
  5566. begin
  5567. { "shl/and" version }
  5568. { Don't do the optimisation if the FLAGS register is in use }
  5569. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5570. begin
  5571. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5572. RemoveInstruction(hp1);
  5573. Result := True;
  5574. end;
  5575. end;
  5576. Exit;
  5577. end
  5578. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5579. begin
  5580. { Even if the mask doesn't allow for its removal, we might be
  5581. able to optimise the mask for the "shl/and" version, which
  5582. may permit other peephole optimisations }
  5583. {$ifdef DEBUG_AOPTCPU}
  5584. mask := taicpu(hp1).oper[0]^.val and mask;
  5585. if taicpu(hp1).oper[0]^.val <> mask then
  5586. begin
  5587. DebugMsg(
  5588. SPeepholeOptimization +
  5589. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5590. ' to $' + debug_tostr(mask) +
  5591. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5592. taicpu(hp1).oper[0]^.val := mask;
  5593. end;
  5594. {$else DEBUG_AOPTCPU}
  5595. { If debugging is off, just set the operand even if it's the same }
  5596. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5597. {$endif DEBUG_AOPTCPU}
  5598. end;
  5599. end;
  5600. {
  5601. change
  5602. shl/sal const,reg
  5603. <op> ...(...,reg,1),...
  5604. into
  5605. <op> ...(...,reg,1 shl const),...
  5606. if const in 1..3
  5607. }
  5608. if MatchOpType(taicpu(p), top_const, top_reg) and
  5609. (taicpu(p).oper[0]^.val in [1..3]) and
  5610. GetNextInstruction(p, hp1) and
  5611. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5612. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5613. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5614. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5615. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5616. begin
  5617. TransferUsedRegs(TmpUsedRegs);
  5618. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5619. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5620. begin
  5621. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5622. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5623. RemoveCurrentP(p);
  5624. Result:=true;
  5625. end;
  5626. end;
  5627. end;
  5628. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5629. var
  5630. CurrentRef: TReference;
  5631. FullReg: TRegister;
  5632. hp1, hp2: tai;
  5633. begin
  5634. Result := False;
  5635. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5636. Exit;
  5637. { We assume you've checked if the operand is actually a reference by
  5638. this point. If it isn't, you'll most likely get an access violation }
  5639. CurrentRef := first_mov.oper[1]^.ref^;
  5640. { Memory must be aligned }
  5641. if (CurrentRef.offset mod 4) <> 0 then
  5642. Exit;
  5643. Inc(CurrentRef.offset);
  5644. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5645. if MatchOperand(second_mov.oper[0]^, 0) and
  5646. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5647. GetNextInstruction(second_mov, hp1) and
  5648. (hp1.typ = ait_instruction) and
  5649. (taicpu(hp1).opcode = A_MOV) and
  5650. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5651. (taicpu(hp1).oper[0]^.val = 0) then
  5652. begin
  5653. Inc(CurrentRef.offset);
  5654. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5655. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5656. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5657. begin
  5658. case taicpu(hp1).opsize of
  5659. S_B:
  5660. if GetNextInstruction(hp1, hp2) and
  5661. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5662. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5663. (taicpu(hp2).oper[0]^.val = 0) then
  5664. begin
  5665. Inc(CurrentRef.offset);
  5666. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5667. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5668. (taicpu(hp2).opsize = S_B) then
  5669. begin
  5670. RemoveInstruction(hp1);
  5671. RemoveInstruction(hp2);
  5672. first_mov.opsize := S_L;
  5673. if first_mov.oper[0]^.typ = top_reg then
  5674. begin
  5675. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5676. { Reuse second_mov as a MOVZX instruction }
  5677. second_mov.opcode := A_MOVZX;
  5678. second_mov.opsize := S_BL;
  5679. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5680. second_mov.loadreg(1, FullReg);
  5681. first_mov.oper[0]^.reg := FullReg;
  5682. asml.Remove(second_mov);
  5683. asml.InsertBefore(second_mov, first_mov);
  5684. end
  5685. else
  5686. { It's a value }
  5687. begin
  5688. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5689. RemoveInstruction(second_mov);
  5690. end;
  5691. Result := True;
  5692. Exit;
  5693. end;
  5694. end;
  5695. S_W:
  5696. begin
  5697. RemoveInstruction(hp1);
  5698. first_mov.opsize := S_L;
  5699. if first_mov.oper[0]^.typ = top_reg then
  5700. begin
  5701. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5702. { Reuse second_mov as a MOVZX instruction }
  5703. second_mov.opcode := A_MOVZX;
  5704. second_mov.opsize := S_BL;
  5705. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5706. second_mov.loadreg(1, FullReg);
  5707. first_mov.oper[0]^.reg := FullReg;
  5708. asml.Remove(second_mov);
  5709. asml.InsertBefore(second_mov, first_mov);
  5710. end
  5711. else
  5712. { It's a value }
  5713. begin
  5714. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5715. RemoveInstruction(second_mov);
  5716. end;
  5717. Result := True;
  5718. Exit;
  5719. end;
  5720. else
  5721. ;
  5722. end;
  5723. end;
  5724. end;
  5725. end;
  5726. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5727. { returns true if a "continue" should be done after this optimization }
  5728. var
  5729. hp1, hp2: tai;
  5730. begin
  5731. Result := false;
  5732. if MatchOpType(taicpu(p),top_ref) and
  5733. GetNextInstruction(p, hp1) and
  5734. (hp1.typ = ait_instruction) and
  5735. (((taicpu(hp1).opcode = A_FLD) and
  5736. (taicpu(p).opcode = A_FSTP)) or
  5737. ((taicpu(p).opcode = A_FISTP) and
  5738. (taicpu(hp1).opcode = A_FILD))) and
  5739. MatchOpType(taicpu(hp1),top_ref) and
  5740. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5741. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5742. begin
  5743. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5744. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5745. GetNextInstruction(hp1, hp2) and
  5746. (hp2.typ = ait_instruction) and
  5747. IsExitCode(hp2) and
  5748. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5749. not(assigned(current_procinfo.procdef.funcretsym) and
  5750. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5751. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5752. begin
  5753. RemoveInstruction(hp1);
  5754. RemoveCurrentP(p, hp2);
  5755. RemoveLastDeallocForFuncRes(p);
  5756. Result := true;
  5757. end
  5758. else
  5759. { we can do this only in fast math mode as fstp is rounding ...
  5760. ... still disabled as it breaks the compiler and/or rtl }
  5761. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5762. { ... or if another fstp equal to the first one follows }
  5763. (GetNextInstruction(hp1,hp2) and
  5764. (hp2.typ = ait_instruction) and
  5765. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5766. (taicpu(p).opsize=taicpu(hp2).opsize))
  5767. ) and
  5768. { fst can't store an extended/comp value }
  5769. (taicpu(p).opsize <> S_FX) and
  5770. (taicpu(p).opsize <> S_IQ) then
  5771. begin
  5772. if (taicpu(p).opcode = A_FSTP) then
  5773. taicpu(p).opcode := A_FST
  5774. else
  5775. taicpu(p).opcode := A_FIST;
  5776. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5777. RemoveInstruction(hp1);
  5778. end;
  5779. end;
  5780. end;
  5781. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5782. var
  5783. hp1, hp2: tai;
  5784. begin
  5785. result:=false;
  5786. if MatchOpType(taicpu(p),top_reg) and
  5787. GetNextInstruction(p, hp1) and
  5788. (hp1.typ = Ait_Instruction) and
  5789. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5790. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5791. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5792. { change to
  5793. fld reg fxxx reg,st
  5794. fxxxp st, st1 (hp1)
  5795. Remark: non commutative operations must be reversed!
  5796. }
  5797. begin
  5798. case taicpu(hp1).opcode Of
  5799. A_FMULP,A_FADDP,
  5800. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5801. begin
  5802. case taicpu(hp1).opcode Of
  5803. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5804. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5805. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5806. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5807. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5808. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5809. else
  5810. internalerror(2019050534);
  5811. end;
  5812. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5813. taicpu(hp1).oper[1]^.reg := NR_ST;
  5814. RemoveCurrentP(p, hp1);
  5815. Result:=true;
  5816. exit;
  5817. end;
  5818. else
  5819. ;
  5820. end;
  5821. end
  5822. else
  5823. if MatchOpType(taicpu(p),top_ref) and
  5824. GetNextInstruction(p, hp2) and
  5825. (hp2.typ = Ait_Instruction) and
  5826. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5827. (taicpu(p).opsize in [S_FS, S_FL]) and
  5828. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5829. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5830. if GetLastInstruction(p, hp1) and
  5831. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5832. MatchOpType(taicpu(hp1),top_ref) and
  5833. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5834. if ((taicpu(hp2).opcode = A_FMULP) or
  5835. (taicpu(hp2).opcode = A_FADDP)) then
  5836. { change to
  5837. fld/fst mem1 (hp1) fld/fst mem1
  5838. fld mem1 (p) fadd/
  5839. faddp/ fmul st, st
  5840. fmulp st, st1 (hp2) }
  5841. begin
  5842. RemoveCurrentP(p, hp1);
  5843. if (taicpu(hp2).opcode = A_FADDP) then
  5844. taicpu(hp2).opcode := A_FADD
  5845. else
  5846. taicpu(hp2).opcode := A_FMUL;
  5847. taicpu(hp2).oper[1]^.reg := NR_ST;
  5848. end
  5849. else
  5850. { change to
  5851. fld/fst mem1 (hp1) fld/fst mem1
  5852. fld mem1 (p) fld st}
  5853. begin
  5854. taicpu(p).changeopsize(S_FL);
  5855. taicpu(p).loadreg(0,NR_ST);
  5856. end
  5857. else
  5858. begin
  5859. case taicpu(hp2).opcode Of
  5860. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5861. { change to
  5862. fld/fst mem1 (hp1) fld/fst mem1
  5863. fld mem2 (p) fxxx mem2
  5864. fxxxp st, st1 (hp2) }
  5865. begin
  5866. case taicpu(hp2).opcode Of
  5867. A_FADDP: taicpu(p).opcode := A_FADD;
  5868. A_FMULP: taicpu(p).opcode := A_FMUL;
  5869. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5870. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5871. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5872. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5873. else
  5874. internalerror(2019050533);
  5875. end;
  5876. RemoveInstruction(hp2);
  5877. end
  5878. else
  5879. ;
  5880. end
  5881. end
  5882. end;
  5883. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5884. begin
  5885. Result := condition_in(cond1, cond2) or
  5886. { Not strictly subsets due to the actual flags checked, but because we're
  5887. comparing integers, E is a subset of AE and GE and their aliases }
  5888. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5889. end;
  5890. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5891. var
  5892. v: TCGInt;
  5893. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5894. FirstMatch: Boolean;
  5895. NewReg: TRegister;
  5896. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5897. begin
  5898. Result:=false;
  5899. { All these optimisations need a next instruction }
  5900. if not GetNextInstruction(p, hp1) then
  5901. Exit;
  5902. { Search for:
  5903. cmp ###,###
  5904. j(c1) @lbl1
  5905. ...
  5906. @lbl:
  5907. cmp ###.### (same comparison as above)
  5908. j(c2) @lbl2
  5909. If c1 is a subset of c2, change to:
  5910. cmp ###,###
  5911. j(c2) @lbl2
  5912. (@lbl1 may become a dead label as a result)
  5913. }
  5914. { Also handle cases where there are multiple jumps in a row }
  5915. p_jump := hp1;
  5916. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5917. begin
  5918. if IsJumpToLabel(taicpu(p_jump)) then
  5919. begin
  5920. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5921. p_label := nil;
  5922. if Assigned(JumpLabel) then
  5923. p_label := getlabelwithsym(JumpLabel);
  5924. if Assigned(p_label) and
  5925. GetNextInstruction(p_label, p_dist) and
  5926. MatchInstruction(p_dist, A_CMP, []) and
  5927. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5928. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5929. GetNextInstruction(p_dist, hp1_dist) and
  5930. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5931. begin
  5932. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5933. if JumpLabel = JumpLabel_dist then
  5934. { This is an infinite loop }
  5935. Exit;
  5936. { Best optimisation when the first condition is a subset (or equal) of the second }
  5937. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5938. begin
  5939. { Any registers used here will already be allocated }
  5940. if Assigned(JumpLabel_dist) then
  5941. JumpLabel_dist.IncRefs;
  5942. if Assigned(JumpLabel) then
  5943. JumpLabel.DecRefs;
  5944. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5945. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5946. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5947. Result := True;
  5948. { Don't exit yet. Since p and p_jump haven't actually been
  5949. removed, we can check for more on this iteration }
  5950. end
  5951. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5952. GetNextInstruction(hp1_dist, hp1_label) and
  5953. SkipAligns(hp1_label, hp1_label) and
  5954. (hp1_label.typ = ait_label) then
  5955. begin
  5956. JumpLabel_far := tai_label(hp1_label).labsym;
  5957. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5958. { This is an infinite loop }
  5959. Exit;
  5960. if Assigned(JumpLabel_far) then
  5961. begin
  5962. { In this situation, if the first jump branches, the second one will never,
  5963. branch so change the destination label to after the second jump }
  5964. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5965. if Assigned(JumpLabel) then
  5966. JumpLabel.DecRefs;
  5967. JumpLabel_far.IncRefs;
  5968. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5969. Result := True;
  5970. { Don't exit yet. Since p and p_jump haven't actually been
  5971. removed, we can check for more on this iteration }
  5972. Continue;
  5973. end;
  5974. end;
  5975. end;
  5976. end;
  5977. { Search for:
  5978. cmp ###,###
  5979. j(c1) @lbl1
  5980. cmp ###,### (same as first)
  5981. Remove second cmp
  5982. }
  5983. if GetNextInstruction(p_jump, hp2) and
  5984. (
  5985. (
  5986. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  5987. (
  5988. (
  5989. MatchOpType(taicpu(p), top_const, top_reg) and
  5990. MatchOpType(taicpu(hp2), top_const, top_reg) and
  5991. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5992. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5993. ) or (
  5994. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5995. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5996. )
  5997. )
  5998. ) or (
  5999. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6000. MatchOperand(taicpu(p).oper[0]^, 0) and
  6001. (taicpu(p).oper[1]^.typ = top_reg) and
  6002. MatchInstruction(hp2, A_TEST, []) and
  6003. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6004. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6005. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6006. )
  6007. ) then
  6008. begin
  6009. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6010. RemoveInstruction(hp2);
  6011. Result := True;
  6012. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6013. end;
  6014. GetNextInstruction(p_jump, p_jump);
  6015. end;
  6016. {
  6017. Try to optimise the following:
  6018. cmp $x,### ($x and $y can be registers or constants)
  6019. je @lbl1 (only reference)
  6020. cmp $y,### (### are identical)
  6021. @Lbl:
  6022. sete %reg1
  6023. Change to:
  6024. cmp $x,###
  6025. sete %reg2 (allocate new %reg2)
  6026. cmp $y,###
  6027. sete %reg1
  6028. orb %reg2,%reg1
  6029. (dealloc %reg2)
  6030. This adds an instruction (so don't perform under -Os), but it removes
  6031. a conditional branch.
  6032. }
  6033. if not (cs_opt_size in current_settings.optimizerswitches) and
  6034. (
  6035. (hp1 = p_jump) or
  6036. GetNextInstruction(p, hp1)
  6037. ) and
  6038. MatchInstruction(hp1, A_Jcc, []) and
  6039. IsJumpToLabel(taicpu(hp1)) and
  6040. (taicpu(hp1).condition in [C_E, C_Z]) and
  6041. GetNextInstruction(hp1, hp2) and
  6042. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6043. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6044. { The first operand of CMP instructions can only be a register or
  6045. immediate anyway, so no need to check }
  6046. GetNextInstruction(hp2, p_label) and
  6047. (p_label.typ = ait_label) and
  6048. (tai_label(p_label).labsym.getrefs = 1) and
  6049. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6050. GetNextInstruction(p_label, p_dist) and
  6051. MatchInstruction(p_dist, A_SETcc, []) and
  6052. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6053. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  6054. begin
  6055. TransferUsedRegs(TmpUsedRegs);
  6056. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6057. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6058. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6059. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6060. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  6061. { Get the instruction after the SETcc instruction so we can
  6062. allocate a new register over the entire range }
  6063. GetNextInstruction(p_dist, hp1_dist) then
  6064. begin
  6065. { Register can appear in p if it's not used afterwards, so only
  6066. allocate between hp1 and hp1_dist }
  6067. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  6068. if NewReg <> NR_NO then
  6069. begin
  6070. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6071. { Change the jump instruction into a SETcc instruction }
  6072. taicpu(hp1).opcode := A_SETcc;
  6073. taicpu(hp1).opsize := S_B;
  6074. taicpu(hp1).loadreg(0, NewReg);
  6075. { This is now a dead label }
  6076. tai_label(p_label).labsym.decrefs;
  6077. { Prefer adding before the next instruction so the FLAGS
  6078. register is deallicated first }
  6079. AsmL.InsertBefore(
  6080. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  6081. hp1_dist
  6082. );
  6083. Result := True;
  6084. { Don't exit yet, as p wasn't changed and hp1, while
  6085. modified, is still intact and might be optimised by the
  6086. SETcc optimisation below }
  6087. end;
  6088. end;
  6089. end;
  6090. if taicpu(p).oper[0]^.typ = top_const then
  6091. begin
  6092. if (taicpu(p).oper[0]^.val = 0) and
  6093. (taicpu(p).oper[1]^.typ = top_reg) and
  6094. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6095. begin
  6096. hp2 := p;
  6097. FirstMatch := True;
  6098. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6099. anything meaningful once it's converted to "test %reg,%reg";
  6100. additionally, some jumps will always (or never) branch, so
  6101. evaluate every jump immediately following the
  6102. comparison, optimising the conditions if possible.
  6103. Similarly with SETcc... those that are always set to 0 or 1
  6104. are changed to MOV instructions }
  6105. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6106. (
  6107. GetNextInstruction(hp2, hp1) and
  6108. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6109. ) do
  6110. begin
  6111. FirstMatch := False;
  6112. case taicpu(hp1).condition of
  6113. C_B, C_C, C_NAE, C_O:
  6114. { For B/NAE:
  6115. Will never branch since an unsigned integer can never be below zero
  6116. For C/O:
  6117. Result cannot overflow because 0 is being subtracted
  6118. }
  6119. begin
  6120. if taicpu(hp1).opcode = A_Jcc then
  6121. begin
  6122. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6123. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6124. RemoveInstruction(hp1);
  6125. { Since hp1 was deleted, hp2 must not be updated }
  6126. Continue;
  6127. end
  6128. else
  6129. begin
  6130. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6131. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6132. taicpu(hp1).opcode := A_MOV;
  6133. taicpu(hp1).ops := 2;
  6134. taicpu(hp1).condition := C_None;
  6135. taicpu(hp1).opsize := S_B;
  6136. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6137. taicpu(hp1).loadconst(0, 0);
  6138. end;
  6139. end;
  6140. C_BE, C_NA:
  6141. begin
  6142. { Will only branch if equal to zero }
  6143. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6144. taicpu(hp1).condition := C_E;
  6145. end;
  6146. C_A, C_NBE:
  6147. begin
  6148. { Will only branch if not equal to zero }
  6149. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6150. taicpu(hp1).condition := C_NE;
  6151. end;
  6152. C_AE, C_NB, C_NC, C_NO:
  6153. begin
  6154. { Will always branch }
  6155. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6156. if taicpu(hp1).opcode = A_Jcc then
  6157. begin
  6158. MakeUnconditional(taicpu(hp1));
  6159. { Any jumps/set that follow will now be dead code }
  6160. RemoveDeadCodeAfterJump(taicpu(hp1));
  6161. Break;
  6162. end
  6163. else
  6164. begin
  6165. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6166. taicpu(hp1).opcode := A_MOV;
  6167. taicpu(hp1).ops := 2;
  6168. taicpu(hp1).condition := C_None;
  6169. taicpu(hp1).opsize := S_B;
  6170. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6171. taicpu(hp1).loadconst(0, 1);
  6172. end;
  6173. end;
  6174. C_None:
  6175. InternalError(2020012201);
  6176. C_P, C_PE, C_NP, C_PO:
  6177. { We can't handle parity checks and they should never be generated
  6178. after a general-purpose CMP (it's used in some floating-point
  6179. comparisons that don't use CMP) }
  6180. InternalError(2020012202);
  6181. else
  6182. { Zero/Equality, Sign, their complements and all of the
  6183. signed comparisons do not need to be converted };
  6184. end;
  6185. hp2 := hp1;
  6186. end;
  6187. { Convert the instruction to a TEST }
  6188. taicpu(p).opcode := A_TEST;
  6189. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6190. Result := True;
  6191. Exit;
  6192. end
  6193. else if (taicpu(p).oper[0]^.val = 1) and
  6194. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6195. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6196. begin
  6197. { Convert; To:
  6198. cmp $1,r/m cmp $0,r/m
  6199. jl @lbl jle @lbl
  6200. }
  6201. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6202. taicpu(p).oper[0]^.val := 0;
  6203. taicpu(hp1).condition := C_LE;
  6204. { If the instruction is now "cmp $0,%reg", convert it to a
  6205. TEST (and effectively do the work of the "cmp $0,%reg" in
  6206. the block above)
  6207. If it's a reference, we can get away with not setting
  6208. Result to True because he haven't evaluated the jump
  6209. in this pass yet.
  6210. }
  6211. if (taicpu(p).oper[1]^.typ = top_reg) then
  6212. begin
  6213. taicpu(p).opcode := A_TEST;
  6214. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6215. Result := True;
  6216. end;
  6217. Exit;
  6218. end
  6219. else if (taicpu(p).oper[1]^.typ = top_reg)
  6220. {$ifdef x86_64}
  6221. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6222. {$endif x86_64}
  6223. then
  6224. begin
  6225. { cmp register,$8000 neg register
  6226. je target --> jo target
  6227. .... only if register is deallocated before jump.}
  6228. case Taicpu(p).opsize of
  6229. S_B: v:=$80;
  6230. S_W: v:=$8000;
  6231. S_L: v:=qword($80000000);
  6232. else
  6233. internalerror(2013112905);
  6234. end;
  6235. if (taicpu(p).oper[0]^.val=v) and
  6236. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6237. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6238. begin
  6239. TransferUsedRegs(TmpUsedRegs);
  6240. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6241. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6242. begin
  6243. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6244. Taicpu(p).opcode:=A_NEG;
  6245. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6246. Taicpu(p).clearop(1);
  6247. Taicpu(p).ops:=1;
  6248. if Taicpu(hp1).condition=C_E then
  6249. Taicpu(hp1).condition:=C_O
  6250. else
  6251. Taicpu(hp1).condition:=C_NO;
  6252. Result:=true;
  6253. exit;
  6254. end;
  6255. end;
  6256. end;
  6257. end;
  6258. if TrySwapMovCmp(p, hp1) then
  6259. begin
  6260. Result := True;
  6261. Exit;
  6262. end;
  6263. end;
  6264. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6265. var
  6266. hp1: tai;
  6267. begin
  6268. {
  6269. remove the second (v)pxor from
  6270. pxor reg,reg
  6271. ...
  6272. pxor reg,reg
  6273. }
  6274. Result:=false;
  6275. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6276. MatchOpType(taicpu(p),top_reg,top_reg) and
  6277. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6278. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6279. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6280. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6281. begin
  6282. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6283. RemoveInstruction(hp1);
  6284. Result:=true;
  6285. Exit;
  6286. end
  6287. {
  6288. replace
  6289. pxor reg1,reg1
  6290. movapd/s reg1,reg2
  6291. dealloc reg1
  6292. by
  6293. pxor reg2,reg2
  6294. }
  6295. else if GetNextInstruction(p,hp1) and
  6296. { we mix single and double opperations here because we assume that the compiler
  6297. generates vmovapd only after double operations and vmovaps only after single operations }
  6298. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6299. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6300. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6301. (taicpu(p).oper[0]^.typ=top_reg) then
  6302. begin
  6303. TransferUsedRegs(TmpUsedRegs);
  6304. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6305. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6306. begin
  6307. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6308. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6309. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6310. RemoveInstruction(hp1);
  6311. result:=true;
  6312. end;
  6313. end;
  6314. end;
  6315. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6316. var
  6317. hp1: tai;
  6318. begin
  6319. {
  6320. remove the second (v)pxor from
  6321. (v)pxor reg,reg
  6322. ...
  6323. (v)pxor reg,reg
  6324. }
  6325. Result:=false;
  6326. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6327. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6328. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6329. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6330. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6331. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6332. begin
  6333. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  6334. RemoveInstruction(hp1);
  6335. Result:=true;
  6336. Exit;
  6337. end
  6338. else
  6339. Result:=OptPass1VOP(p);
  6340. end;
  6341. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6342. var
  6343. hp1 : tai;
  6344. begin
  6345. result:=false;
  6346. { replace
  6347. IMul const,%mreg1,%mreg2
  6348. Mov %reg2,%mreg3
  6349. dealloc %mreg3
  6350. by
  6351. Imul const,%mreg1,%mreg23
  6352. }
  6353. if (taicpu(p).ops=3) and
  6354. GetNextInstruction(p,hp1) and
  6355. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6356. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6357. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6358. begin
  6359. TransferUsedRegs(TmpUsedRegs);
  6360. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6361. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6362. begin
  6363. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6364. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6365. RemoveInstruction(hp1);
  6366. result:=true;
  6367. end;
  6368. end;
  6369. end;
  6370. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6371. var
  6372. hp1 : tai;
  6373. begin
  6374. result:=false;
  6375. { replace
  6376. IMul %reg0,%reg1,%reg2
  6377. Mov %reg2,%reg3
  6378. dealloc %reg2
  6379. by
  6380. Imul %reg0,%reg1,%reg3
  6381. }
  6382. if GetNextInstruction(p,hp1) and
  6383. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6384. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6385. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6386. begin
  6387. TransferUsedRegs(TmpUsedRegs);
  6388. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6389. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6390. begin
  6391. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6392. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6393. RemoveInstruction(hp1);
  6394. result:=true;
  6395. end;
  6396. end;
  6397. end;
  6398. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6399. var
  6400. hp1: tai;
  6401. begin
  6402. Result:=false;
  6403. { get rid of
  6404. (v)cvtss2sd reg0,<reg1,>reg2
  6405. (v)cvtss2sd reg2,<reg2,>reg0
  6406. }
  6407. if GetNextInstruction(p,hp1) and
  6408. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6409. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6410. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6411. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6412. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6413. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6414. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6415. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6416. )
  6417. ) then
  6418. begin
  6419. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6420. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6421. begin
  6422. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6423. RemoveCurrentP(p);
  6424. RemoveInstruction(hp1);
  6425. end
  6426. else
  6427. begin
  6428. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6429. if taicpu(hp1).opcode=A_CVTSD2SS then
  6430. begin
  6431. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6432. taicpu(p).opcode:=A_MOVAPS;
  6433. end
  6434. else
  6435. begin
  6436. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6437. taicpu(p).opcode:=A_VMOVAPS;
  6438. end;
  6439. taicpu(p).ops:=2;
  6440. RemoveInstruction(hp1);
  6441. end;
  6442. Result:=true;
  6443. Exit;
  6444. end;
  6445. end;
  6446. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6447. var
  6448. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6449. ThisReg: TRegister;
  6450. begin
  6451. Result := False;
  6452. if not GetNextInstruction(p,hp1) then
  6453. Exit;
  6454. {
  6455. convert
  6456. j<c> .L1
  6457. mov 1,reg
  6458. jmp .L2
  6459. .L1
  6460. mov 0,reg
  6461. .L2
  6462. into
  6463. mov 0,reg
  6464. set<not(c)> reg
  6465. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6466. would destroy the flag contents
  6467. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6468. executed at the same time as a previous comparison.
  6469. set<not(c)> reg
  6470. movzx reg, reg
  6471. }
  6472. if MatchInstruction(hp1,A_MOV,[]) and
  6473. (taicpu(hp1).oper[0]^.typ = top_const) and
  6474. (
  6475. (
  6476. (taicpu(hp1).oper[1]^.typ = top_reg)
  6477. {$ifdef i386}
  6478. { Under i386, ESI, EDI, EBP and ESP
  6479. don't have an 8-bit representation }
  6480. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6481. {$endif i386}
  6482. ) or (
  6483. {$ifdef i386}
  6484. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6485. {$endif i386}
  6486. (taicpu(hp1).opsize = S_B)
  6487. )
  6488. ) and
  6489. GetNextInstruction(hp1,hp2) and
  6490. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6491. GetNextInstruction(hp2,hp3) and
  6492. SkipAligns(hp3, hp3) and
  6493. (hp3.typ=ait_label) and
  6494. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6495. GetNextInstruction(hp3,hp4) and
  6496. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6497. (taicpu(hp4).oper[0]^.typ = top_const) and
  6498. (
  6499. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6500. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6501. ) and
  6502. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6503. GetNextInstruction(hp4,hp5) and
  6504. SkipAligns(hp5, hp5) and
  6505. (hp5.typ=ait_label) and
  6506. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6507. begin
  6508. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6509. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6510. tai_label(hp3).labsym.DecRefs;
  6511. { If this isn't the only reference to the middle label, we can
  6512. still make a saving - only that the first jump and everything
  6513. that follows will remain. }
  6514. if (tai_label(hp3).labsym.getrefs = 0) then
  6515. begin
  6516. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6517. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6518. else
  6519. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6520. { remove jump, first label and second MOV (also catching any aligns) }
  6521. repeat
  6522. if not GetNextInstruction(hp2, hp3) then
  6523. InternalError(2021040810);
  6524. RemoveInstruction(hp2);
  6525. hp2 := hp3;
  6526. until hp2 = hp5;
  6527. { Don't decrement reference count before the removal loop
  6528. above, otherwise GetNextInstruction won't stop on the
  6529. the label }
  6530. tai_label(hp5).labsym.DecRefs;
  6531. end
  6532. else
  6533. begin
  6534. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6535. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6536. else
  6537. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6538. end;
  6539. taicpu(p).opcode:=A_SETcc;
  6540. taicpu(p).opsize:=S_B;
  6541. taicpu(p).is_jmp:=False;
  6542. if taicpu(hp1).opsize=S_B then
  6543. begin
  6544. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6545. if taicpu(hp1).oper[1]^.typ = top_reg then
  6546. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6547. RemoveInstruction(hp1);
  6548. end
  6549. else
  6550. begin
  6551. { Will be a register because the size can't be S_B otherwise }
  6552. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6553. taicpu(p).loadreg(0, ThisReg);
  6554. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6555. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6556. begin
  6557. case taicpu(hp1).opsize of
  6558. S_W:
  6559. taicpu(hp1).opsize := S_BW;
  6560. S_L:
  6561. taicpu(hp1).opsize := S_BL;
  6562. {$ifdef x86_64}
  6563. S_Q:
  6564. begin
  6565. taicpu(hp1).opsize := S_BL;
  6566. { Change the destination register to 32-bit }
  6567. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6568. end;
  6569. {$endif x86_64}
  6570. else
  6571. InternalError(2021040820);
  6572. end;
  6573. taicpu(hp1).opcode := A_MOVZX;
  6574. taicpu(hp1).loadreg(0, ThisReg);
  6575. end
  6576. else
  6577. begin
  6578. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6579. { hp1 is already a MOV instruction with the correct register }
  6580. taicpu(hp1).loadconst(0, 0);
  6581. { Inserting it right before p will guarantee that the flags are also tracked }
  6582. asml.Remove(hp1);
  6583. asml.InsertBefore(hp1, p);
  6584. end;
  6585. end;
  6586. Result:=true;
  6587. exit;
  6588. end
  6589. else if (hp1.typ = ait_label) then
  6590. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6591. end;
  6592. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6593. var
  6594. hp1, hp2, hp3: tai;
  6595. SourceRef, TargetRef: TReference;
  6596. CurrentReg: TRegister;
  6597. begin
  6598. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6599. if not UseAVX then
  6600. InternalError(2021100501);
  6601. Result := False;
  6602. { Look for the following to simplify:
  6603. vmovdqa/u x(mem1), %xmmreg
  6604. vmovdqa/u %xmmreg, y(mem2)
  6605. vmovdqa/u x+16(mem1), %xmmreg
  6606. vmovdqa/u %xmmreg, y+16(mem2)
  6607. Change to:
  6608. vmovdqa/u x(mem1), %ymmreg
  6609. vmovdqa/u %ymmreg, y(mem2)
  6610. vpxor %ymmreg, %ymmreg, %ymmreg
  6611. ( The VPXOR instruction is to zero the upper half, thus removing the
  6612. need to call the potentially expensive VZEROUPPER instruction. Other
  6613. peephole optimisations can remove VPXOR if it's unnecessary )
  6614. }
  6615. TransferUsedRegs(TmpUsedRegs);
  6616. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6617. { NOTE: In the optimisations below, if the references dictate that an
  6618. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6619. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6620. if (taicpu(p).opsize = S_XMM) and
  6621. MatchOpType(taicpu(p), top_ref, top_reg) and
  6622. GetNextInstruction(p, hp1) and
  6623. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6624. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6625. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6626. begin
  6627. SourceRef := taicpu(p).oper[0]^.ref^;
  6628. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6629. if GetNextInstruction(hp1, hp2) and
  6630. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6631. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6632. begin
  6633. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6634. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6635. Inc(SourceRef.offset, 16);
  6636. { Reuse the register in the first block move }
  6637. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6638. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  6639. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  6640. begin
  6641. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6642. Inc(TargetRef.offset, 16);
  6643. if GetNextInstruction(hp2, hp3) and
  6644. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6645. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6646. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6647. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6648. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6649. begin
  6650. { Update the register tracking to the new size }
  6651. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6652. { Remember that the offsets are 16 ahead }
  6653. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6654. if not (
  6655. ((SourceRef.offset mod 32) = 16) and
  6656. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6657. ) then
  6658. taicpu(p).opcode := A_VMOVDQU;
  6659. taicpu(p).opsize := S_YMM;
  6660. taicpu(p).oper[1]^.reg := CurrentReg;
  6661. if not (
  6662. ((TargetRef.offset mod 32) = 16) and
  6663. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6664. ) then
  6665. taicpu(hp1).opcode := A_VMOVDQU;
  6666. taicpu(hp1).opsize := S_YMM;
  6667. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6668. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6669. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6670. if (pi_uses_ymm in current_procinfo.flags) then
  6671. RemoveInstruction(hp2)
  6672. else
  6673. begin
  6674. taicpu(hp2).opcode := A_VPXOR;
  6675. taicpu(hp2).opsize := S_YMM;
  6676. taicpu(hp2).loadreg(0, CurrentReg);
  6677. taicpu(hp2).loadreg(1, CurrentReg);
  6678. taicpu(hp2).loadreg(2, CurrentReg);
  6679. taicpu(hp2).ops := 3;
  6680. end;
  6681. RemoveInstruction(hp3);
  6682. Result := True;
  6683. Exit;
  6684. end;
  6685. end
  6686. else
  6687. begin
  6688. { See if the next references are 16 less rather than 16 greater }
  6689. Dec(SourceRef.offset, 32); { -16 the other way }
  6690. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6691. begin
  6692. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6693. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6694. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  6695. GetNextInstruction(hp2, hp3) and
  6696. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6697. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6698. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6699. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6700. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6701. begin
  6702. { Update the register tracking to the new size }
  6703. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6704. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6705. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6706. if not(
  6707. ((SourceRef.offset mod 32) = 0) and
  6708. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6709. ) then
  6710. taicpu(hp2).opcode := A_VMOVDQU;
  6711. taicpu(hp2).opsize := S_YMM;
  6712. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6713. if not (
  6714. ((TargetRef.offset mod 32) = 0) and
  6715. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6716. ) then
  6717. taicpu(hp3).opcode := A_VMOVDQU;
  6718. taicpu(hp3).opsize := S_YMM;
  6719. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6720. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6721. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6722. if (pi_uses_ymm in current_procinfo.flags) then
  6723. RemoveInstruction(hp1)
  6724. else
  6725. begin
  6726. taicpu(hp1).opcode := A_VPXOR;
  6727. taicpu(hp1).opsize := S_YMM;
  6728. taicpu(hp1).loadreg(0, CurrentReg);
  6729. taicpu(hp1).loadreg(1, CurrentReg);
  6730. taicpu(hp1).loadreg(2, CurrentReg);
  6731. taicpu(hp1).ops := 3;
  6732. Asml.Remove(hp1);
  6733. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6734. end;
  6735. RemoveCurrentP(p, hp2);
  6736. Result := True;
  6737. Exit;
  6738. end;
  6739. end;
  6740. end;
  6741. end;
  6742. end;
  6743. end;
  6744. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6745. var
  6746. hp2, hp3, first_assignment: tai;
  6747. IncCount, OperIdx: Integer;
  6748. OrigLabel: TAsmLabel;
  6749. begin
  6750. Count := 0;
  6751. Result := False;
  6752. first_assignment := nil;
  6753. if (LoopCount >= 20) then
  6754. begin
  6755. { Guard against infinite loops }
  6756. Exit;
  6757. end;
  6758. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6759. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6760. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6761. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6762. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6763. Exit;
  6764. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6765. {
  6766. change
  6767. jmp .L1
  6768. ...
  6769. .L1:
  6770. mov ##, ## ( multiple movs possible )
  6771. jmp/ret
  6772. into
  6773. mov ##, ##
  6774. jmp/ret
  6775. }
  6776. if not Assigned(hp1) then
  6777. begin
  6778. hp1 := GetLabelWithSym(OrigLabel);
  6779. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6780. Exit;
  6781. end;
  6782. hp2 := hp1;
  6783. while Assigned(hp2) do
  6784. begin
  6785. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6786. SkipLabels(hp2,hp2);
  6787. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6788. Break;
  6789. case taicpu(hp2).opcode of
  6790. A_MOVSS:
  6791. begin
  6792. if taicpu(hp2).ops = 0 then
  6793. { Wrong MOVSS }
  6794. Break;
  6795. Inc(Count);
  6796. if Count >= 5 then
  6797. { Too many to be worthwhile }
  6798. Break;
  6799. GetNextInstruction(hp2, hp2);
  6800. Continue;
  6801. end;
  6802. A_MOV,
  6803. A_MOVD,
  6804. A_MOVQ,
  6805. A_MOVSX,
  6806. {$ifdef x86_64}
  6807. A_MOVSXD,
  6808. {$endif x86_64}
  6809. A_MOVZX,
  6810. A_MOVAPS,
  6811. A_MOVUPS,
  6812. A_MOVSD,
  6813. A_MOVAPD,
  6814. A_MOVUPD,
  6815. A_MOVDQA,
  6816. A_MOVDQU,
  6817. A_VMOVSS,
  6818. A_VMOVAPS,
  6819. A_VMOVUPS,
  6820. A_VMOVSD,
  6821. A_VMOVAPD,
  6822. A_VMOVUPD,
  6823. A_VMOVDQA,
  6824. A_VMOVDQU:
  6825. begin
  6826. Inc(Count);
  6827. if Count >= 5 then
  6828. { Too many to be worthwhile }
  6829. Break;
  6830. GetNextInstruction(hp2, hp2);
  6831. Continue;
  6832. end;
  6833. A_JMP:
  6834. begin
  6835. { Guard against infinite loops }
  6836. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6837. Exit;
  6838. { Analyse this jump first in case it also duplicates assignments }
  6839. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6840. begin
  6841. { Something did change! }
  6842. Result := True;
  6843. Inc(Count, IncCount);
  6844. if Count >= 5 then
  6845. begin
  6846. { Too many to be worthwhile }
  6847. Exit;
  6848. end;
  6849. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6850. Break;
  6851. end;
  6852. Result := True;
  6853. Break;
  6854. end;
  6855. A_RET:
  6856. begin
  6857. Result := True;
  6858. Break;
  6859. end;
  6860. else
  6861. Break;
  6862. end;
  6863. end;
  6864. if Result then
  6865. begin
  6866. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6867. if Count = 0 then
  6868. begin
  6869. Result := False;
  6870. Exit;
  6871. end;
  6872. hp3 := p;
  6873. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6874. while True do
  6875. begin
  6876. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6877. SkipLabels(hp1,hp1);
  6878. if (hp1.typ <> ait_instruction) then
  6879. InternalError(2021040720);
  6880. case taicpu(hp1).opcode of
  6881. A_JMP:
  6882. begin
  6883. { Change the original jump to the new destination }
  6884. OrigLabel.decrefs;
  6885. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6886. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6887. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6888. if not Assigned(first_assignment) then
  6889. InternalError(2021040810)
  6890. else
  6891. p := first_assignment;
  6892. Exit;
  6893. end;
  6894. A_RET:
  6895. begin
  6896. { Now change the jump into a RET instruction }
  6897. ConvertJumpToRET(p, hp1);
  6898. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6899. if not Assigned(first_assignment) then
  6900. InternalError(2021040811)
  6901. else
  6902. p := first_assignment;
  6903. Exit;
  6904. end;
  6905. else
  6906. begin
  6907. { Duplicate the MOV instruction }
  6908. hp3:=tai(hp1.getcopy);
  6909. if first_assignment = nil then
  6910. first_assignment := hp3;
  6911. asml.InsertBefore(hp3, p);
  6912. { Make sure the compiler knows about any final registers written here }
  6913. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6914. with taicpu(hp3).oper[OperIdx]^ do
  6915. begin
  6916. case typ of
  6917. top_ref:
  6918. begin
  6919. if (ref^.base <> NR_NO) and
  6920. (getsupreg(ref^.base) <> RS_ESP) and
  6921. (getsupreg(ref^.base) <> RS_EBP)
  6922. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6923. then
  6924. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6925. if (ref^.index <> NR_NO) and
  6926. (getsupreg(ref^.index) <> RS_ESP) and
  6927. (getsupreg(ref^.index) <> RS_EBP)
  6928. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6929. (ref^.index <> ref^.base) then
  6930. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6931. end;
  6932. top_reg:
  6933. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6934. else
  6935. ;
  6936. end;
  6937. end;
  6938. end;
  6939. end;
  6940. if not GetNextInstruction(hp1, hp1) then
  6941. { Should have dropped out earlier }
  6942. InternalError(2021040710);
  6943. end;
  6944. end;
  6945. end;
  6946. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6947. var
  6948. hp2: tai;
  6949. X: Integer;
  6950. const
  6951. WriteOp: array[0..3] of set of TInsChange = (
  6952. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6953. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6954. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6955. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6956. RegWriteFlags: array[0..7] of set of TInsChange = (
  6957. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6958. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6959. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6960. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6961. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6962. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6963. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6964. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6965. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6966. begin
  6967. { If we have something like:
  6968. cmp ###,%reg1
  6969. mov 0,%reg2
  6970. And no modified registers are shared, move the instruction to before
  6971. the comparison as this means it can be optimised without worrying
  6972. about the FLAGS register. (CMP/MOV is generated by
  6973. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6974. As long as the second instruction doesn't use the flags or one of the
  6975. registers used by CMP or TEST (also check any references that use the
  6976. registers), then it can be moved prior to the comparison.
  6977. }
  6978. Result := False;
  6979. if (hp1.typ <> ait_instruction) or
  6980. taicpu(hp1).is_jmp or
  6981. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6982. Exit;
  6983. { NOP is a pipeline fence, likely marking the beginning of the function
  6984. epilogue, so drop out. Similarly, drop out if POP or RET are
  6985. encountered }
  6986. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6987. Exit;
  6988. if (taicpu(hp1).opcode = A_MOVSS) and
  6989. (taicpu(hp1).ops = 0) then
  6990. { Wrong MOVSS }
  6991. Exit;
  6992. { Check for writes to specific registers first }
  6993. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  6994. for X := 0 to 7 do
  6995. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  6996. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  6997. Exit;
  6998. for X := 0 to taicpu(hp1).ops - 1 do
  6999. begin
  7000. { Check to see if this operand writes to something }
  7001. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7002. { And matches something in the CMP/TEST instruction }
  7003. (
  7004. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7005. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7006. (
  7007. { If it's a register, make sure the register written to doesn't
  7008. appear in the cmp instruction as part of a reference }
  7009. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7010. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7011. )
  7012. ) then
  7013. Exit;
  7014. end;
  7015. { The instruction can be safely moved }
  7016. asml.Remove(hp1);
  7017. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  7018. if not GetLastInstruction(p, hp2) then
  7019. asml.InsertBefore(hp1, p)
  7020. else
  7021. asml.InsertAfter(hp1, hp2);
  7022. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7023. for X := 0 to taicpu(hp1).ops - 1 do
  7024. case taicpu(hp1).oper[X]^.typ of
  7025. top_reg:
  7026. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7027. top_ref:
  7028. begin
  7029. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7030. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7031. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7032. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7033. end;
  7034. else
  7035. ;
  7036. end;
  7037. if taicpu(hp1).opcode = A_LEA then
  7038. { The flags will be overwritten by the CMP/TEST instruction }
  7039. ConvertLEA(taicpu(hp1));
  7040. Result := True;
  7041. end;
  7042. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7043. function IsXCHGAcceptable: Boolean; inline;
  7044. begin
  7045. { Always accept if optimising for size }
  7046. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7047. (
  7048. {$ifdef x86_64}
  7049. { XCHG takes 3 cycles on AMD Athlon64 }
  7050. (current_settings.optimizecputype >= cpu_core_i)
  7051. {$else x86_64}
  7052. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7053. than 3, so it becomes a saving compared to three MOVs with two of
  7054. them able to execute simultaneously. [Kit] }
  7055. (current_settings.optimizecputype >= cpu_PentiumM)
  7056. {$endif x86_64}
  7057. );
  7058. end;
  7059. var
  7060. NewRef: TReference;
  7061. hp1, hp2, hp3, hp4: Tai;
  7062. {$ifndef x86_64}
  7063. OperIdx: Integer;
  7064. {$endif x86_64}
  7065. NewInstr : Taicpu;
  7066. NewAligh : Tai_align;
  7067. DestLabel: TAsmLabel;
  7068. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7069. var
  7070. NextInstr: tai;
  7071. begin
  7072. Result := False;
  7073. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7074. if not GetNextInstruction(InputInstr, NextInstr) or
  7075. (
  7076. { The FLAGS register isn't always tracked properly, so do not
  7077. perform this optimisation if a conditional statement follows }
  7078. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7079. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7080. ) then
  7081. begin
  7082. reference_reset(NewRef, 1, []);
  7083. NewRef.base := taicpu(p).oper[0]^.reg;
  7084. NewRef.scalefactor := 1;
  7085. if taicpu(InputInstr).opcode = A_ADD then
  7086. begin
  7087. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7088. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7089. end
  7090. else
  7091. begin
  7092. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7093. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7094. end;
  7095. taicpu(p).opcode := A_LEA;
  7096. taicpu(p).loadref(0, NewRef);
  7097. RemoveInstruction(InputInstr);
  7098. Result := True;
  7099. end;
  7100. end;
  7101. begin
  7102. Result:=false;
  7103. { This optimisation adds an instruction, so only do it for speed }
  7104. if not (cs_opt_size in current_settings.optimizerswitches) and
  7105. MatchOpType(taicpu(p), top_const, top_reg) and
  7106. (taicpu(p).oper[0]^.val = 0) then
  7107. begin
  7108. { To avoid compiler warning }
  7109. DestLabel := nil;
  7110. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7111. InternalError(2021040750);
  7112. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7113. Exit;
  7114. case hp1.typ of
  7115. ait_label:
  7116. begin
  7117. { Change:
  7118. mov $0,%reg mov $0,%reg
  7119. @Lbl1: @Lbl1:
  7120. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7121. je @Lbl2 jne @Lbl2
  7122. To: To:
  7123. mov $0,%reg mov $0,%reg
  7124. jmp @Lbl2 jmp @Lbl3
  7125. (align) (align)
  7126. @Lbl1: @Lbl1:
  7127. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7128. je @Lbl2 je @Lbl2
  7129. @Lbl3: <-- Only if label exists
  7130. (Not if it's optimised for size)
  7131. }
  7132. if not GetNextInstruction(hp1, hp2) then
  7133. Exit;
  7134. if not (cs_opt_size in current_settings.optimizerswitches) and
  7135. (hp2.typ = ait_instruction) and
  7136. (
  7137. { Register sizes must exactly match }
  7138. (
  7139. (taicpu(hp2).opcode = A_CMP) and
  7140. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7141. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7142. ) or (
  7143. (taicpu(hp2).opcode = A_TEST) and
  7144. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7145. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7146. )
  7147. ) and GetNextInstruction(hp2, hp3) and
  7148. (hp3.typ = ait_instruction) and
  7149. (taicpu(hp3).opcode = A_JCC) and
  7150. (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
  7151. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7152. begin
  7153. { Check condition of jump }
  7154. { Always true? }
  7155. if condition_in(C_E, taicpu(hp3).condition) then
  7156. begin
  7157. { Copy label symbol and obtain matching label entry for the
  7158. conditional jump, as this will be our destination}
  7159. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7160. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7161. Result := True;
  7162. end
  7163. { Always false? }
  7164. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7165. begin
  7166. { This is only worth it if there's a jump to take }
  7167. case hp2.typ of
  7168. ait_instruction:
  7169. begin
  7170. if taicpu(hp2).opcode = A_JMP then
  7171. begin
  7172. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7173. { An unconditional jump follows the conditional jump which will always be false,
  7174. so use this jump's destination for the new jump }
  7175. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7176. Result := True;
  7177. end
  7178. else if taicpu(hp2).opcode = A_JCC then
  7179. begin
  7180. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7181. if condition_in(C_E, taicpu(hp2).condition) then
  7182. begin
  7183. { A second conditional jump follows the conditional jump which will always be false,
  7184. while the second jump is always True, so use this jump's destination for the new jump }
  7185. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7186. Result := True;
  7187. end;
  7188. { Don't risk it if the jump isn't always true (Result remains False) }
  7189. end;
  7190. end;
  7191. else
  7192. { If anything else don't optimise };
  7193. end;
  7194. end;
  7195. if Result then
  7196. begin
  7197. { Just so we have something to insert as a paremeter}
  7198. reference_reset(NewRef, 1, []);
  7199. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7200. { Now actually load the correct parameter }
  7201. NewInstr.loadsymbol(0, DestLabel, 0);
  7202. { Get instruction before original label (may not be p under -O3) }
  7203. if not GetLastInstruction(hp1, hp2) then
  7204. { Shouldn't fail here }
  7205. InternalError(2021040701);
  7206. DestLabel.increfs;
  7207. AsmL.InsertAfter(NewInstr, hp2);
  7208. { Add new alignment field }
  7209. (* AsmL.InsertAfter(
  7210. cai_align.create_max(
  7211. current_settings.alignment.jumpalign,
  7212. current_settings.alignment.jumpalignskipmax
  7213. ),
  7214. NewInstr
  7215. ); *)
  7216. end;
  7217. Exit;
  7218. end;
  7219. end;
  7220. else
  7221. ;
  7222. end;
  7223. end;
  7224. if not GetNextInstruction(p, hp1) then
  7225. Exit;
  7226. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7227. and DoMovCmpMemOpt(p, hp1, True) then
  7228. begin
  7229. Result := True;
  7230. Exit;
  7231. end
  7232. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7233. begin
  7234. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7235. further, but we can't just put this jump optimisation in pass 1
  7236. because it tends to perform worse when conditional jumps are
  7237. nearby (e.g. when converting CMOV instructions). [Kit] }
  7238. if OptPass2JMP(hp1) then
  7239. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7240. Result := OptPass1MOV(p)
  7241. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7242. returned True and the instruction is still a MOV, thus checking
  7243. the optimisations below }
  7244. { If OptPass2JMP returned False, no optimisations were done to
  7245. the jump and there are no further optimisations that can be done
  7246. to the MOV instruction on this pass }
  7247. end
  7248. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7249. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7250. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7251. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7252. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7253. begin
  7254. { Change:
  7255. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7256. addl/q $x,%reg2 subl/q $x,%reg2
  7257. To:
  7258. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7259. }
  7260. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7261. { be lazy, checking separately for sub would be slightly better }
  7262. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7263. begin
  7264. TransferUsedRegs(TmpUsedRegs);
  7265. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7266. if TryMovArith2Lea(hp1) then
  7267. begin
  7268. Result := True;
  7269. Exit;
  7270. end
  7271. end
  7272. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7273. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7274. { Same as above, but also adds or subtracts to %reg2 in between.
  7275. It's still valid as long as the flags aren't in use }
  7276. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7277. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7278. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7279. { be lazy, checking separately for sub would be slightly better }
  7280. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7281. begin
  7282. TransferUsedRegs(TmpUsedRegs);
  7283. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7284. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7285. if TryMovArith2Lea(hp2) then
  7286. begin
  7287. Result := True;
  7288. Exit;
  7289. end;
  7290. end;
  7291. end
  7292. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7293. {$ifdef x86_64}
  7294. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7295. {$else x86_64}
  7296. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7297. {$endif x86_64}
  7298. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7299. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7300. { mov reg1, reg2 mov reg1, reg2
  7301. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7302. begin
  7303. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7304. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7305. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7306. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7307. TransferUsedRegs(TmpUsedRegs);
  7308. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7309. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7310. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7311. then
  7312. begin
  7313. RemoveCurrentP(p, hp1);
  7314. Result:=true;
  7315. end;
  7316. exit;
  7317. end
  7318. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7319. IsXCHGAcceptable and
  7320. { XCHG doesn't support 8-byte registers }
  7321. (taicpu(p).opsize <> S_B) and
  7322. MatchInstruction(hp1, A_MOV, []) and
  7323. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7324. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7325. GetNextInstruction(hp1, hp2) and
  7326. MatchInstruction(hp2, A_MOV, []) and
  7327. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7328. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7329. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7330. begin
  7331. { mov %reg1,%reg2
  7332. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7333. mov %reg2,%reg3
  7334. (%reg2 not used afterwards)
  7335. Note that xchg takes 3 cycles to execute, and generally mov's take
  7336. only one cycle apiece, but the first two mov's can be executed in
  7337. parallel, only taking 2 cycles overall. Older processors should
  7338. therefore only optimise for size. [Kit]
  7339. }
  7340. TransferUsedRegs(TmpUsedRegs);
  7341. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7342. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7343. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7344. begin
  7345. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7346. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7347. taicpu(hp1).opcode := A_XCHG;
  7348. RemoveCurrentP(p, hp1);
  7349. RemoveInstruction(hp2);
  7350. Result := True;
  7351. Exit;
  7352. end;
  7353. end
  7354. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7355. MatchInstruction(hp1, A_SAR, []) then
  7356. begin
  7357. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7358. begin
  7359. { the use of %edx also covers the opsize being S_L }
  7360. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7361. begin
  7362. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7363. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7364. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7365. begin
  7366. { Change:
  7367. movl %eax,%edx
  7368. sarl $31,%edx
  7369. To:
  7370. cltd
  7371. }
  7372. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7373. RemoveInstruction(hp1);
  7374. taicpu(p).opcode := A_CDQ;
  7375. taicpu(p).opsize := S_NO;
  7376. taicpu(p).clearop(1);
  7377. taicpu(p).clearop(0);
  7378. taicpu(p).ops:=0;
  7379. Result := True;
  7380. end
  7381. else if (cs_opt_size in current_settings.optimizerswitches) and
  7382. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7383. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7384. begin
  7385. { Change:
  7386. movl %edx,%eax
  7387. sarl $31,%edx
  7388. To:
  7389. movl %edx,%eax
  7390. cltd
  7391. Note that this creates a dependency between the two instructions,
  7392. so only perform if optimising for size.
  7393. }
  7394. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7395. taicpu(hp1).opcode := A_CDQ;
  7396. taicpu(hp1).opsize := S_NO;
  7397. taicpu(hp1).clearop(1);
  7398. taicpu(hp1).clearop(0);
  7399. taicpu(hp1).ops:=0;
  7400. end;
  7401. {$ifndef x86_64}
  7402. end
  7403. { Don't bother if CMOV is supported, because a more optimal
  7404. sequence would have been generated for the Abs() intrinsic }
  7405. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7406. { the use of %eax also covers the opsize being S_L }
  7407. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7408. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7409. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7410. GetNextInstruction(hp1, hp2) and
  7411. MatchInstruction(hp2, A_XOR, [S_L]) and
  7412. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7413. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7414. GetNextInstruction(hp2, hp3) and
  7415. MatchInstruction(hp3, A_SUB, [S_L]) and
  7416. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7417. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7418. begin
  7419. { Change:
  7420. movl %eax,%edx
  7421. sarl $31,%eax
  7422. xorl %eax,%edx
  7423. subl %eax,%edx
  7424. (Instruction that uses %edx)
  7425. (%eax deallocated)
  7426. (%edx deallocated)
  7427. To:
  7428. cltd
  7429. xorl %edx,%eax <-- Note the registers have swapped
  7430. subl %edx,%eax
  7431. (Instruction that uses %eax) <-- %eax rather than %edx
  7432. }
  7433. TransferUsedRegs(TmpUsedRegs);
  7434. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7435. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7436. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7437. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7438. begin
  7439. if GetNextInstruction(hp3, hp4) and
  7440. not RegModifiedByInstruction(NR_EDX, hp4) and
  7441. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7442. begin
  7443. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7444. taicpu(p).opcode := A_CDQ;
  7445. taicpu(p).clearop(1);
  7446. taicpu(p).clearop(0);
  7447. taicpu(p).ops:=0;
  7448. RemoveInstruction(hp1);
  7449. taicpu(hp2).loadreg(0, NR_EDX);
  7450. taicpu(hp2).loadreg(1, NR_EAX);
  7451. taicpu(hp3).loadreg(0, NR_EDX);
  7452. taicpu(hp3).loadreg(1, NR_EAX);
  7453. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7454. { Convert references in the following instruction (hp4) from %edx to %eax }
  7455. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7456. with taicpu(hp4).oper[OperIdx]^ do
  7457. case typ of
  7458. top_reg:
  7459. if getsupreg(reg) = RS_EDX then
  7460. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7461. top_ref:
  7462. begin
  7463. if getsupreg(reg) = RS_EDX then
  7464. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7465. if getsupreg(reg) = RS_EDX then
  7466. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7467. end;
  7468. else
  7469. ;
  7470. end;
  7471. end;
  7472. end;
  7473. {$else x86_64}
  7474. end;
  7475. end
  7476. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7477. { the use of %rdx also covers the opsize being S_Q }
  7478. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7479. begin
  7480. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7481. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7482. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7483. begin
  7484. { Change:
  7485. movq %rax,%rdx
  7486. sarq $63,%rdx
  7487. To:
  7488. cqto
  7489. }
  7490. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7491. RemoveInstruction(hp1);
  7492. taicpu(p).opcode := A_CQO;
  7493. taicpu(p).opsize := S_NO;
  7494. taicpu(p).clearop(1);
  7495. taicpu(p).clearop(0);
  7496. taicpu(p).ops:=0;
  7497. Result := True;
  7498. end
  7499. else if (cs_opt_size in current_settings.optimizerswitches) and
  7500. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7501. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7502. begin
  7503. { Change:
  7504. movq %rdx,%rax
  7505. sarq $63,%rdx
  7506. To:
  7507. movq %rdx,%rax
  7508. cqto
  7509. Note that this creates a dependency between the two instructions,
  7510. so only perform if optimising for size.
  7511. }
  7512. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7513. taicpu(hp1).opcode := A_CQO;
  7514. taicpu(hp1).opsize := S_NO;
  7515. taicpu(hp1).clearop(1);
  7516. taicpu(hp1).clearop(0);
  7517. taicpu(hp1).ops:=0;
  7518. {$endif x86_64}
  7519. end;
  7520. end;
  7521. end
  7522. else if MatchInstruction(hp1, A_MOV, []) and
  7523. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7524. { Though "GetNextInstruction" could be factored out, along with
  7525. the instructions that depend on hp2, it is an expensive call that
  7526. should be delayed for as long as possible, hence we do cheaper
  7527. checks first that are likely to be False. [Kit] }
  7528. begin
  7529. if (
  7530. (
  7531. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7532. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7533. (
  7534. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7535. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7536. )
  7537. ) or
  7538. (
  7539. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7540. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7541. (
  7542. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7543. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7544. )
  7545. )
  7546. ) and
  7547. GetNextInstruction(hp1, hp2) and
  7548. MatchInstruction(hp2, A_SAR, []) and
  7549. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7550. begin
  7551. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7552. begin
  7553. { Change:
  7554. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7555. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7556. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7557. To:
  7558. movl r/m,%eax <- Note the change in register
  7559. cltd
  7560. }
  7561. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7562. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7563. taicpu(p).loadreg(1, NR_EAX);
  7564. taicpu(hp1).opcode := A_CDQ;
  7565. taicpu(hp1).clearop(1);
  7566. taicpu(hp1).clearop(0);
  7567. taicpu(hp1).ops:=0;
  7568. RemoveInstruction(hp2);
  7569. (*
  7570. {$ifdef x86_64}
  7571. end
  7572. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7573. { This code sequence does not get generated - however it might become useful
  7574. if and when 128-bit signed integer types make an appearance, so the code
  7575. is kept here for when it is eventually needed. [Kit] }
  7576. (
  7577. (
  7578. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7579. (
  7580. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7581. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7582. )
  7583. ) or
  7584. (
  7585. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7586. (
  7587. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7588. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7589. )
  7590. )
  7591. ) and
  7592. GetNextInstruction(hp1, hp2) and
  7593. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7594. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7595. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7596. begin
  7597. { Change:
  7598. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7599. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7600. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7601. To:
  7602. movq r/m,%rax <- Note the change in register
  7603. cqto
  7604. }
  7605. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7606. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7607. taicpu(p).loadreg(1, NR_RAX);
  7608. taicpu(hp1).opcode := A_CQO;
  7609. taicpu(hp1).clearop(1);
  7610. taicpu(hp1).clearop(0);
  7611. taicpu(hp1).ops:=0;
  7612. RemoveInstruction(hp2);
  7613. {$endif x86_64}
  7614. *)
  7615. end;
  7616. end;
  7617. {$ifdef x86_64}
  7618. end
  7619. else if (taicpu(p).opsize = S_L) and
  7620. (taicpu(p).oper[1]^.typ = top_reg) and
  7621. (
  7622. MatchInstruction(hp1, A_MOV,[]) and
  7623. (taicpu(hp1).opsize = S_L) and
  7624. (taicpu(hp1).oper[1]^.typ = top_reg)
  7625. ) and (
  7626. GetNextInstruction(hp1, hp2) and
  7627. (tai(hp2).typ=ait_instruction) and
  7628. (taicpu(hp2).opsize = S_Q) and
  7629. (
  7630. (
  7631. MatchInstruction(hp2, A_ADD,[]) and
  7632. (taicpu(hp2).opsize = S_Q) and
  7633. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7634. (
  7635. (
  7636. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7637. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7638. ) or (
  7639. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7640. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7641. )
  7642. )
  7643. ) or (
  7644. MatchInstruction(hp2, A_LEA,[]) and
  7645. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7646. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7647. (
  7648. (
  7649. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7650. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7651. ) or (
  7652. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7653. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7654. )
  7655. ) and (
  7656. (
  7657. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7658. ) or (
  7659. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7660. )
  7661. )
  7662. )
  7663. )
  7664. ) and (
  7665. GetNextInstruction(hp2, hp3) and
  7666. MatchInstruction(hp3, A_SHR,[]) and
  7667. (taicpu(hp3).opsize = S_Q) and
  7668. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7669. (taicpu(hp3).oper[0]^.val = 1) and
  7670. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7671. ) then
  7672. begin
  7673. { Change movl x, reg1d movl x, reg1d
  7674. movl y, reg2d movl y, reg2d
  7675. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7676. shrq $1, reg1q shrq $1, reg1q
  7677. ( reg1d and reg2d can be switched around in the first two instructions )
  7678. To movl x, reg1d
  7679. addl y, reg1d
  7680. rcrl $1, reg1d
  7681. This corresponds to the common expression (x + y) shr 1, where
  7682. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7683. smaller code, but won't account for x + y causing an overflow). [Kit]
  7684. }
  7685. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7686. { Change first MOV command to have the same register as the final output }
  7687. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7688. else
  7689. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7690. { Change second MOV command to an ADD command. This is easier than
  7691. converting the existing command because it means we don't have to
  7692. touch 'y', which might be a complicated reference, and also the
  7693. fact that the third command might either be ADD or LEA. [Kit] }
  7694. taicpu(hp1).opcode := A_ADD;
  7695. { Delete old ADD/LEA instruction }
  7696. RemoveInstruction(hp2);
  7697. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7698. taicpu(hp3).opcode := A_RCR;
  7699. taicpu(hp3).changeopsize(S_L);
  7700. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7701. {$endif x86_64}
  7702. end;
  7703. end;
  7704. {$push}
  7705. {$q-}{$r-}
  7706. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7707. var
  7708. ThisReg: TRegister;
  7709. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7710. TargetSubReg: TSubRegister;
  7711. hp1, hp2: tai;
  7712. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  7713. { Store list of found instructions so we don't have to call
  7714. GetNextInstructionUsingReg multiple times }
  7715. InstrList: array of taicpu;
  7716. InstrMax, Index: Integer;
  7717. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7718. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7719. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7720. WorkingValue: TCgInt;
  7721. PreMessage: string;
  7722. { Data flow analysis }
  7723. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7724. BitwiseOnly, OrXorUsed,
  7725. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7726. function CheckOverflowConditions: Boolean;
  7727. begin
  7728. Result := True;
  7729. if (TestValSignedMax > SignedUpperLimit) then
  7730. UpperSignedOverflow := True;
  7731. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7732. LowerSignedOverflow := True;
  7733. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7734. LowerUnsignedOverflow := True;
  7735. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7736. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7737. begin
  7738. { Absolute overflow }
  7739. Result := False;
  7740. Exit;
  7741. end;
  7742. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7743. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7744. ShiftDownOverflow := True;
  7745. if (TestValMin < 0) or (TestValMax < 0) then
  7746. begin
  7747. LowerUnsignedOverflow := True;
  7748. UpperUnsignedOverflow := True;
  7749. end;
  7750. end;
  7751. function AdjustInitialLoadAndSize: Boolean;
  7752. begin
  7753. Result := False;
  7754. if not p_removed then
  7755. begin
  7756. if TargetSize = MinSize then
  7757. begin
  7758. { Convert the input MOVZX to a MOV }
  7759. if (taicpu(p).oper[0]^.typ = top_reg) and
  7760. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7761. begin
  7762. { Or remove it completely! }
  7763. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7764. RemoveCurrentP(p);
  7765. p_removed := True;
  7766. end
  7767. else
  7768. begin
  7769. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7770. taicpu(p).opcode := A_MOV;
  7771. taicpu(p).oper[1]^.reg := ThisReg;
  7772. taicpu(p).opsize := TargetSize;
  7773. end;
  7774. Result := True;
  7775. end
  7776. else if TargetSize <> MaxSize then
  7777. begin
  7778. case MaxSize of
  7779. S_L:
  7780. if TargetSize = S_W then
  7781. begin
  7782. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7783. taicpu(p).opsize := S_BW;
  7784. taicpu(p).oper[1]^.reg := ThisReg;
  7785. Result := True;
  7786. end
  7787. else
  7788. InternalError(2020112341);
  7789. S_W:
  7790. if TargetSize = S_L then
  7791. begin
  7792. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7793. taicpu(p).opsize := S_BL;
  7794. taicpu(p).oper[1]^.reg := ThisReg;
  7795. Result := True;
  7796. end
  7797. else
  7798. InternalError(2020112342);
  7799. else
  7800. ;
  7801. end;
  7802. end
  7803. else if not hp1_removed and not RegInUse then
  7804. begin
  7805. { If we have something like:
  7806. movzbl (oper),%regd
  7807. add x, %regd
  7808. movzbl %regb, %regd
  7809. We can reduce the register size to the input of the final
  7810. movzbl instruction. Overflows won't have any effect.
  7811. }
  7812. if (taicpu(p).opsize in [S_BW, S_BL]) and
  7813. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  7814. begin
  7815. TargetSize := S_B;
  7816. setsubreg(ThisReg, R_SUBL);
  7817. Result := True;
  7818. end
  7819. else if (taicpu(p).opsize = S_WL) and
  7820. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  7821. begin
  7822. TargetSize := S_W;
  7823. setsubreg(ThisReg, R_SUBW);
  7824. Result := True;
  7825. end;
  7826. if Result then
  7827. begin
  7828. { Convert the input MOVZX to a MOV }
  7829. if (taicpu(p).oper[0]^.typ = top_reg) and
  7830. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7831. begin
  7832. { Or remove it completely! }
  7833. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  7834. RemoveCurrentP(p);
  7835. p_removed := True;
  7836. end
  7837. else
  7838. begin
  7839. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  7840. taicpu(p).opcode := A_MOV;
  7841. taicpu(p).oper[1]^.reg := ThisReg;
  7842. taicpu(p).opsize := TargetSize;
  7843. end;
  7844. end;
  7845. end;
  7846. end;
  7847. end;
  7848. procedure AdjustFinalLoad;
  7849. begin
  7850. if not LowerUnsignedOverflow then
  7851. begin
  7852. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7853. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7854. begin
  7855. { Convert the output MOVZX to a MOV }
  7856. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7857. begin
  7858. { Or remove it completely! }
  7859. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7860. { Be careful; if p = hp1 and p was also removed, p
  7861. will become a dangling pointer }
  7862. if p = hp1 then
  7863. begin
  7864. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7865. p_removed := True;
  7866. end
  7867. else
  7868. RemoveInstruction(hp1);
  7869. hp1_removed := True;
  7870. end
  7871. else
  7872. begin
  7873. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7874. taicpu(hp1).opcode := A_MOV;
  7875. taicpu(hp1).oper[0]^.reg := ThisReg;
  7876. taicpu(hp1).opsize := TargetSize;
  7877. end;
  7878. end
  7879. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  7880. begin
  7881. { Need to change the size of the output }
  7882. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  7883. taicpu(hp1).oper[0]^.reg := ThisReg;
  7884. taicpu(hp1).opsize := S_BL;
  7885. end;
  7886. end;
  7887. end;
  7888. function CompressInstructions: Boolean;
  7889. var
  7890. LocalIndex: Integer;
  7891. begin
  7892. Result := False;
  7893. { The objective here is to try to find a combination that
  7894. removes one of the MOV/Z instructions. }
  7895. if (
  7896. (taicpu(p).oper[0]^.typ <> top_reg) or
  7897. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  7898. ) and
  7899. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7900. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7901. begin
  7902. { Make a preference to remove the second MOVZX instruction }
  7903. case taicpu(hp1).opsize of
  7904. S_BL, S_WL:
  7905. begin
  7906. TargetSize := S_L;
  7907. TargetSubReg := R_SUBD;
  7908. end;
  7909. S_BW:
  7910. begin
  7911. TargetSize := S_W;
  7912. TargetSubReg := R_SUBW;
  7913. end;
  7914. else
  7915. InternalError(2020112302);
  7916. end;
  7917. end
  7918. else
  7919. begin
  7920. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7921. begin
  7922. { Exceeded lower bound but not upper bound }
  7923. TargetSize := MaxSize;
  7924. end
  7925. else if not LowerUnsignedOverflow then
  7926. begin
  7927. { Size didn't exceed lower bound }
  7928. TargetSize := MinSize;
  7929. end
  7930. else
  7931. Exit;
  7932. end;
  7933. case TargetSize of
  7934. S_B:
  7935. TargetSubReg := R_SUBL;
  7936. S_W:
  7937. TargetSubReg := R_SUBW;
  7938. S_L:
  7939. TargetSubReg := R_SUBD;
  7940. else
  7941. InternalError(2020112350);
  7942. end;
  7943. { Update the register to its new size }
  7944. setsubreg(ThisReg, TargetSubReg);
  7945. RegInUse := False;
  7946. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7947. begin
  7948. { Check to see if the active register is used afterwards;
  7949. if not, we can change it and make a saving. }
  7950. TransferUsedRegs(TmpUsedRegs);
  7951. { The target register may be marked as in use to cross
  7952. a jump to a distant label, so exclude it }
  7953. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7954. hp2 := p;
  7955. repeat
  7956. { Explicitly check for the excluded register (don't include the first
  7957. instruction as it may be reading from here }
  7958. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7959. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7960. begin
  7961. RegInUse := True;
  7962. Break;
  7963. end;
  7964. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7965. if not GetNextInstruction(hp2, hp2) then
  7966. InternalError(2020112340);
  7967. until (hp2 = hp1);
  7968. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7969. { We might still be able to get away with this }
  7970. RegInUse := not
  7971. (
  7972. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  7973. (hp2.typ = ait_instruction) and
  7974. (
  7975. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7976. instruction that doesn't actually contain ThisReg }
  7977. (cs_opt_level3 in current_settings.optimizerswitches) or
  7978. RegInInstruction(ThisReg, hp2)
  7979. ) and
  7980. RegLoadedWithNewValue(ThisReg, hp2)
  7981. );
  7982. if not RegInUse then
  7983. begin
  7984. { Force the register size to the same as this instruction so it can be removed}
  7985. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  7986. begin
  7987. TargetSize := S_L;
  7988. TargetSubReg := R_SUBD;
  7989. end
  7990. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  7991. begin
  7992. TargetSize := S_W;
  7993. TargetSubReg := R_SUBW;
  7994. end;
  7995. ThisReg := taicpu(hp1).oper[1]^.reg;
  7996. setsubreg(ThisReg, TargetSubReg);
  7997. RegChanged := True;
  7998. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  7999. TransferUsedRegs(TmpUsedRegs);
  8000. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8001. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8002. if p = hp1 then
  8003. begin
  8004. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8005. p_removed := True;
  8006. end
  8007. else
  8008. RemoveInstruction(hp1);
  8009. hp1_removed := True;
  8010. { Instruction will become "mov %reg,%reg" }
  8011. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8012. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8013. begin
  8014. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8015. RemoveCurrentP(p);
  8016. p_removed := True;
  8017. end
  8018. else
  8019. taicpu(p).oper[1]^.reg := ThisReg;
  8020. Result := True;
  8021. end
  8022. else
  8023. begin
  8024. if TargetSize <> MaxSize then
  8025. begin
  8026. { Since the register is in use, we have to force it to
  8027. MaxSize otherwise part of it may become undefined later on }
  8028. TargetSize := MaxSize;
  8029. case TargetSize of
  8030. S_B:
  8031. TargetSubReg := R_SUBL;
  8032. S_W:
  8033. TargetSubReg := R_SUBW;
  8034. S_L:
  8035. TargetSubReg := R_SUBD;
  8036. else
  8037. InternalError(2020112351);
  8038. end;
  8039. setsubreg(ThisReg, TargetSubReg);
  8040. end;
  8041. AdjustFinalLoad;
  8042. end;
  8043. end
  8044. else
  8045. AdjustFinalLoad;
  8046. Result := AdjustInitialLoadAndSize or Result;
  8047. { Now go through every instruction we found and change the
  8048. size. If TargetSize = MaxSize, then almost no changes are
  8049. needed and Result can remain False if it hasn't been set
  8050. yet.
  8051. If RegChanged is True, then the register requires changing
  8052. and so the point about TargetSize = MaxSize doesn't apply. }
  8053. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8054. begin
  8055. for LocalIndex := 0 to InstrMax do
  8056. begin
  8057. { If p_removed is true, then the original MOV/Z was removed
  8058. and removing the AND instruction may not be safe if it
  8059. appears first }
  8060. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8061. InternalError(2020112310);
  8062. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8063. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8064. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8065. InstrList[LocalIndex].opsize := TargetSize;
  8066. end;
  8067. Result := True;
  8068. end;
  8069. end;
  8070. begin
  8071. Result := False;
  8072. p_removed := False;
  8073. hp1_removed := False;
  8074. ThisReg := taicpu(p).oper[1]^.reg;
  8075. { Check for:
  8076. movs/z ###,%ecx (or %cx or %rcx)
  8077. ...
  8078. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8079. (dealloc %ecx)
  8080. Change to:
  8081. mov ###,%cl (if ### = %cl, then remove completely)
  8082. ...
  8083. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8084. }
  8085. if (getsupreg(ThisReg) = RS_ECX) and
  8086. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8087. (hp1.typ = ait_instruction) and
  8088. (
  8089. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8090. instruction that doesn't actually contain ECX }
  8091. (cs_opt_level3 in current_settings.optimizerswitches) or
  8092. RegInInstruction(NR_ECX, hp1) or
  8093. (
  8094. { It's common for the shift/rotate's read/write register to be
  8095. initialised in between, so under -O2 and under, search ahead
  8096. one more instruction
  8097. }
  8098. GetNextInstruction(hp1, hp1) and
  8099. (hp1.typ = ait_instruction) and
  8100. RegInInstruction(NR_ECX, hp1)
  8101. )
  8102. ) and
  8103. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8104. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8105. begin
  8106. TransferUsedRegs(TmpUsedRegs);
  8107. hp2 := p;
  8108. repeat
  8109. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8110. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8111. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8112. begin
  8113. case taicpu(p).opsize of
  8114. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8115. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8116. begin
  8117. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8118. RemoveCurrentP(p);
  8119. end
  8120. else
  8121. begin
  8122. taicpu(p).opcode := A_MOV;
  8123. taicpu(p).opsize := S_B;
  8124. taicpu(p).oper[1]^.reg := NR_CL;
  8125. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8126. end;
  8127. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8128. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8129. begin
  8130. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8131. RemoveCurrentP(p);
  8132. end
  8133. else
  8134. begin
  8135. taicpu(p).opcode := A_MOV;
  8136. taicpu(p).opsize := S_W;
  8137. taicpu(p).oper[1]^.reg := NR_CX;
  8138. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8139. end;
  8140. {$ifdef x86_64}
  8141. S_LQ:
  8142. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8143. begin
  8144. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8145. RemoveCurrentP(p);
  8146. end
  8147. else
  8148. begin
  8149. taicpu(p).opcode := A_MOV;
  8150. taicpu(p).opsize := S_L;
  8151. taicpu(p).oper[1]^.reg := NR_ECX;
  8152. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8153. end;
  8154. {$endif x86_64}
  8155. else
  8156. InternalError(2021120401);
  8157. end;
  8158. Result := True;
  8159. Exit;
  8160. end;
  8161. end;
  8162. { This is anything but quick! }
  8163. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8164. Exit;
  8165. SetLength(InstrList, 0);
  8166. InstrMax := -1;
  8167. case taicpu(p).opsize of
  8168. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8169. begin
  8170. {$if defined(i386) or defined(i8086)}
  8171. { If the target size is 8-bit, make sure we can actually encode it }
  8172. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8173. Exit;
  8174. {$endif i386 or i8086}
  8175. LowerLimit := $FF;
  8176. SignedLowerLimit := $7F;
  8177. SignedLowerLimitBottom := -128;
  8178. MinSize := S_B;
  8179. if taicpu(p).opsize = S_BW then
  8180. begin
  8181. MaxSize := S_W;
  8182. UpperLimit := $FFFF;
  8183. SignedUpperLimit := $7FFF;
  8184. SignedUpperLimitBottom := -32768;
  8185. end
  8186. else
  8187. begin
  8188. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8189. MaxSize := S_L;
  8190. UpperLimit := $FFFFFFFF;
  8191. SignedUpperLimit := $7FFFFFFF;
  8192. SignedUpperLimitBottom := -2147483648;
  8193. end;
  8194. end;
  8195. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8196. begin
  8197. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8198. LowerLimit := $FFFF;
  8199. SignedLowerLimit := $7FFF;
  8200. SignedLowerLimitBottom := -32768;
  8201. UpperLimit := $FFFFFFFF;
  8202. SignedUpperLimit := $7FFFFFFF;
  8203. SignedUpperLimitBottom := -2147483648;
  8204. MinSize := S_W;
  8205. MaxSize := S_L;
  8206. end;
  8207. {$ifdef x86_64}
  8208. S_LQ:
  8209. begin
  8210. { Both the lower and upper limits are set to 32-bit. If a limit
  8211. is breached, then optimisation is impossible }
  8212. LowerLimit := $FFFFFFFF;
  8213. SignedLowerLimit := $7FFFFFFF;
  8214. SignedLowerLimitBottom := -2147483648;
  8215. UpperLimit := $FFFFFFFF;
  8216. SignedUpperLimit := $7FFFFFFF;
  8217. SignedUpperLimitBottom := -2147483648;
  8218. MinSize := S_L;
  8219. MaxSize := S_L;
  8220. end;
  8221. {$endif x86_64}
  8222. else
  8223. InternalError(2020112301);
  8224. end;
  8225. TestValMin := 0;
  8226. TestValMax := LowerLimit;
  8227. TestValSignedMax := SignedLowerLimit;
  8228. TryShiftDownLimit := LowerLimit;
  8229. TryShiftDown := S_NO;
  8230. ShiftDownOverflow := False;
  8231. RegChanged := False;
  8232. BitwiseOnly := True;
  8233. OrXorUsed := False;
  8234. UpperSignedOverflow := False;
  8235. LowerSignedOverflow := False;
  8236. UpperUnsignedOverflow := False;
  8237. LowerUnsignedOverflow := False;
  8238. hp1 := p;
  8239. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8240. (hp1.typ = ait_instruction) and
  8241. (
  8242. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8243. instruction that doesn't actually contain ThisReg }
  8244. (cs_opt_level3 in current_settings.optimizerswitches) or
  8245. { This allows this Movx optimisation to work through the SETcc instructions
  8246. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8247. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8248. skip over these SETcc instructions). }
  8249. (taicpu(hp1).opcode = A_SETcc) or
  8250. RegInInstruction(ThisReg, hp1)
  8251. ) do
  8252. begin
  8253. case taicpu(hp1).opcode of
  8254. A_INC,A_DEC:
  8255. begin
  8256. { Has to be an exact match on the register }
  8257. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8258. Break;
  8259. if taicpu(hp1).opcode = A_INC then
  8260. begin
  8261. Inc(TestValMin);
  8262. Inc(TestValMax);
  8263. Inc(TestValSignedMax);
  8264. end
  8265. else
  8266. begin
  8267. Dec(TestValMin);
  8268. Dec(TestValMax);
  8269. Dec(TestValSignedMax);
  8270. end;
  8271. end;
  8272. A_TEST, A_CMP:
  8273. begin
  8274. if (
  8275. { Too high a risk of non-linear behaviour that breaks DFA
  8276. here, unless it's cmp $0,%reg, which is equivalent to
  8277. test %reg,%reg }
  8278. OrXorUsed and
  8279. (taicpu(hp1).opcode = A_CMP) and
  8280. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8281. ) or
  8282. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8283. { Has to be an exact match on the register }
  8284. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8285. (
  8286. { Permit "test %reg,%reg" }
  8287. (taicpu(hp1).opcode = A_TEST) and
  8288. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8289. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8290. ) or
  8291. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8292. { Make sure the comparison value is not smaller than the
  8293. smallest allowed signed value for the minimum size (e.g.
  8294. -128 for 8-bit) }
  8295. not (
  8296. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8297. { Is it in the negative range? }
  8298. (
  8299. (taicpu(hp1).oper[0]^.val < 0) and
  8300. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8301. )
  8302. ) then
  8303. Break;
  8304. { Check to see if the active register is used afterwards }
  8305. TransferUsedRegs(TmpUsedRegs);
  8306. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8307. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8308. begin
  8309. { Make sure the comparison or any previous instructions
  8310. hasn't pushed the test values outside of the range of
  8311. MinSize }
  8312. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8313. begin
  8314. { Exceeded lower bound but not upper bound }
  8315. Exit;
  8316. end
  8317. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8318. begin
  8319. { Size didn't exceed lower bound }
  8320. TargetSize := MinSize;
  8321. end
  8322. else
  8323. Break;
  8324. case TargetSize of
  8325. S_B:
  8326. TargetSubReg := R_SUBL;
  8327. S_W:
  8328. TargetSubReg := R_SUBW;
  8329. S_L:
  8330. TargetSubReg := R_SUBD;
  8331. else
  8332. InternalError(2021051002);
  8333. end;
  8334. if TargetSize <> MaxSize then
  8335. begin
  8336. { Update the register to its new size }
  8337. setsubreg(ThisReg, TargetSubReg);
  8338. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8339. taicpu(hp1).oper[1]^.reg := ThisReg;
  8340. taicpu(hp1).opsize := TargetSize;
  8341. { Convert the input MOVZX to a MOV if necessary }
  8342. AdjustInitialLoadAndSize;
  8343. if (InstrMax >= 0) then
  8344. begin
  8345. for Index := 0 to InstrMax do
  8346. begin
  8347. { If p_removed is true, then the original MOV/Z was removed
  8348. and removing the AND instruction may not be safe if it
  8349. appears first }
  8350. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8351. InternalError(2020112311);
  8352. if InstrList[Index].oper[0]^.typ = top_reg then
  8353. InstrList[Index].oper[0]^.reg := ThisReg;
  8354. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8355. InstrList[Index].opsize := MinSize;
  8356. end;
  8357. end;
  8358. Result := True;
  8359. end;
  8360. Exit;
  8361. end;
  8362. end;
  8363. A_SETcc:
  8364. begin
  8365. { This allows this Movx optimisation to work through the SETcc instructions
  8366. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8367. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8368. skip over these SETcc instructions). }
  8369. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8370. { Of course, break out if the current register is used }
  8371. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8372. Break
  8373. else
  8374. { We must use Continue so the instruction doesn't get added
  8375. to InstrList }
  8376. Continue;
  8377. end;
  8378. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8379. begin
  8380. if
  8381. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8382. { Has to be an exact match on the register }
  8383. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8384. (
  8385. (
  8386. (taicpu(hp1).oper[0]^.typ = top_const) and
  8387. (
  8388. (
  8389. (taicpu(hp1).opcode = A_SHL) and
  8390. (
  8391. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8392. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8393. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8394. )
  8395. ) or (
  8396. (taicpu(hp1).opcode <> A_SHL) and
  8397. (
  8398. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8399. { Is it in the negative range? }
  8400. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8401. )
  8402. )
  8403. )
  8404. ) or (
  8405. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8406. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8407. )
  8408. ) then
  8409. Break;
  8410. { Only process OR and XOR if there are only bitwise operations,
  8411. since otherwise they can too easily fool the data flow
  8412. analysis (they can cause non-linear behaviour) }
  8413. case taicpu(hp1).opcode of
  8414. A_ADD:
  8415. begin
  8416. if OrXorUsed then
  8417. { Too high a risk of non-linear behaviour that breaks DFA here }
  8418. Break
  8419. else
  8420. BitwiseOnly := False;
  8421. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8422. begin
  8423. TestValMin := TestValMin * 2;
  8424. TestValMax := TestValMax * 2;
  8425. TestValSignedMax := TestValSignedMax * 2;
  8426. end
  8427. else
  8428. begin
  8429. WorkingValue := taicpu(hp1).oper[0]^.val;
  8430. TestValMin := TestValMin + WorkingValue;
  8431. TestValMax := TestValMax + WorkingValue;
  8432. TestValSignedMax := TestValSignedMax + WorkingValue;
  8433. end;
  8434. end;
  8435. A_SUB:
  8436. begin
  8437. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8438. begin
  8439. TestValMin := 0;
  8440. TestValMax := 0;
  8441. TestValSignedMax := 0;
  8442. end
  8443. else
  8444. begin
  8445. if OrXorUsed then
  8446. { Too high a risk of non-linear behaviour that breaks DFA here }
  8447. Break
  8448. else
  8449. BitwiseOnly := False;
  8450. WorkingValue := taicpu(hp1).oper[0]^.val;
  8451. TestValMin := TestValMin - WorkingValue;
  8452. TestValMax := TestValMax - WorkingValue;
  8453. TestValSignedMax := TestValSignedMax - WorkingValue;
  8454. end;
  8455. end;
  8456. A_AND:
  8457. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8458. begin
  8459. { we might be able to go smaller if AND appears first }
  8460. if InstrMax = -1 then
  8461. case MinSize of
  8462. S_B:
  8463. ;
  8464. S_W:
  8465. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8466. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8467. begin
  8468. TryShiftDown := S_B;
  8469. TryShiftDownLimit := $FF;
  8470. end;
  8471. S_L:
  8472. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8473. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8474. begin
  8475. TryShiftDown := S_B;
  8476. TryShiftDownLimit := $FF;
  8477. end
  8478. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8479. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8480. begin
  8481. TryShiftDown := S_W;
  8482. TryShiftDownLimit := $FFFF;
  8483. end;
  8484. else
  8485. InternalError(2020112320);
  8486. end;
  8487. WorkingValue := taicpu(hp1).oper[0]^.val;
  8488. TestValMin := TestValMin and WorkingValue;
  8489. TestValMax := TestValMax and WorkingValue;
  8490. TestValSignedMax := TestValSignedMax and WorkingValue;
  8491. end;
  8492. A_OR:
  8493. begin
  8494. if not BitwiseOnly then
  8495. Break;
  8496. OrXorUsed := True;
  8497. WorkingValue := taicpu(hp1).oper[0]^.val;
  8498. TestValMin := TestValMin or WorkingValue;
  8499. TestValMax := TestValMax or WorkingValue;
  8500. TestValSignedMax := TestValSignedMax or WorkingValue;
  8501. end;
  8502. A_XOR:
  8503. begin
  8504. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8505. begin
  8506. TestValMin := 0;
  8507. TestValMax := 0;
  8508. TestValSignedMax := 0;
  8509. end
  8510. else
  8511. begin
  8512. if not BitwiseOnly then
  8513. Break;
  8514. OrXorUsed := True;
  8515. WorkingValue := taicpu(hp1).oper[0]^.val;
  8516. TestValMin := TestValMin xor WorkingValue;
  8517. TestValMax := TestValMax xor WorkingValue;
  8518. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8519. end;
  8520. end;
  8521. A_SHL:
  8522. begin
  8523. BitwiseOnly := False;
  8524. WorkingValue := taicpu(hp1).oper[0]^.val;
  8525. TestValMin := TestValMin shl WorkingValue;
  8526. TestValMax := TestValMax shl WorkingValue;
  8527. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8528. end;
  8529. A_SHR,
  8530. { The first instruction was MOVZX, so the value won't be negative }
  8531. A_SAR:
  8532. begin
  8533. if InstrMax <> -1 then
  8534. BitwiseOnly := False
  8535. else
  8536. { we might be able to go smaller if SHR appears first }
  8537. case MinSize of
  8538. S_B:
  8539. ;
  8540. S_W:
  8541. if (taicpu(hp1).oper[0]^.val >= 8) then
  8542. begin
  8543. TryShiftDown := S_B;
  8544. TryShiftDownLimit := $FF;
  8545. TryShiftDownSignedLimit := $7F;
  8546. TryShiftDownSignedLimitLower := -128;
  8547. end;
  8548. S_L:
  8549. if (taicpu(hp1).oper[0]^.val >= 24) then
  8550. begin
  8551. TryShiftDown := S_B;
  8552. TryShiftDownLimit := $FF;
  8553. TryShiftDownSignedLimit := $7F;
  8554. TryShiftDownSignedLimitLower := -128;
  8555. end
  8556. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8557. begin
  8558. TryShiftDown := S_W;
  8559. TryShiftDownLimit := $FFFF;
  8560. TryShiftDownSignedLimit := $7FFF;
  8561. TryShiftDownSignedLimitLower := -32768;
  8562. end;
  8563. else
  8564. InternalError(2020112321);
  8565. end;
  8566. WorkingValue := taicpu(hp1).oper[0]^.val;
  8567. if taicpu(hp1).opcode = A_SAR then
  8568. begin
  8569. TestValMin := SarInt64(TestValMin, WorkingValue);
  8570. TestValMax := SarInt64(TestValMax, WorkingValue);
  8571. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8572. end
  8573. else
  8574. begin
  8575. TestValMin := TestValMin shr WorkingValue;
  8576. TestValMax := TestValMax shr WorkingValue;
  8577. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8578. end;
  8579. end;
  8580. else
  8581. InternalError(2020112303);
  8582. end;
  8583. end;
  8584. (*
  8585. A_IMUL:
  8586. case taicpu(hp1).ops of
  8587. 2:
  8588. begin
  8589. if not MatchOpType(hp1, top_reg, top_reg) or
  8590. { Has to be an exact match on the register }
  8591. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8592. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8593. Break;
  8594. TestValMin := TestValMin * TestValMin;
  8595. TestValMax := TestValMax * TestValMax;
  8596. TestValSignedMax := TestValSignedMax * TestValMax;
  8597. end;
  8598. 3:
  8599. begin
  8600. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8601. { Has to be an exact match on the register }
  8602. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8603. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8604. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8605. { Is it in the negative range? }
  8606. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8607. Break;
  8608. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8609. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8610. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8611. end;
  8612. else
  8613. Break;
  8614. end;
  8615. A_IDIV:
  8616. case taicpu(hp1).ops of
  8617. 3:
  8618. begin
  8619. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8620. { Has to be an exact match on the register }
  8621. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8622. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8623. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8624. { Is it in the negative range? }
  8625. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8626. Break;
  8627. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8628. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8629. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8630. end;
  8631. else
  8632. Break;
  8633. end;
  8634. *)
  8635. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8636. begin
  8637. { If there are no instructions in between, then we might be able to make a saving }
  8638. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8639. Break;
  8640. { We have something like:
  8641. movzbw %dl,%dx
  8642. ...
  8643. movswl %dx,%edx
  8644. Change the latter to a zero-extension then enter the
  8645. A_MOVZX case branch.
  8646. }
  8647. {$ifdef x86_64}
  8648. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8649. begin
  8650. { this becomes a zero extension from 32-bit to 64-bit, but
  8651. the upper 32 bits are already zero, so just delete the
  8652. instruction }
  8653. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8654. RemoveInstruction(hp1);
  8655. Result := True;
  8656. Exit;
  8657. end
  8658. else
  8659. {$endif x86_64}
  8660. begin
  8661. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8662. taicpu(hp1).opcode := A_MOVZX;
  8663. {$ifdef x86_64}
  8664. case taicpu(hp1).opsize of
  8665. S_BQ:
  8666. begin
  8667. taicpu(hp1).opsize := S_BL;
  8668. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8669. end;
  8670. S_WQ:
  8671. begin
  8672. taicpu(hp1).opsize := S_WL;
  8673. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8674. end;
  8675. S_LQ:
  8676. begin
  8677. taicpu(hp1).opcode := A_MOV;
  8678. taicpu(hp1).opsize := S_L;
  8679. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8680. { In this instance, we need to break out because the
  8681. instruction is no longer MOVZX or MOVSXD }
  8682. Result := True;
  8683. Exit;
  8684. end;
  8685. else
  8686. ;
  8687. end;
  8688. {$endif x86_64}
  8689. Result := CompressInstructions;
  8690. Exit;
  8691. end;
  8692. end;
  8693. A_MOVZX:
  8694. begin
  8695. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8696. Break;
  8697. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8698. begin
  8699. if (InstrMax = -1) and
  8700. { Will return false if the second parameter isn't ThisReg
  8701. (can happen on -O2 and under) }
  8702. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8703. begin
  8704. { The two MOVZX instructions are adjacent, so remove the first one }
  8705. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8706. RemoveCurrentP(p);
  8707. Result := True;
  8708. Exit;
  8709. end;
  8710. Break;
  8711. end;
  8712. Result := CompressInstructions;
  8713. Exit;
  8714. end;
  8715. else
  8716. { This includes ADC, SBB and IDIV }
  8717. Break;
  8718. end;
  8719. if not CheckOverflowConditions then
  8720. Break;
  8721. { Contains highest index (so instruction count - 1) }
  8722. Inc(InstrMax);
  8723. if InstrMax > High(InstrList) then
  8724. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8725. InstrList[InstrMax] := taicpu(hp1);
  8726. end;
  8727. end;
  8728. {$pop}
  8729. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8730. var
  8731. hp1 : tai;
  8732. begin
  8733. Result:=false;
  8734. if (taicpu(p).ops >= 2) and
  8735. ((taicpu(p).oper[0]^.typ = top_const) or
  8736. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8737. (taicpu(p).oper[1]^.typ = top_reg) and
  8738. ((taicpu(p).ops = 2) or
  8739. ((taicpu(p).oper[2]^.typ = top_reg) and
  8740. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8741. GetLastInstruction(p,hp1) and
  8742. MatchInstruction(hp1,A_MOV,[]) and
  8743. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8744. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8745. begin
  8746. TransferUsedRegs(TmpUsedRegs);
  8747. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8748. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8749. { change
  8750. mov reg1,reg2
  8751. imul y,reg2 to imul y,reg1,reg2 }
  8752. begin
  8753. taicpu(p).ops := 3;
  8754. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8755. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8756. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8757. RemoveInstruction(hp1);
  8758. result:=true;
  8759. end;
  8760. end;
  8761. end;
  8762. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8763. var
  8764. ThisLabel: TAsmLabel;
  8765. begin
  8766. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8767. ThisLabel.decrefs;
  8768. taicpu(p).opcode := A_RET;
  8769. taicpu(p).is_jmp := false;
  8770. taicpu(p).ops := taicpu(ret_p).ops;
  8771. case taicpu(ret_p).ops of
  8772. 0:
  8773. taicpu(p).clearop(0);
  8774. 1:
  8775. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8776. else
  8777. internalerror(2016041301);
  8778. end;
  8779. { If the original label is now dead, it might turn out that the label
  8780. immediately follows p. As a result, everything beyond it, which will
  8781. be just some final register configuration and a RET instruction, is
  8782. now dead code. [Kit] }
  8783. { NOTE: This is much faster than introducing a OptPass2RET routine and
  8784. running RemoveDeadCodeAfterJump for each RET instruction, because
  8785. this optimisation rarely happens and most RETs appear at the end of
  8786. routines where there is nothing that can be stripped. [Kit] }
  8787. if not ThisLabel.is_used then
  8788. RemoveDeadCodeAfterJump(p);
  8789. end;
  8790. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  8791. var
  8792. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  8793. Unconditional, PotentialModified: Boolean;
  8794. OperPtr: POper;
  8795. NewRef: TReference;
  8796. InstrList: array of taicpu;
  8797. InstrMax, Index: Integer;
  8798. const
  8799. {$ifdef DEBUG_AOPTCPU}
  8800. SNoFlags: shortstring = ' so the flags aren''t modified';
  8801. {$else DEBUG_AOPTCPU}
  8802. SNoFlags = '';
  8803. {$endif DEBUG_AOPTCPU}
  8804. begin
  8805. Result:=false;
  8806. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  8807. begin
  8808. if MatchInstruction(hp1, A_TEST, [S_B]) and
  8809. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8810. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8811. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8812. GetNextInstruction(hp1, hp2) and
  8813. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  8814. { Change from: To:
  8815. set(C) %reg j(~C) label
  8816. test %reg,%reg/cmp $0,%reg
  8817. je label
  8818. set(C) %reg j(C) label
  8819. test %reg,%reg/cmp $0,%reg
  8820. jne label
  8821. (Also do something similar with sete/setne instead of je/jne)
  8822. }
  8823. begin
  8824. { Before we do anything else, we need to check the instructions
  8825. in between SETcc and TEST to make sure they don't modify the
  8826. FLAGS register - if -O2 or under, there won't be any
  8827. instructions between SET and TEST }
  8828. TransferUsedRegs(TmpUsedRegs);
  8829. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8830. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8831. begin
  8832. next := p;
  8833. SetLength(InstrList, 0);
  8834. InstrMax := -1;
  8835. PotentialModified := False;
  8836. { Make a note of every instruction that modifies the FLAGS
  8837. register }
  8838. while GetNextInstruction(next, next) and (next <> hp1) do
  8839. begin
  8840. if next.typ <> ait_instruction then
  8841. { GetNextInstructionUsingReg should have returned False }
  8842. InternalError(2021051701);
  8843. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  8844. begin
  8845. case taicpu(next).opcode of
  8846. A_SETcc,
  8847. A_CMOVcc,
  8848. A_Jcc:
  8849. begin
  8850. if PotentialModified then
  8851. { Not safe because the flags were modified earlier }
  8852. Exit
  8853. else
  8854. { Condition is the same as the initial SETcc, so this is safe
  8855. (don't add to instruction list though) }
  8856. Continue;
  8857. end;
  8858. A_ADD:
  8859. begin
  8860. if (taicpu(next).opsize = S_B) or
  8861. { LEA doesn't support 8-bit operands }
  8862. (taicpu(next).oper[1]^.typ <> top_reg) or
  8863. { Must write to a register }
  8864. (taicpu(next).oper[0]^.typ = top_ref) then
  8865. { Require a constant or a register }
  8866. Exit;
  8867. PotentialModified := True;
  8868. end;
  8869. A_SUB:
  8870. begin
  8871. if (taicpu(next).opsize = S_B) or
  8872. { LEA doesn't support 8-bit operands }
  8873. (taicpu(next).oper[1]^.typ <> top_reg) or
  8874. { Must write to a register }
  8875. (taicpu(next).oper[0]^.typ <> top_const) or
  8876. (taicpu(next).oper[0]^.val = $80000000) then
  8877. { Can't subtract a register with LEA - also
  8878. check that the value isn't -2^31, as this
  8879. can't be negated }
  8880. Exit;
  8881. PotentialModified := True;
  8882. end;
  8883. A_SAL,
  8884. A_SHL:
  8885. begin
  8886. if (taicpu(next).opsize = S_B) or
  8887. { LEA doesn't support 8-bit operands }
  8888. (taicpu(next).oper[1]^.typ <> top_reg) or
  8889. { Must write to a register }
  8890. (taicpu(next).oper[0]^.typ <> top_const) or
  8891. (taicpu(next).oper[0]^.val < 0) or
  8892. (taicpu(next).oper[0]^.val > 3) then
  8893. Exit;
  8894. PotentialModified := True;
  8895. end;
  8896. A_IMUL:
  8897. begin
  8898. if (taicpu(next).ops <> 3) or
  8899. (taicpu(next).oper[1]^.typ <> top_reg) or
  8900. { Must write to a register }
  8901. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  8902. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  8903. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  8904. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  8905. Exit
  8906. else
  8907. PotentialModified := True;
  8908. end;
  8909. else
  8910. { Don't know how to change this, so abort }
  8911. Exit;
  8912. end;
  8913. { Contains highest index (so instruction count - 1) }
  8914. Inc(InstrMax);
  8915. if InstrMax > High(InstrList) then
  8916. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8917. InstrList[InstrMax] := taicpu(next);
  8918. end;
  8919. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  8920. end;
  8921. if not Assigned(next) or (next <> hp1) then
  8922. { It should be equal to hp1 }
  8923. InternalError(2021051702);
  8924. { Cycle through each instruction and check to see if we can
  8925. change them to versions that don't modify the flags }
  8926. if (InstrMax >= 0) then
  8927. begin
  8928. for Index := 0 to InstrMax do
  8929. case InstrList[Index].opcode of
  8930. A_ADD:
  8931. begin
  8932. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  8933. InstrList[Index].opcode := A_LEA;
  8934. reference_reset(NewRef, 1, []);
  8935. NewRef.base := InstrList[Index].oper[1]^.reg;
  8936. if InstrList[Index].oper[0]^.typ = top_reg then
  8937. begin
  8938. NewRef.index := InstrList[Index].oper[0]^.reg;
  8939. NewRef.scalefactor := 1;
  8940. end
  8941. else
  8942. NewRef.offset := InstrList[Index].oper[0]^.val;
  8943. InstrList[Index].loadref(0, NewRef);
  8944. end;
  8945. A_SUB:
  8946. begin
  8947. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  8948. InstrList[Index].opcode := A_LEA;
  8949. reference_reset(NewRef, 1, []);
  8950. NewRef.base := InstrList[Index].oper[1]^.reg;
  8951. NewRef.offset := -InstrList[Index].oper[0]^.val;
  8952. InstrList[Index].loadref(0, NewRef);
  8953. end;
  8954. A_SHL,
  8955. A_SAL:
  8956. begin
  8957. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  8958. InstrList[Index].opcode := A_LEA;
  8959. reference_reset(NewRef, 1, []);
  8960. NewRef.index := InstrList[Index].oper[1]^.reg;
  8961. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  8962. InstrList[Index].loadref(0, NewRef);
  8963. end;
  8964. A_IMUL:
  8965. begin
  8966. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  8967. InstrList[Index].opcode := A_LEA;
  8968. reference_reset(NewRef, 1, []);
  8969. NewRef.index := InstrList[Index].oper[1]^.reg;
  8970. case InstrList[Index].oper[0]^.val of
  8971. 2, 4, 8:
  8972. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  8973. else {3, 5 and 9}
  8974. begin
  8975. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  8976. NewRef.base := InstrList[Index].oper[1]^.reg;
  8977. end;
  8978. end;
  8979. InstrList[Index].loadref(0, NewRef);
  8980. end;
  8981. else
  8982. InternalError(2021051710);
  8983. end;
  8984. end;
  8985. { Mark the FLAGS register as used across this whole block }
  8986. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  8987. end;
  8988. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  8989. JumpC := taicpu(hp2).condition;
  8990. Unconditional := False;
  8991. if conditions_equal(JumpC, C_E) then
  8992. SetC := inverse_cond(taicpu(p).condition)
  8993. else if conditions_equal(JumpC, C_NE) then
  8994. SetC := taicpu(p).condition
  8995. else
  8996. { We've got something weird here (and inefficent) }
  8997. begin
  8998. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  8999. SetC := C_NONE;
  9000. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9001. if condition_in(C_AE, JumpC) then
  9002. Unconditional := True
  9003. else
  9004. { Not sure what to do with this jump - drop out }
  9005. Exit;
  9006. end;
  9007. RemoveInstruction(hp1);
  9008. if Unconditional then
  9009. MakeUnconditional(taicpu(hp2))
  9010. else
  9011. begin
  9012. if SetC = C_NONE then
  9013. InternalError(2018061402);
  9014. taicpu(hp2).SetCondition(SetC);
  9015. end;
  9016. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9017. TmpUsedRegs }
  9018. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9019. begin
  9020. RemoveCurrentp(p, hp2);
  9021. if taicpu(hp2).opcode = A_SETcc then
  9022. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9023. else
  9024. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9025. end
  9026. else
  9027. if taicpu(hp2).opcode = A_SETcc then
  9028. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9029. else
  9030. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9031. Result := True;
  9032. end
  9033. else if
  9034. { Make sure the instructions are adjacent }
  9035. (
  9036. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9037. GetNextInstruction(p, hp1)
  9038. ) and
  9039. MatchInstruction(hp1, A_MOV, [S_B]) and
  9040. { Writing to memory is allowed }
  9041. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9042. begin
  9043. {
  9044. Watch out for sequences such as:
  9045. set(c)b %regb
  9046. movb %regb,(ref)
  9047. movb $0,1(ref)
  9048. movb $0,2(ref)
  9049. movb $0,3(ref)
  9050. Much more efficient to turn it into:
  9051. movl $0,%regl
  9052. set(c)b %regb
  9053. movl %regl,(ref)
  9054. Or:
  9055. set(c)b %regb
  9056. movzbl %regb,%regl
  9057. movl %regl,(ref)
  9058. }
  9059. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9060. GetNextInstruction(hp1, hp2) and
  9061. MatchInstruction(hp2, A_MOV, [S_B]) and
  9062. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9063. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9064. begin
  9065. { Don't do anything else except set Result to True }
  9066. end
  9067. else
  9068. begin
  9069. if taicpu(p).oper[0]^.typ = top_reg then
  9070. begin
  9071. TransferUsedRegs(TmpUsedRegs);
  9072. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9073. end;
  9074. { If it's not a register, it's a memory address }
  9075. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9076. begin
  9077. { Even if the register is still in use, we can minimise the
  9078. pipeline stall by changing the MOV into another SETcc. }
  9079. taicpu(hp1).opcode := A_SETcc;
  9080. taicpu(hp1).condition := taicpu(p).condition;
  9081. if taicpu(hp1).oper[1]^.typ = top_ref then
  9082. begin
  9083. { Swapping the operand pointers like this is probably a
  9084. bit naughty, but it is far faster than using loadoper
  9085. to transfer the reference from oper[1] to oper[0] if
  9086. you take into account the extra procedure calls and
  9087. the memory allocation and deallocation required }
  9088. OperPtr := taicpu(hp1).oper[1];
  9089. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9090. taicpu(hp1).oper[0] := OperPtr;
  9091. end
  9092. else
  9093. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9094. taicpu(hp1).clearop(1);
  9095. taicpu(hp1).ops := 1;
  9096. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9097. end
  9098. else
  9099. begin
  9100. if taicpu(hp1).oper[1]^.typ = top_reg then
  9101. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9102. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9103. RemoveInstruction(hp1);
  9104. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9105. end
  9106. end;
  9107. Result := True;
  9108. end;
  9109. end;
  9110. end;
  9111. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9112. var
  9113. hp1: tai;
  9114. Count: Integer;
  9115. OrigLabel: TAsmLabel;
  9116. begin
  9117. result := False;
  9118. { Sometimes, the optimisations below can permit this }
  9119. RemoveDeadCodeAfterJump(p);
  9120. 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
  9121. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9122. begin
  9123. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9124. { Also a side-effect of optimisations }
  9125. if CollapseZeroDistJump(p, OrigLabel) then
  9126. begin
  9127. Result := True;
  9128. Exit;
  9129. end;
  9130. hp1 := GetLabelWithSym(OrigLabel);
  9131. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9132. begin
  9133. case taicpu(hp1).opcode of
  9134. A_RET:
  9135. {
  9136. change
  9137. jmp .L1
  9138. ...
  9139. .L1:
  9140. ret
  9141. into
  9142. ret
  9143. }
  9144. begin
  9145. ConvertJumpToRET(p, hp1);
  9146. result:=true;
  9147. end;
  9148. { Check any kind of direct assignment instruction }
  9149. A_MOV,
  9150. A_MOVD,
  9151. A_MOVQ,
  9152. A_MOVSX,
  9153. {$ifdef x86_64}
  9154. A_MOVSXD,
  9155. {$endif x86_64}
  9156. A_MOVZX,
  9157. A_MOVAPS,
  9158. A_MOVUPS,
  9159. A_MOVSD,
  9160. A_MOVAPD,
  9161. A_MOVUPD,
  9162. A_MOVDQA,
  9163. A_MOVDQU,
  9164. A_VMOVSS,
  9165. A_VMOVAPS,
  9166. A_VMOVUPS,
  9167. A_VMOVSD,
  9168. A_VMOVAPD,
  9169. A_VMOVUPD,
  9170. A_VMOVDQA,
  9171. A_VMOVDQU:
  9172. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  9173. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9174. begin
  9175. Result := True;
  9176. Exit;
  9177. end;
  9178. else
  9179. ;
  9180. end;
  9181. end;
  9182. end;
  9183. end;
  9184. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9185. begin
  9186. CanBeCMOV:=assigned(p) and
  9187. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9188. { we can't use cmov ref,reg because
  9189. ref could be nil and cmov still throws an exception
  9190. if ref=nil but the mov isn't done (FK)
  9191. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9192. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9193. }
  9194. (taicpu(p).oper[1]^.typ = top_reg) and
  9195. (
  9196. (taicpu(p).oper[0]^.typ = top_reg) or
  9197. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9198. it is not expected that this can cause a seg. violation }
  9199. (
  9200. (taicpu(p).oper[0]^.typ = top_ref) and
  9201. IsRefSafe(taicpu(p).oper[0]^.ref)
  9202. )
  9203. );
  9204. end;
  9205. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9206. var
  9207. hp1,hp2: tai;
  9208. {$ifndef i8086}
  9209. hp3,hp4,hpmov2, hp5: tai;
  9210. l : Longint;
  9211. condition : TAsmCond;
  9212. {$endif i8086}
  9213. carryadd_opcode : TAsmOp;
  9214. symbol: TAsmSymbol;
  9215. increg, tmpreg: TRegister;
  9216. begin
  9217. result:=false;
  9218. if GetNextInstruction(p,hp1) then
  9219. begin
  9220. if (hp1.typ=ait_label) then
  9221. begin
  9222. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9223. Exit;
  9224. end
  9225. else if (hp1.typ<>ait_instruction) then
  9226. Exit;
  9227. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9228. if (
  9229. (
  9230. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9231. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9232. (Taicpu(hp1).oper[0]^.val=1)
  9233. ) or
  9234. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9235. ) and
  9236. GetNextInstruction(hp1,hp2) and
  9237. SkipAligns(hp2, hp2) and
  9238. (hp2.typ = ait_label) and
  9239. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9240. { jb @@1 cmc
  9241. inc/dec operand --> adc/sbb operand,0
  9242. @@1:
  9243. ... and ...
  9244. jnb @@1
  9245. inc/dec operand --> adc/sbb operand,0
  9246. @@1: }
  9247. begin
  9248. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9249. begin
  9250. case taicpu(hp1).opcode of
  9251. A_INC,
  9252. A_ADD:
  9253. carryadd_opcode:=A_ADC;
  9254. A_DEC,
  9255. A_SUB:
  9256. carryadd_opcode:=A_SBB;
  9257. else
  9258. InternalError(2021011001);
  9259. end;
  9260. Taicpu(p).clearop(0);
  9261. Taicpu(p).ops:=0;
  9262. Taicpu(p).is_jmp:=false;
  9263. Taicpu(p).opcode:=A_CMC;
  9264. Taicpu(p).condition:=C_NONE;
  9265. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9266. Taicpu(hp1).ops:=2;
  9267. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9268. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9269. else
  9270. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9271. Taicpu(hp1).loadconst(0,0);
  9272. Taicpu(hp1).opcode:=carryadd_opcode;
  9273. result:=true;
  9274. exit;
  9275. end
  9276. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9277. begin
  9278. case taicpu(hp1).opcode of
  9279. A_INC,
  9280. A_ADD:
  9281. carryadd_opcode:=A_ADC;
  9282. A_DEC,
  9283. A_SUB:
  9284. carryadd_opcode:=A_SBB;
  9285. else
  9286. InternalError(2021011002);
  9287. end;
  9288. Taicpu(hp1).ops:=2;
  9289. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9290. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9291. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9292. else
  9293. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9294. Taicpu(hp1).loadconst(0,0);
  9295. Taicpu(hp1).opcode:=carryadd_opcode;
  9296. RemoveCurrentP(p, hp1);
  9297. result:=true;
  9298. exit;
  9299. end
  9300. {
  9301. jcc @@1 setcc tmpreg
  9302. inc/dec/add/sub operand -> (movzx tmpreg)
  9303. @@1: add/sub tmpreg,operand
  9304. While this increases code size slightly, it makes the code much faster if the
  9305. jump is unpredictable
  9306. }
  9307. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9308. begin
  9309. { search for an available register which is volatile }
  9310. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9311. if increg <> NR_NO then
  9312. begin
  9313. { We don't need to check if tmpreg is in hp1 or not, because
  9314. it will be marked as in use at p (if not, this is
  9315. indictive of a compiler bug). }
  9316. TAsmLabel(symbol).decrefs;
  9317. Taicpu(p).clearop(0);
  9318. Taicpu(p).ops:=1;
  9319. Taicpu(p).is_jmp:=false;
  9320. Taicpu(p).opcode:=A_SETcc;
  9321. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9322. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9323. Taicpu(p).loadreg(0,increg);
  9324. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9325. begin
  9326. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9327. R_SUBW:
  9328. begin
  9329. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9330. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9331. end;
  9332. R_SUBD:
  9333. begin
  9334. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9335. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9336. end;
  9337. {$ifdef x86_64}
  9338. R_SUBQ:
  9339. begin
  9340. { MOVZX doesn't have a 64-bit variant, because
  9341. the 32-bit version implicitly zeroes the
  9342. upper 32-bits of the destination register }
  9343. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9344. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9345. setsubreg(tmpreg, R_SUBQ);
  9346. end;
  9347. {$endif x86_64}
  9348. else
  9349. Internalerror(2020030601);
  9350. end;
  9351. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9352. asml.InsertAfter(hp2,p);
  9353. end
  9354. else
  9355. tmpreg := increg;
  9356. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9357. begin
  9358. Taicpu(hp1).ops:=2;
  9359. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9360. end;
  9361. Taicpu(hp1).loadreg(0,tmpreg);
  9362. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9363. Result := True;
  9364. { p is no longer a Jcc instruction, so exit }
  9365. Exit;
  9366. end;
  9367. end;
  9368. end;
  9369. { Detect the following:
  9370. jmp<cond> @Lbl1
  9371. jmp @Lbl2
  9372. ...
  9373. @Lbl1:
  9374. ret
  9375. Change to:
  9376. jmp<inv_cond> @Lbl2
  9377. ret
  9378. }
  9379. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9380. begin
  9381. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9382. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9383. MatchInstruction(hp2,A_RET,[S_NO]) then
  9384. begin
  9385. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9386. { Change label address to that of the unconditional jump }
  9387. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9388. TAsmLabel(symbol).DecRefs;
  9389. taicpu(hp1).opcode := A_RET;
  9390. taicpu(hp1).is_jmp := false;
  9391. taicpu(hp1).ops := taicpu(hp2).ops;
  9392. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9393. case taicpu(hp2).ops of
  9394. 0:
  9395. taicpu(hp1).clearop(0);
  9396. 1:
  9397. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9398. else
  9399. internalerror(2016041302);
  9400. end;
  9401. end;
  9402. {$ifndef i8086}
  9403. end
  9404. {
  9405. convert
  9406. j<c> .L1
  9407. mov 1,reg
  9408. jmp .L2
  9409. .L1
  9410. mov 0,reg
  9411. .L2
  9412. into
  9413. mov 0,reg
  9414. set<not(c)> reg
  9415. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9416. would destroy the flag contents
  9417. }
  9418. else if MatchInstruction(hp1,A_MOV,[]) and
  9419. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9420. {$ifdef i386}
  9421. (
  9422. { Under i386, ESI, EDI, EBP and ESP
  9423. don't have an 8-bit representation }
  9424. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9425. ) and
  9426. {$endif i386}
  9427. (taicpu(hp1).oper[0]^.val=1) and
  9428. GetNextInstruction(hp1,hp2) and
  9429. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9430. GetNextInstruction(hp2,hp3) and
  9431. { skip align }
  9432. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9433. (hp3.typ=ait_label) and
  9434. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9435. (tai_label(hp3).labsym.getrefs=1) and
  9436. GetNextInstruction(hp3,hp4) and
  9437. MatchInstruction(hp4,A_MOV,[]) and
  9438. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9439. (taicpu(hp4).oper[0]^.val=0) and
  9440. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9441. GetNextInstruction(hp4,hp5) and
  9442. (hp5.typ=ait_label) and
  9443. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9444. (tai_label(hp5).labsym.getrefs=1) then
  9445. begin
  9446. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9447. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9448. { remove last label }
  9449. RemoveInstruction(hp5);
  9450. { remove second label }
  9451. RemoveInstruction(hp3);
  9452. { if align is present remove it }
  9453. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9454. RemoveInstruction(hp3);
  9455. { remove jmp }
  9456. RemoveInstruction(hp2);
  9457. if taicpu(hp1).opsize=S_B then
  9458. RemoveInstruction(hp1)
  9459. else
  9460. taicpu(hp1).loadconst(0,0);
  9461. taicpu(hp4).opcode:=A_SETcc;
  9462. taicpu(hp4).opsize:=S_B;
  9463. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9464. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9465. taicpu(hp4).opercnt:=1;
  9466. taicpu(hp4).ops:=1;
  9467. taicpu(hp4).freeop(1);
  9468. RemoveCurrentP(p);
  9469. Result:=true;
  9470. exit;
  9471. end
  9472. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9473. begin
  9474. { check for
  9475. jCC xxx
  9476. <several movs>
  9477. xxx:
  9478. Also spot:
  9479. Jcc xxx
  9480. <several movs>
  9481. jmp xxx
  9482. Change to:
  9483. <several cmovs with inverted condition>
  9484. jmp xxx
  9485. }
  9486. l:=0;
  9487. while assigned(hp1) and
  9488. CanBeCMOV(hp1) and
  9489. { stop on labels }
  9490. not(hp1.typ=ait_label) do
  9491. begin
  9492. inc(l);
  9493. hp5 := hp1;
  9494. GetNextInstruction(hp1,hp1);
  9495. end;
  9496. if assigned(hp1) then
  9497. begin
  9498. TransferUsedRegs(TmpUsedRegs);
  9499. if (
  9500. MatchInstruction(hp1, A_JMP, []) and
  9501. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9502. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9503. ) or
  9504. FindLabel(tasmlabel(symbol),hp1) then
  9505. begin
  9506. if (l<=4) and (l>0) then
  9507. begin
  9508. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9509. condition:=inverse_cond(taicpu(p).condition);
  9510. UpdateUsedRegs(tai(p.next));
  9511. GetNextInstruction(p,hp1);
  9512. repeat
  9513. if not Assigned(hp1) then
  9514. InternalError(2018062900);
  9515. taicpu(hp1).opcode:=A_CMOVcc;
  9516. taicpu(hp1).condition:=condition;
  9517. UpdateUsedRegs(tai(hp1.next));
  9518. GetNextInstruction(hp1,hp1);
  9519. until not(CanBeCMOV(hp1));
  9520. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9521. hp2 := hp1;
  9522. repeat
  9523. if not Assigned(hp2) then
  9524. InternalError(2018062910);
  9525. case hp2.typ of
  9526. ait_label:
  9527. { What we expected - break out of the loop (it won't be a dead label at the top of
  9528. a cluster because that was optimised at an earlier stage) }
  9529. Break;
  9530. ait_align:
  9531. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9532. begin
  9533. hp2 := tai(hp2.Next);
  9534. Continue;
  9535. end;
  9536. ait_instruction:
  9537. begin
  9538. if taicpu(hp2).opcode<>A_JMP then
  9539. InternalError(2018062912);
  9540. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9541. Break;
  9542. end
  9543. else
  9544. begin
  9545. { Might be a comment or temporary allocation entry }
  9546. if not (hp2.typ in SkipInstr) then
  9547. InternalError(2018062911);
  9548. hp2 := tai(hp2.Next);
  9549. Continue;
  9550. end;
  9551. end;
  9552. until False;
  9553. { Now we can safely decrement the reference count }
  9554. tasmlabel(symbol).decrefs;
  9555. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9556. { Remove the original jump }
  9557. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9558. if hp2.typ=ait_instruction then
  9559. begin
  9560. p:=hp2;
  9561. Result:=True;
  9562. end
  9563. else
  9564. begin
  9565. UpdateUsedRegs(tai(hp2.next));
  9566. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9567. { Remove the label if this is its final reference }
  9568. if (tasmlabel(symbol).getrefs=0) then
  9569. StripLabelFast(hp1);
  9570. end;
  9571. exit;
  9572. end;
  9573. end
  9574. else
  9575. begin
  9576. { check further for
  9577. jCC xxx
  9578. <several movs 1>
  9579. jmp yyy
  9580. xxx:
  9581. <several movs 2>
  9582. yyy:
  9583. }
  9584. { hp2 points to jmp yyy }
  9585. hp2:=hp1;
  9586. { skip hp1 to xxx (or an align right before it) }
  9587. GetNextInstruction(hp1, hp1);
  9588. if assigned(hp2) and
  9589. assigned(hp1) and
  9590. (l<=3) and
  9591. (hp2.typ=ait_instruction) and
  9592. (taicpu(hp2).is_jmp) and
  9593. (taicpu(hp2).condition=C_None) and
  9594. { real label and jump, no further references to the
  9595. label are allowed }
  9596. (tasmlabel(symbol).getrefs=1) and
  9597. FindLabel(tasmlabel(symbol),hp1) then
  9598. begin
  9599. l:=0;
  9600. { skip hp1 to <several moves 2> }
  9601. if (hp1.typ = ait_align) then
  9602. GetNextInstruction(hp1, hp1);
  9603. GetNextInstruction(hp1, hpmov2);
  9604. hp1 := hpmov2;
  9605. while assigned(hp1) and
  9606. CanBeCMOV(hp1) do
  9607. begin
  9608. inc(l);
  9609. hp5 := hp1;
  9610. GetNextInstruction(hp1, hp1);
  9611. end;
  9612. { hp1 points to yyy (or an align right before it) }
  9613. hp3 := hp1;
  9614. if assigned(hp1) and
  9615. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9616. begin
  9617. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9618. condition:=inverse_cond(taicpu(p).condition);
  9619. UpdateUsedRegs(tai(p.next));
  9620. GetNextInstruction(p,hp1);
  9621. repeat
  9622. taicpu(hp1).opcode:=A_CMOVcc;
  9623. taicpu(hp1).condition:=condition;
  9624. UpdateUsedRegs(tai(hp1.next));
  9625. GetNextInstruction(hp1,hp1);
  9626. until not(assigned(hp1)) or
  9627. not(CanBeCMOV(hp1));
  9628. condition:=inverse_cond(condition);
  9629. if GetLastInstruction(hpmov2,hp1) then
  9630. UpdateUsedRegs(tai(hp1.next));
  9631. hp1 := hpmov2;
  9632. { hp1 is now at <several movs 2> }
  9633. while Assigned(hp1) and CanBeCMOV(hp1) do
  9634. begin
  9635. taicpu(hp1).opcode:=A_CMOVcc;
  9636. taicpu(hp1).condition:=condition;
  9637. UpdateUsedRegs(tai(hp1.next));
  9638. GetNextInstruction(hp1,hp1);
  9639. end;
  9640. hp1 := p;
  9641. { Get first instruction after label }
  9642. UpdateUsedRegs(tai(hp3.next));
  9643. GetNextInstruction(hp3, p);
  9644. if assigned(p) and (hp3.typ = ait_align) then
  9645. GetNextInstruction(p, p);
  9646. { Don't dereference yet, as doing so will cause
  9647. GetNextInstruction to skip the label and
  9648. optional align marker. [Kit] }
  9649. GetNextInstruction(hp2, hp4);
  9650. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9651. { remove jCC }
  9652. RemoveInstruction(hp1);
  9653. { Now we can safely decrement it }
  9654. tasmlabel(symbol).decrefs;
  9655. { Remove label xxx (it will have a ref of zero due to the initial check }
  9656. StripLabelFast(hp4);
  9657. { remove jmp }
  9658. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9659. RemoveInstruction(hp2);
  9660. { As before, now we can safely decrement it }
  9661. tasmlabel(symbol).decrefs;
  9662. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9663. if tasmlabel(symbol).getrefs = 0 then
  9664. StripLabelFast(hp3);
  9665. if Assigned(p) then
  9666. result:=true;
  9667. exit;
  9668. end;
  9669. end;
  9670. end;
  9671. end;
  9672. {$endif i8086}
  9673. end;
  9674. end;
  9675. end;
  9676. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9677. var
  9678. hp1,hp2,hp3: tai;
  9679. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9680. NewSize: TOpSize;
  9681. NewRegSize: TSubRegister;
  9682. Limit: TCgInt;
  9683. SwapOper: POper;
  9684. begin
  9685. result:=false;
  9686. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9687. GetNextInstruction(p,hp1) and
  9688. (hp1.typ = ait_instruction);
  9689. if reg_and_hp1_is_instr and
  9690. (
  9691. (taicpu(hp1).opcode <> A_LEA) or
  9692. { If the LEA instruction can be converted into an arithmetic instruction,
  9693. it may be possible to then fold it. }
  9694. (
  9695. { If the flags register is in use, don't change the instruction
  9696. to an ADD otherwise this will scramble the flags. [Kit] }
  9697. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9698. ConvertLEA(taicpu(hp1))
  9699. )
  9700. ) and
  9701. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9702. GetNextInstruction(hp1,hp2) and
  9703. MatchInstruction(hp2,A_MOV,[]) and
  9704. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9705. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9706. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9707. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9708. {$ifdef i386}
  9709. { not all registers have byte size sub registers on i386 }
  9710. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9711. {$endif i386}
  9712. (((taicpu(hp1).ops=2) and
  9713. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9714. ((taicpu(hp1).ops=1) and
  9715. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9716. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9717. begin
  9718. { change movsX/movzX reg/ref, reg2
  9719. add/sub/or/... reg3/$const, reg2
  9720. mov reg2 reg/ref
  9721. to add/sub/or/... reg3/$const, reg/ref }
  9722. { by example:
  9723. movswl %si,%eax movswl %si,%eax p
  9724. decl %eax addl %edx,%eax hp1
  9725. movw %ax,%si movw %ax,%si hp2
  9726. ->
  9727. movswl %si,%eax movswl %si,%eax p
  9728. decw %eax addw %edx,%eax hp1
  9729. movw %ax,%si movw %ax,%si hp2
  9730. }
  9731. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9732. {
  9733. ->
  9734. movswl %si,%eax movswl %si,%eax p
  9735. decw %si addw %dx,%si hp1
  9736. movw %ax,%si movw %ax,%si hp2
  9737. }
  9738. case taicpu(hp1).ops of
  9739. 1:
  9740. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9741. 2:
  9742. begin
  9743. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9744. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9745. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9746. end;
  9747. else
  9748. internalerror(2008042702);
  9749. end;
  9750. {
  9751. ->
  9752. decw %si addw %dx,%si p
  9753. }
  9754. DebugMsg(SPeepholeOptimization + 'var3',p);
  9755. RemoveCurrentP(p, hp1);
  9756. RemoveInstruction(hp2);
  9757. Result := True;
  9758. Exit;
  9759. end;
  9760. if reg_and_hp1_is_instr and
  9761. (taicpu(hp1).opcode = A_MOV) and
  9762. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9763. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9764. {$ifdef x86_64}
  9765. { check for implicit extension to 64 bit }
  9766. or
  9767. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9768. (taicpu(hp1).opsize=S_Q) and
  9769. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9770. )
  9771. {$endif x86_64}
  9772. )
  9773. then
  9774. begin
  9775. { change
  9776. movx %reg1,%reg2
  9777. mov %reg2,%reg3
  9778. dealloc %reg2
  9779. into
  9780. movx %reg,%reg3
  9781. }
  9782. TransferUsedRegs(TmpUsedRegs);
  9783. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9784. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9785. begin
  9786. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9787. {$ifdef x86_64}
  9788. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9789. (taicpu(hp1).opsize=S_Q) then
  9790. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9791. else
  9792. {$endif x86_64}
  9793. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9794. RemoveInstruction(hp1);
  9795. Result := True;
  9796. Exit;
  9797. end;
  9798. end;
  9799. if reg_and_hp1_is_instr and
  9800. ((taicpu(hp1).opcode=A_MOV) or
  9801. (taicpu(hp1).opcode=A_ADD) or
  9802. (taicpu(hp1).opcode=A_SUB) or
  9803. (taicpu(hp1).opcode=A_CMP) or
  9804. (taicpu(hp1).opcode=A_OR) or
  9805. (taicpu(hp1).opcode=A_XOR) or
  9806. (taicpu(hp1).opcode=A_AND)
  9807. ) and
  9808. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9809. begin
  9810. AndTest := (taicpu(hp1).opcode=A_AND) and
  9811. GetNextInstruction(hp1, hp2) and
  9812. (hp2.typ = ait_instruction) and
  9813. (
  9814. (
  9815. (taicpu(hp2).opcode=A_TEST) and
  9816. (
  9817. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  9818. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  9819. (
  9820. { If the AND and TEST instructions share a constant, this is also valid }
  9821. (taicpu(hp1).oper[0]^.typ = top_const) and
  9822. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  9823. )
  9824. ) and
  9825. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9826. ) or
  9827. (
  9828. (taicpu(hp2).opcode=A_CMP) and
  9829. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9830. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9831. )
  9832. );
  9833. { change
  9834. movx (oper),%reg2
  9835. and $x,%reg2
  9836. test %reg2,%reg2
  9837. dealloc %reg2
  9838. into
  9839. op %reg1,%reg3
  9840. if the second op accesses only the bits stored in reg1
  9841. }
  9842. if ((taicpu(p).oper[0]^.typ=top_reg) or
  9843. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  9844. (taicpu(hp1).oper[0]^.typ = top_const) and
  9845. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9846. AndTest then
  9847. begin
  9848. { Check if the AND constant is in range }
  9849. case taicpu(p).opsize of
  9850. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9851. begin
  9852. NewSize := S_B;
  9853. Limit := $FF;
  9854. end;
  9855. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9856. begin
  9857. NewSize := S_W;
  9858. Limit := $FFFF;
  9859. end;
  9860. {$ifdef x86_64}
  9861. S_LQ:
  9862. begin
  9863. NewSize := S_L;
  9864. Limit := $FFFFFFFF;
  9865. end;
  9866. {$endif x86_64}
  9867. else
  9868. InternalError(2021120303);
  9869. end;
  9870. if (
  9871. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  9872. { Check for negative operands }
  9873. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  9874. ) and
  9875. GetNextInstruction(hp2,hp3) and
  9876. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  9877. (taicpu(hp3).condition in [C_E,C_NE]) then
  9878. begin
  9879. TransferUsedRegs(TmpUsedRegs);
  9880. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9881. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9882. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  9883. begin
  9884. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  9885. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9886. taicpu(hp1).opcode := A_TEST;
  9887. taicpu(hp1).opsize := NewSize;
  9888. RemoveInstruction(hp2);
  9889. RemoveCurrentP(p, hp1);
  9890. Result:=true;
  9891. exit;
  9892. end;
  9893. end;
  9894. end;
  9895. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9896. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  9897. (taicpu(hp1).opsize=S_B)) or
  9898. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  9899. (taicpu(hp1).opsize=S_W))
  9900. {$ifdef x86_64}
  9901. or ((taicpu(p).opsize=S_LQ) and
  9902. (taicpu(hp1).opsize=S_L))
  9903. {$endif x86_64}
  9904. ) and
  9905. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  9906. begin
  9907. { change
  9908. movx %reg1,%reg2
  9909. op %reg2,%reg3
  9910. dealloc %reg2
  9911. into
  9912. op %reg1,%reg3
  9913. if the second op accesses only the bits stored in reg1
  9914. }
  9915. TransferUsedRegs(TmpUsedRegs);
  9916. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9917. if AndTest then
  9918. begin
  9919. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9920. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9921. end
  9922. else
  9923. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9924. if not RegUsed then
  9925. begin
  9926. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  9927. if taicpu(p).oper[0]^.typ=top_reg then
  9928. begin
  9929. case taicpu(hp1).opsize of
  9930. S_B:
  9931. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  9932. S_W:
  9933. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  9934. S_L:
  9935. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  9936. else
  9937. Internalerror(2020102301);
  9938. end;
  9939. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  9940. end
  9941. else
  9942. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  9943. RemoveCurrentP(p);
  9944. if AndTest then
  9945. RemoveInstruction(hp2);
  9946. result:=true;
  9947. exit;
  9948. end;
  9949. end
  9950. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9951. (
  9952. { Bitwise operations only }
  9953. (taicpu(hp1).opcode=A_AND) or
  9954. (taicpu(hp1).opcode=A_TEST) or
  9955. (
  9956. (taicpu(hp1).oper[0]^.typ = top_const) and
  9957. (
  9958. (taicpu(hp1).opcode=A_OR) or
  9959. (taicpu(hp1).opcode=A_XOR)
  9960. )
  9961. )
  9962. ) and
  9963. (
  9964. (taicpu(hp1).oper[0]^.typ = top_const) or
  9965. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  9966. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  9967. ) then
  9968. begin
  9969. { change
  9970. movx %reg2,%reg2
  9971. op const,%reg2
  9972. into
  9973. op const,%reg2 (smaller version)
  9974. movx %reg2,%reg2
  9975. also change
  9976. movx %reg1,%reg2
  9977. and/test (oper),%reg2
  9978. dealloc %reg2
  9979. into
  9980. and/test (oper),%reg1
  9981. }
  9982. case taicpu(p).opsize of
  9983. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9984. begin
  9985. NewSize := S_B;
  9986. NewRegSize := R_SUBL;
  9987. Limit := $FF;
  9988. end;
  9989. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9990. begin
  9991. NewSize := S_W;
  9992. NewRegSize := R_SUBW;
  9993. Limit := $FFFF;
  9994. end;
  9995. {$ifdef x86_64}
  9996. S_LQ:
  9997. begin
  9998. NewSize := S_L;
  9999. NewRegSize := R_SUBD;
  10000. Limit := $FFFFFFFF;
  10001. end;
  10002. {$endif x86_64}
  10003. else
  10004. Internalerror(2021120302);
  10005. end;
  10006. TransferUsedRegs(TmpUsedRegs);
  10007. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10008. if AndTest then
  10009. begin
  10010. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10011. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10012. end
  10013. else
  10014. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10015. if
  10016. (
  10017. (taicpu(p).opcode = A_MOVZX) and
  10018. (
  10019. (taicpu(hp1).opcode=A_AND) or
  10020. (taicpu(hp1).opcode=A_TEST)
  10021. ) and
  10022. not (
  10023. { If both are references, then the final instruction will have
  10024. both operands as references, which is not allowed }
  10025. (taicpu(p).oper[0]^.typ = top_ref) and
  10026. (taicpu(hp1).oper[0]^.typ = top_ref)
  10027. ) and
  10028. not RegUsed
  10029. ) or
  10030. (
  10031. (
  10032. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10033. not RegUsed
  10034. ) and
  10035. (taicpu(p).oper[0]^.typ = top_reg) and
  10036. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10037. (taicpu(hp1).oper[0]^.typ = top_const) and
  10038. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10039. ) then
  10040. begin
  10041. {$if defined(i386) or defined(i8086)}
  10042. { If the target size is 8-bit, make sure we can actually encode it }
  10043. 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
  10044. Exit;
  10045. {$endif i386 or i8086}
  10046. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10047. taicpu(hp1).opsize := NewSize;
  10048. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10049. if AndTest then
  10050. begin
  10051. RemoveInstruction(hp2);
  10052. if not RegUsed then
  10053. begin
  10054. taicpu(hp1).opcode := A_TEST;
  10055. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10056. begin
  10057. { Make sure the reference is the second operand }
  10058. SwapOper := taicpu(hp1).oper[0];
  10059. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10060. taicpu(hp1).oper[1] := SwapOper;
  10061. end;
  10062. end;
  10063. end;
  10064. case taicpu(hp1).oper[0]^.typ of
  10065. top_reg:
  10066. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10067. top_const:
  10068. { For the AND/TEST case }
  10069. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10070. else
  10071. ;
  10072. end;
  10073. if RegUsed then
  10074. begin
  10075. AsmL.Remove(p);
  10076. AsmL.InsertAfter(p, hp1);
  10077. p := hp1;
  10078. end
  10079. else
  10080. RemoveCurrentP(p, hp1);
  10081. result:=true;
  10082. exit;
  10083. end;
  10084. end;
  10085. end;
  10086. if reg_and_hp1_is_instr and
  10087. (taicpu(p).oper[0]^.typ = top_reg) and
  10088. (
  10089. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10090. ) and
  10091. (taicpu(hp1).oper[0]^.typ = top_const) and
  10092. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10093. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10094. { Minimum shift value allowed is the bit difference between the sizes }
  10095. (taicpu(hp1).oper[0]^.val >=
  10096. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10097. 8 * (
  10098. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10099. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10100. )
  10101. ) then
  10102. begin
  10103. { For:
  10104. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10105. shl/sal ##, %reg1
  10106. Remove the movsx/movzx instruction if the shift overwrites the
  10107. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10108. }
  10109. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10110. RemoveCurrentP(p, hp1);
  10111. Result := True;
  10112. Exit;
  10113. end
  10114. else if reg_and_hp1_is_instr and
  10115. (taicpu(p).oper[0]^.typ = top_reg) and
  10116. (
  10117. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10118. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10119. ) and
  10120. (taicpu(hp1).oper[0]^.typ = top_const) and
  10121. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10122. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10123. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10124. (taicpu(hp1).oper[0]^.val <
  10125. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10126. 8 * (
  10127. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10128. )
  10129. ) then
  10130. begin
  10131. { For:
  10132. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10133. sar ##, %reg1 shr ##, %reg1
  10134. Move the shift to before the movx instruction if the shift value
  10135. is not too large.
  10136. }
  10137. asml.Remove(hp1);
  10138. asml.InsertBefore(hp1, p);
  10139. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10140. case taicpu(p).opsize of
  10141. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10142. taicpu(hp1).opsize := S_B;
  10143. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10144. taicpu(hp1).opsize := S_W;
  10145. {$ifdef x86_64}
  10146. S_LQ:
  10147. taicpu(hp1).opsize := S_L;
  10148. {$endif}
  10149. else
  10150. InternalError(2020112401);
  10151. end;
  10152. if (taicpu(hp1).opcode = A_SHR) then
  10153. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10154. else
  10155. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10156. Result := True;
  10157. end;
  10158. if reg_and_hp1_is_instr and
  10159. (taicpu(p).oper[0]^.typ = top_reg) and
  10160. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10161. (
  10162. (taicpu(hp1).opcode = taicpu(p).opcode)
  10163. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10164. {$ifdef x86_64}
  10165. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10166. {$endif x86_64}
  10167. ) then
  10168. begin
  10169. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10170. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10171. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10172. begin
  10173. {
  10174. For example:
  10175. movzbw %al,%ax
  10176. movzwl %ax,%eax
  10177. Compress into:
  10178. movzbl %al,%eax
  10179. }
  10180. RegUsed := False;
  10181. case taicpu(p).opsize of
  10182. S_BW:
  10183. case taicpu(hp1).opsize of
  10184. S_WL:
  10185. begin
  10186. taicpu(p).opsize := S_BL;
  10187. RegUsed := True;
  10188. end;
  10189. {$ifdef x86_64}
  10190. S_WQ:
  10191. begin
  10192. if taicpu(p).opcode = A_MOVZX then
  10193. begin
  10194. taicpu(p).opsize := S_BL;
  10195. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10196. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10197. end
  10198. else
  10199. taicpu(p).opsize := S_BQ;
  10200. RegUsed := True;
  10201. end;
  10202. {$endif x86_64}
  10203. else
  10204. ;
  10205. end;
  10206. {$ifdef x86_64}
  10207. S_BL:
  10208. case taicpu(hp1).opsize of
  10209. S_LQ:
  10210. begin
  10211. if taicpu(p).opcode = A_MOVZX then
  10212. begin
  10213. taicpu(p).opsize := S_BL;
  10214. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10215. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10216. end
  10217. else
  10218. taicpu(p).opsize := S_BQ;
  10219. RegUsed := True;
  10220. end;
  10221. else
  10222. ;
  10223. end;
  10224. S_WL:
  10225. case taicpu(hp1).opsize of
  10226. S_LQ:
  10227. begin
  10228. if taicpu(p).opcode = A_MOVZX then
  10229. begin
  10230. taicpu(p).opsize := S_WL;
  10231. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10232. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10233. end
  10234. else
  10235. taicpu(p).opsize := S_WQ;
  10236. RegUsed := True;
  10237. end;
  10238. else
  10239. ;
  10240. end;
  10241. {$endif x86_64}
  10242. else
  10243. ;
  10244. end;
  10245. if RegUsed then
  10246. begin
  10247. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10248. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10249. RemoveInstruction(hp1);
  10250. Result := True;
  10251. Exit;
  10252. end;
  10253. end;
  10254. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10255. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10256. GetNextInstruction(hp1, hp2) and
  10257. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10258. (
  10259. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10260. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10261. {$ifdef x86_64}
  10262. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10263. {$endif x86_64}
  10264. ) and
  10265. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10266. (
  10267. (
  10268. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10269. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10270. ) or
  10271. (
  10272. { Only allow the operands in reverse order for TEST instructions }
  10273. (taicpu(hp2).opcode = A_TEST) and
  10274. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10275. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10276. )
  10277. ) then
  10278. begin
  10279. {
  10280. For example:
  10281. movzbl %al,%eax
  10282. movzbl (ref),%edx
  10283. andl %edx,%eax
  10284. (%edx deallocated)
  10285. Change to:
  10286. andb (ref),%al
  10287. movzbl %al,%eax
  10288. Rules are:
  10289. - First two instructions have the same opcode and opsize
  10290. - First instruction's operands are the same super-register
  10291. - Second instruction operates on a different register
  10292. - Third instruction is AND, OR, XOR or TEST
  10293. - Third instruction's operands are the destination registers of the first two instructions
  10294. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10295. - Second instruction's destination register is deallocated afterwards
  10296. }
  10297. TransferUsedRegs(TmpUsedRegs);
  10298. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10299. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10300. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10301. begin
  10302. case taicpu(p).opsize of
  10303. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10304. NewSize := S_B;
  10305. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10306. NewSize := S_W;
  10307. {$ifdef x86_64}
  10308. S_LQ:
  10309. NewSize := S_L;
  10310. {$endif x86_64}
  10311. else
  10312. InternalError(2021120301);
  10313. end;
  10314. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10315. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10316. taicpu(hp2).opsize := NewSize;
  10317. RemoveInstruction(hp1);
  10318. { With TEST, it's best to keep the MOVX instruction at the top }
  10319. if (taicpu(hp2).opcode <> A_TEST) then
  10320. begin
  10321. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10322. asml.Remove(p);
  10323. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10324. asml.InsertAfter(p, hp2);
  10325. p := hp2;
  10326. end
  10327. else
  10328. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10329. Result := True;
  10330. Exit;
  10331. end;
  10332. end;
  10333. end;
  10334. if taicpu(p).opcode=A_MOVZX then
  10335. begin
  10336. { removes superfluous And's after movzx's }
  10337. if reg_and_hp1_is_instr and
  10338. (taicpu(hp1).opcode = A_AND) and
  10339. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10340. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10341. {$ifdef x86_64}
  10342. { check for implicit extension to 64 bit }
  10343. or
  10344. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10345. (taicpu(hp1).opsize=S_Q) and
  10346. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10347. )
  10348. {$endif x86_64}
  10349. )
  10350. then
  10351. begin
  10352. case taicpu(p).opsize Of
  10353. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10354. if (taicpu(hp1).oper[0]^.val = $ff) then
  10355. begin
  10356. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10357. RemoveInstruction(hp1);
  10358. Result:=true;
  10359. exit;
  10360. end;
  10361. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10362. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10363. begin
  10364. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10365. RemoveInstruction(hp1);
  10366. Result:=true;
  10367. exit;
  10368. end;
  10369. {$ifdef x86_64}
  10370. S_LQ:
  10371. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10372. begin
  10373. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10374. RemoveInstruction(hp1);
  10375. Result:=true;
  10376. exit;
  10377. end;
  10378. {$endif x86_64}
  10379. else
  10380. ;
  10381. end;
  10382. { we cannot get rid of the and, but can we get rid of the movz ?}
  10383. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10384. begin
  10385. case taicpu(p).opsize Of
  10386. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10387. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10388. begin
  10389. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10390. RemoveCurrentP(p,hp1);
  10391. Result:=true;
  10392. exit;
  10393. end;
  10394. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10395. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10396. begin
  10397. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10398. RemoveCurrentP(p,hp1);
  10399. Result:=true;
  10400. exit;
  10401. end;
  10402. {$ifdef x86_64}
  10403. S_LQ:
  10404. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10405. begin
  10406. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10407. RemoveCurrentP(p,hp1);
  10408. Result:=true;
  10409. exit;
  10410. end;
  10411. {$endif x86_64}
  10412. else
  10413. ;
  10414. end;
  10415. end;
  10416. end;
  10417. { changes some movzx constructs to faster synonyms (all examples
  10418. are given with eax/ax, but are also valid for other registers)}
  10419. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10420. begin
  10421. case taicpu(p).opsize of
  10422. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10423. (the machine code is equivalent to movzbl %al,%eax), but the
  10424. code generator still generates that assembler instruction and
  10425. it is silently converted. This should probably be checked.
  10426. [Kit] }
  10427. S_BW:
  10428. begin
  10429. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10430. (
  10431. not IsMOVZXAcceptable
  10432. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10433. or (
  10434. (cs_opt_size in current_settings.optimizerswitches) and
  10435. (taicpu(p).oper[1]^.reg = NR_AX)
  10436. )
  10437. ) then
  10438. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10439. begin
  10440. DebugMsg(SPeepholeOptimization + 'var7',p);
  10441. taicpu(p).opcode := A_AND;
  10442. taicpu(p).changeopsize(S_W);
  10443. taicpu(p).loadConst(0,$ff);
  10444. Result := True;
  10445. end
  10446. else if not IsMOVZXAcceptable and
  10447. GetNextInstruction(p, hp1) and
  10448. (tai(hp1).typ = ait_instruction) and
  10449. (taicpu(hp1).opcode = A_AND) and
  10450. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10451. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10452. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10453. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10454. begin
  10455. DebugMsg(SPeepholeOptimization + 'var8',p);
  10456. taicpu(p).opcode := A_MOV;
  10457. taicpu(p).changeopsize(S_W);
  10458. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10459. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10460. Result := True;
  10461. end;
  10462. end;
  10463. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10464. S_BL:
  10465. begin
  10466. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10467. (
  10468. not IsMOVZXAcceptable
  10469. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10470. or (
  10471. (cs_opt_size in current_settings.optimizerswitches) and
  10472. (taicpu(p).oper[1]^.reg = NR_EAX)
  10473. )
  10474. ) then
  10475. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10476. begin
  10477. DebugMsg(SPeepholeOptimization + 'var9',p);
  10478. taicpu(p).opcode := A_AND;
  10479. taicpu(p).changeopsize(S_L);
  10480. taicpu(p).loadConst(0,$ff);
  10481. Result := True;
  10482. end
  10483. else if not IsMOVZXAcceptable and
  10484. GetNextInstruction(p, hp1) and
  10485. (tai(hp1).typ = ait_instruction) and
  10486. (taicpu(hp1).opcode = A_AND) and
  10487. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10488. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10489. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10490. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10491. begin
  10492. DebugMsg(SPeepholeOptimization + 'var10',p);
  10493. taicpu(p).opcode := A_MOV;
  10494. taicpu(p).changeopsize(S_L);
  10495. { do not use R_SUBWHOLE
  10496. as movl %rdx,%eax
  10497. is invalid in assembler PM }
  10498. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10499. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10500. Result := True;
  10501. end;
  10502. end;
  10503. {$endif i8086}
  10504. S_WL:
  10505. if not IsMOVZXAcceptable then
  10506. begin
  10507. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10508. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10509. begin
  10510. DebugMsg(SPeepholeOptimization + 'var11',p);
  10511. taicpu(p).opcode := A_AND;
  10512. taicpu(p).changeopsize(S_L);
  10513. taicpu(p).loadConst(0,$ffff);
  10514. Result := True;
  10515. end
  10516. else if GetNextInstruction(p, hp1) and
  10517. (tai(hp1).typ = ait_instruction) and
  10518. (taicpu(hp1).opcode = A_AND) and
  10519. (taicpu(hp1).oper[0]^.typ = top_const) and
  10520. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10521. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10522. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10523. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10524. begin
  10525. DebugMsg(SPeepholeOptimization + 'var12',p);
  10526. taicpu(p).opcode := A_MOV;
  10527. taicpu(p).changeopsize(S_L);
  10528. { do not use R_SUBWHOLE
  10529. as movl %rdx,%eax
  10530. is invalid in assembler PM }
  10531. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10532. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10533. Result := True;
  10534. end;
  10535. end;
  10536. else
  10537. InternalError(2017050705);
  10538. end;
  10539. end
  10540. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10541. begin
  10542. if GetNextInstruction(p, hp1) and
  10543. (tai(hp1).typ = ait_instruction) and
  10544. (taicpu(hp1).opcode = A_AND) and
  10545. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10546. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10547. begin
  10548. //taicpu(p).opcode := A_MOV;
  10549. case taicpu(p).opsize Of
  10550. S_BL:
  10551. begin
  10552. DebugMsg(SPeepholeOptimization + 'var13',p);
  10553. taicpu(hp1).changeopsize(S_L);
  10554. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10555. end;
  10556. S_WL:
  10557. begin
  10558. DebugMsg(SPeepholeOptimization + 'var14',p);
  10559. taicpu(hp1).changeopsize(S_L);
  10560. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10561. end;
  10562. S_BW:
  10563. begin
  10564. DebugMsg(SPeepholeOptimization + 'var15',p);
  10565. taicpu(hp1).changeopsize(S_W);
  10566. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10567. end;
  10568. else
  10569. Internalerror(2017050704)
  10570. end;
  10571. Result := True;
  10572. end;
  10573. end;
  10574. end;
  10575. end;
  10576. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10577. var
  10578. hp1, hp2 : tai;
  10579. MaskLength : Cardinal;
  10580. MaskedBits : TCgInt;
  10581. ActiveReg : TRegister;
  10582. begin
  10583. Result:=false;
  10584. { There are no optimisations for reference targets }
  10585. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10586. Exit;
  10587. while GetNextInstruction(p, hp1) and
  10588. (hp1.typ = ait_instruction) do
  10589. begin
  10590. if (taicpu(p).oper[0]^.typ = top_const) then
  10591. begin
  10592. case taicpu(hp1).opcode of
  10593. A_AND:
  10594. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10595. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10596. { the second register must contain the first one, so compare their subreg types }
  10597. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10598. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10599. { change
  10600. and const1, reg
  10601. and const2, reg
  10602. to
  10603. and (const1 and const2), reg
  10604. }
  10605. begin
  10606. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10607. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10608. RemoveCurrentP(p, hp1);
  10609. Result:=true;
  10610. exit;
  10611. end;
  10612. A_CMP:
  10613. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10614. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10615. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10616. { Just check that the condition on the next instruction is compatible }
  10617. GetNextInstruction(hp1, hp2) and
  10618. (hp2.typ = ait_instruction) and
  10619. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10620. then
  10621. { change
  10622. and 2^n, reg
  10623. cmp 2^n, reg
  10624. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10625. to
  10626. and 2^n, reg
  10627. test reg, reg
  10628. j(~c) / set(~c) / cmov(~c)
  10629. }
  10630. begin
  10631. { Keep TEST instruction in, rather than remove it, because
  10632. it may trigger other optimisations such as MovAndTest2Test }
  10633. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10634. taicpu(hp1).opcode := A_TEST;
  10635. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10636. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10637. Result := True;
  10638. Exit;
  10639. end;
  10640. A_MOVZX:
  10641. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10642. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10643. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10644. (
  10645. (
  10646. (taicpu(p).opsize=S_W) and
  10647. (taicpu(hp1).opsize=S_BW)
  10648. ) or
  10649. (
  10650. (taicpu(p).opsize=S_L) and
  10651. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10652. )
  10653. {$ifdef x86_64}
  10654. or
  10655. (
  10656. (taicpu(p).opsize=S_Q) and
  10657. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10658. )
  10659. {$endif x86_64}
  10660. ) then
  10661. begin
  10662. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10663. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10664. ) or
  10665. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10666. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10667. then
  10668. begin
  10669. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10670. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10671. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10672. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10673. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10674. }
  10675. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10676. RemoveInstruction(hp1);
  10677. { See if there are other optimisations possible }
  10678. Continue;
  10679. end;
  10680. end;
  10681. A_SHL:
  10682. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10683. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10684. begin
  10685. {$ifopt R+}
  10686. {$define RANGE_WAS_ON}
  10687. {$R-}
  10688. {$endif}
  10689. { get length of potential and mask }
  10690. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10691. { really a mask? }
  10692. {$ifdef RANGE_WAS_ON}
  10693. {$R+}
  10694. {$endif}
  10695. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10696. { unmasked part shifted out? }
  10697. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10698. begin
  10699. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10700. RemoveCurrentP(p, hp1);
  10701. Result:=true;
  10702. exit;
  10703. end;
  10704. end;
  10705. A_SHR:
  10706. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10707. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10708. (taicpu(hp1).oper[0]^.val <= 63) then
  10709. begin
  10710. { Does SHR combined with the AND cover all the bits?
  10711. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10712. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10713. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10714. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10715. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10716. begin
  10717. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10718. RemoveCurrentP(p, hp1);
  10719. Result := True;
  10720. Exit;
  10721. end;
  10722. end;
  10723. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10724. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10725. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10726. begin
  10727. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10728. (
  10729. (
  10730. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10731. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10732. ) or (
  10733. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10734. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10735. {$ifdef x86_64}
  10736. ) or (
  10737. (taicpu(hp1).opsize = S_LQ) and
  10738. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10739. {$endif x86_64}
  10740. )
  10741. ) then
  10742. begin
  10743. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10744. begin
  10745. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10746. RemoveInstruction(hp1);
  10747. { See if there are other optimisations possible }
  10748. Continue;
  10749. end;
  10750. { The super-registers are the same though.
  10751. Note that this change by itself doesn't improve
  10752. code speed, but it opens up other optimisations. }
  10753. {$ifdef x86_64}
  10754. { Convert 64-bit register to 32-bit }
  10755. case taicpu(hp1).opsize of
  10756. S_BQ:
  10757. begin
  10758. taicpu(hp1).opsize := S_BL;
  10759. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10760. end;
  10761. S_WQ:
  10762. begin
  10763. taicpu(hp1).opsize := S_WL;
  10764. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10765. end
  10766. else
  10767. ;
  10768. end;
  10769. {$endif x86_64}
  10770. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10771. taicpu(hp1).opcode := A_MOVZX;
  10772. { See if there are other optimisations possible }
  10773. Continue;
  10774. end;
  10775. end;
  10776. else
  10777. ;
  10778. end;
  10779. end
  10780. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10781. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10782. begin
  10783. {$ifdef x86_64}
  10784. if (taicpu(p).opsize = S_Q) then
  10785. begin
  10786. { Never necessary }
  10787. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10788. RemoveCurrentP(p, hp1);
  10789. Result := True;
  10790. Exit;
  10791. end;
  10792. {$endif x86_64}
  10793. { Forward check to determine necessity of and %reg,%reg }
  10794. TransferUsedRegs(TmpUsedRegs);
  10795. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10796. { Saves on a bunch of dereferences }
  10797. ActiveReg := taicpu(p).oper[1]^.reg;
  10798. case taicpu(hp1).opcode of
  10799. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10800. if (
  10801. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10802. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10803. ) and
  10804. (
  10805. (taicpu(hp1).opcode <> A_MOV) or
  10806. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  10807. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  10808. ) and
  10809. not (
  10810. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  10811. (taicpu(hp1).opcode = A_MOV) and
  10812. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  10813. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  10814. ) and
  10815. (
  10816. (
  10817. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10818. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  10819. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  10820. ) or
  10821. (
  10822. {$ifdef x86_64}
  10823. (
  10824. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  10825. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  10826. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  10827. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  10828. ) and
  10829. {$endif x86_64}
  10830. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  10831. )
  10832. ) then
  10833. begin
  10834. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  10835. RemoveCurrentP(p, hp1);
  10836. Result := True;
  10837. Exit;
  10838. end;
  10839. A_ADD,
  10840. A_AND,
  10841. A_BSF,
  10842. A_BSR,
  10843. A_BTC,
  10844. A_BTR,
  10845. A_BTS,
  10846. A_OR,
  10847. A_SUB,
  10848. A_XOR:
  10849. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  10850. if (
  10851. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10852. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10853. ) and
  10854. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  10855. begin
  10856. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  10857. RemoveCurrentP(p, hp1);
  10858. Result := True;
  10859. Exit;
  10860. end;
  10861. A_CMP,
  10862. A_TEST:
  10863. if (
  10864. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10865. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10866. ) and
  10867. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  10868. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  10869. begin
  10870. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  10871. RemoveCurrentP(p, hp1);
  10872. Result := True;
  10873. Exit;
  10874. end;
  10875. A_BSWAP,
  10876. A_NEG,
  10877. A_NOT:
  10878. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  10879. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  10880. begin
  10881. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  10882. RemoveCurrentP(p, hp1);
  10883. Result := True;
  10884. Exit;
  10885. end;
  10886. else
  10887. ;
  10888. end;
  10889. end;
  10890. if (taicpu(hp1).is_jmp) and
  10891. (taicpu(hp1).opcode<>A_JMP) and
  10892. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  10893. begin
  10894. { change
  10895. and x, reg
  10896. jxx
  10897. to
  10898. test x, reg
  10899. jxx
  10900. if reg is deallocated before the
  10901. jump, but only if it's a conditional jump (PFV)
  10902. }
  10903. taicpu(p).opcode := A_TEST;
  10904. Exit;
  10905. end;
  10906. Break;
  10907. end;
  10908. { Lone AND tests }
  10909. if (taicpu(p).oper[0]^.typ = top_const) then
  10910. begin
  10911. {
  10912. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  10913. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  10914. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  10915. }
  10916. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  10917. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  10918. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  10919. begin
  10920. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  10921. if taicpu(p).opsize = S_L then
  10922. begin
  10923. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  10924. Result := True;
  10925. end;
  10926. end;
  10927. end;
  10928. { Backward check to determine necessity of and %reg,%reg }
  10929. if (taicpu(p).oper[0]^.typ = top_reg) and
  10930. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10931. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10932. GetLastInstruction(p, hp2) and
  10933. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  10934. { Check size of adjacent instruction to determine if the AND is
  10935. effectively a null operation }
  10936. (
  10937. (taicpu(p).opsize = taicpu(hp2).opsize) or
  10938. { Note: Don't include S_Q }
  10939. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  10940. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  10941. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  10942. ) then
  10943. begin
  10944. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  10945. { If GetNextInstruction returned False, hp1 will be nil }
  10946. RemoveCurrentP(p, hp1);
  10947. Result := True;
  10948. Exit;
  10949. end;
  10950. end;
  10951. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  10952. var
  10953. hp1: tai; NewRef: TReference;
  10954. { This entire nested function is used in an if-statement below, but we
  10955. want to avoid all the used reg transfers and GetNextInstruction calls
  10956. until we really have to check }
  10957. function MemRegisterNotUsedLater: Boolean; inline;
  10958. var
  10959. hp2: tai;
  10960. begin
  10961. TransferUsedRegs(TmpUsedRegs);
  10962. hp2 := p;
  10963. repeat
  10964. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10965. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10966. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  10967. end;
  10968. begin
  10969. Result := False;
  10970. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  10971. Exit;
  10972. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  10973. begin
  10974. { Change:
  10975. add %reg2,%reg1
  10976. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  10977. To:
  10978. mov/s/z #(%reg1,%reg2),%reg1
  10979. }
  10980. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10981. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  10982. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  10983. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  10984. (
  10985. (
  10986. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  10987. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  10988. { r/esp cannot be an index }
  10989. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  10990. ) or (
  10991. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  10992. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  10993. )
  10994. ) and (
  10995. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  10996. (
  10997. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  10998. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10999. MemRegisterNotUsedLater
  11000. )
  11001. ) then
  11002. begin
  11003. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11004. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11005. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11006. RemoveCurrentp(p, hp1);
  11007. Result := True;
  11008. Exit;
  11009. end;
  11010. { Change:
  11011. addl/q $x,%reg1
  11012. movl/q %reg1,%reg2
  11013. To:
  11014. leal/q $x(%reg1),%reg2
  11015. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11016. Breaks the dependency chain.
  11017. }
  11018. if MatchOpType(taicpu(p),top_const,top_reg) and
  11019. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11020. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11021. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11022. (
  11023. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11024. not (cs_opt_size in current_settings.optimizerswitches) or
  11025. (
  11026. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11027. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11028. )
  11029. ) then
  11030. begin
  11031. { Change the MOV instruction to a LEA instruction, and update the
  11032. first operand }
  11033. reference_reset(NewRef, 1, []);
  11034. NewRef.base := taicpu(p).oper[1]^.reg;
  11035. NewRef.scalefactor := 1;
  11036. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11037. taicpu(hp1).opcode := A_LEA;
  11038. taicpu(hp1).loadref(0, NewRef);
  11039. TransferUsedRegs(TmpUsedRegs);
  11040. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11041. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11042. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11043. begin
  11044. { Move what is now the LEA instruction to before the SUB instruction }
  11045. Asml.Remove(hp1);
  11046. Asml.InsertBefore(hp1, p);
  11047. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11048. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11049. p := hp1;
  11050. end
  11051. else
  11052. begin
  11053. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11054. RemoveCurrentP(p, hp1);
  11055. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  11056. end;
  11057. Result := True;
  11058. end;
  11059. end;
  11060. end;
  11061. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11062. var
  11063. SubReg: TSubRegister;
  11064. begin
  11065. Result:=false;
  11066. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11067. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11068. with taicpu(p).oper[0]^.ref^ do
  11069. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11070. begin
  11071. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11072. begin
  11073. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11074. taicpu(p).opcode := A_ADD;
  11075. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11076. Result := True;
  11077. end
  11078. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11079. begin
  11080. if (base <> NR_NO) then
  11081. begin
  11082. if (scalefactor <= 1) then
  11083. begin
  11084. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11085. taicpu(p).opcode := A_ADD;
  11086. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11087. Result := True;
  11088. end;
  11089. end
  11090. else
  11091. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11092. if (scalefactor in [2, 4, 8]) then
  11093. begin
  11094. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11095. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11096. taicpu(p).opcode := A_SHL;
  11097. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11098. Result := True;
  11099. end;
  11100. end;
  11101. end;
  11102. end;
  11103. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11104. var
  11105. hp1: tai; NewRef: TReference;
  11106. begin
  11107. { Change:
  11108. subl/q $x,%reg1
  11109. movl/q %reg1,%reg2
  11110. To:
  11111. leal/q $-x(%reg1),%reg2
  11112. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11113. Breaks the dependency chain and potentially permits the removal of
  11114. a CMP instruction if one follows.
  11115. }
  11116. Result := False;
  11117. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11118. MatchOpType(taicpu(p),top_const,top_reg) and
  11119. GetNextInstruction(p, hp1) and
  11120. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11121. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11122. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11123. (
  11124. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11125. not (cs_opt_size in current_settings.optimizerswitches) or
  11126. (
  11127. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11128. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11129. )
  11130. ) then
  11131. begin
  11132. { Change the MOV instruction to a LEA instruction, and update the
  11133. first operand }
  11134. reference_reset(NewRef, 1, []);
  11135. NewRef.base := taicpu(p).oper[1]^.reg;
  11136. NewRef.scalefactor := 1;
  11137. NewRef.offset := -taicpu(p).oper[0]^.val;
  11138. taicpu(hp1).opcode := A_LEA;
  11139. taicpu(hp1).loadref(0, NewRef);
  11140. TransferUsedRegs(TmpUsedRegs);
  11141. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11142. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11143. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11144. begin
  11145. { Move what is now the LEA instruction to before the SUB instruction }
  11146. Asml.Remove(hp1);
  11147. Asml.InsertBefore(hp1, p);
  11148. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11149. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11150. p := hp1;
  11151. end
  11152. else
  11153. begin
  11154. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11155. RemoveCurrentP(p, hp1);
  11156. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11157. end;
  11158. Result := True;
  11159. end;
  11160. end;
  11161. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11162. begin
  11163. { we can skip all instructions not messing with the stack pointer }
  11164. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11165. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11166. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11167. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11168. ({(taicpu(hp1).ops=0) or }
  11169. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11170. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11171. ) and }
  11172. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11173. )
  11174. ) do
  11175. GetNextInstruction(hp1,hp1);
  11176. Result:=assigned(hp1);
  11177. end;
  11178. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11179. var
  11180. hp1, hp2, hp3, hp4, hp5: tai;
  11181. begin
  11182. Result:=false;
  11183. hp5:=nil;
  11184. { replace
  11185. leal(q) x(<stackpointer>),<stackpointer>
  11186. call procname
  11187. leal(q) -x(<stackpointer>),<stackpointer>
  11188. ret
  11189. by
  11190. jmp procname
  11191. but do it only on level 4 because it destroys stack back traces
  11192. }
  11193. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11194. MatchOpType(taicpu(p),top_ref,top_reg) and
  11195. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11196. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11197. { the -8 or -24 are not required, but bail out early if possible,
  11198. higher values are unlikely }
  11199. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11200. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11201. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11202. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11203. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11204. GetNextInstruction(p, hp1) and
  11205. { Take a copy of hp1 }
  11206. SetAndTest(hp1, hp4) and
  11207. { trick to skip label }
  11208. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11209. SkipSimpleInstructions(hp1) and
  11210. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11211. GetNextInstruction(hp1, hp2) and
  11212. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11213. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11214. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11215. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11216. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11217. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11218. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11219. { Segment register will be NR_NO }
  11220. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11221. GetNextInstruction(hp2, hp3) and
  11222. { trick to skip label }
  11223. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11224. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11225. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11226. SetAndTest(hp3,hp5) and
  11227. GetNextInstruction(hp3,hp3) and
  11228. MatchInstruction(hp3,A_RET,[S_NO])
  11229. )
  11230. ) and
  11231. (taicpu(hp3).ops=0) then
  11232. begin
  11233. taicpu(hp1).opcode := A_JMP;
  11234. taicpu(hp1).is_jmp := true;
  11235. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11236. RemoveCurrentP(p, hp4);
  11237. RemoveInstruction(hp2);
  11238. RemoveInstruction(hp3);
  11239. if Assigned(hp5) then
  11240. begin
  11241. AsmL.Remove(hp5);
  11242. ASmL.InsertBefore(hp5,hp1)
  11243. end;
  11244. Result:=true;
  11245. end;
  11246. end;
  11247. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11248. {$ifdef x86_64}
  11249. var
  11250. hp1, hp2, hp3, hp4, hp5: tai;
  11251. {$endif x86_64}
  11252. begin
  11253. Result:=false;
  11254. {$ifdef x86_64}
  11255. hp5:=nil;
  11256. { replace
  11257. push %rax
  11258. call procname
  11259. pop %rcx
  11260. ret
  11261. by
  11262. jmp procname
  11263. but do it only on level 4 because it destroys stack back traces
  11264. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11265. for all supported calling conventions
  11266. }
  11267. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11268. MatchOpType(taicpu(p),top_reg) and
  11269. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11270. GetNextInstruction(p, hp1) and
  11271. { Take a copy of hp1 }
  11272. SetAndTest(hp1, hp4) and
  11273. { trick to skip label }
  11274. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11275. SkipSimpleInstructions(hp1) and
  11276. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11277. GetNextInstruction(hp1, hp2) and
  11278. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11279. MatchOpType(taicpu(hp2),top_reg) and
  11280. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11281. GetNextInstruction(hp2, hp3) and
  11282. { trick to skip label }
  11283. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11284. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11285. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11286. SetAndTest(hp3,hp5) and
  11287. GetNextInstruction(hp3,hp3) and
  11288. MatchInstruction(hp3,A_RET,[S_NO])
  11289. )
  11290. ) and
  11291. (taicpu(hp3).ops=0) then
  11292. begin
  11293. taicpu(hp1).opcode := A_JMP;
  11294. taicpu(hp1).is_jmp := true;
  11295. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11296. RemoveCurrentP(p, hp4);
  11297. RemoveInstruction(hp2);
  11298. RemoveInstruction(hp3);
  11299. if Assigned(hp5) then
  11300. begin
  11301. AsmL.Remove(hp5);
  11302. ASmL.InsertBefore(hp5,hp1)
  11303. end;
  11304. Result:=true;
  11305. end;
  11306. {$endif x86_64}
  11307. end;
  11308. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11309. var
  11310. Value, RegName: string;
  11311. begin
  11312. Result:=false;
  11313. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11314. begin
  11315. case taicpu(p).oper[0]^.val of
  11316. 0:
  11317. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11318. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11319. begin
  11320. { change "mov $0,%reg" into "xor %reg,%reg" }
  11321. taicpu(p).opcode := A_XOR;
  11322. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11323. Result := True;
  11324. {$ifdef x86_64}
  11325. end
  11326. else if (taicpu(p).opsize = S_Q) then
  11327. begin
  11328. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11329. { The actual optimization }
  11330. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11331. taicpu(p).changeopsize(S_L);
  11332. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11333. Result := True;
  11334. end;
  11335. $1..$FFFFFFFF:
  11336. begin
  11337. { Code size reduction by J. Gareth "Kit" Moreton }
  11338. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11339. case taicpu(p).opsize of
  11340. S_Q:
  11341. begin
  11342. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11343. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11344. { The actual optimization }
  11345. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11346. taicpu(p).changeopsize(S_L);
  11347. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11348. Result := True;
  11349. end;
  11350. else
  11351. { Do nothing };
  11352. end;
  11353. {$endif x86_64}
  11354. end;
  11355. -1:
  11356. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11357. if (cs_opt_size in current_settings.optimizerswitches) and
  11358. (taicpu(p).opsize <> S_B) and
  11359. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11360. begin
  11361. { change "mov $-1,%reg" into "or $-1,%reg" }
  11362. { NOTES:
  11363. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11364. - This operation creates a false dependency on the register, so only do it when optimising for size
  11365. - 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
  11366. }
  11367. taicpu(p).opcode := A_OR;
  11368. Result := True;
  11369. end;
  11370. else
  11371. { Do nothing };
  11372. end;
  11373. end;
  11374. end;
  11375. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11376. var
  11377. hp1: tai;
  11378. begin
  11379. { Detect:
  11380. andw x, %ax (0 <= x < $8000)
  11381. ...
  11382. movzwl %ax,%eax
  11383. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11384. }
  11385. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11386. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11387. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11388. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11389. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11390. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11391. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11392. begin
  11393. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11394. taicpu(hp1).opcode := A_CWDE;
  11395. taicpu(hp1).clearop(0);
  11396. taicpu(hp1).clearop(1);
  11397. taicpu(hp1).ops := 0;
  11398. { A change was made, but not with p, so move forward 1 }
  11399. p := tai(p.Next);
  11400. Result := True;
  11401. end;
  11402. end;
  11403. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11404. begin
  11405. Result := False;
  11406. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11407. Exit;
  11408. { Convert:
  11409. movswl %ax,%eax -> cwtl
  11410. movslq %eax,%rax -> cdqe
  11411. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11412. refer to the same opcode and depends only on the assembler's
  11413. current operand-size attribute. [Kit]
  11414. }
  11415. with taicpu(p) do
  11416. case opsize of
  11417. S_WL:
  11418. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11419. begin
  11420. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11421. opcode := A_CWDE;
  11422. clearop(0);
  11423. clearop(1);
  11424. ops := 0;
  11425. Result := True;
  11426. end;
  11427. {$ifdef x86_64}
  11428. S_LQ:
  11429. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11430. begin
  11431. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11432. opcode := A_CDQE;
  11433. clearop(0);
  11434. clearop(1);
  11435. ops := 0;
  11436. Result := True;
  11437. end;
  11438. {$endif x86_64}
  11439. else
  11440. ;
  11441. end;
  11442. end;
  11443. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11444. var
  11445. hp1: tai;
  11446. begin
  11447. { Detect:
  11448. shr x, %ax (x > 0)
  11449. ...
  11450. movzwl %ax,%eax
  11451. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11452. }
  11453. Result := False;
  11454. if MatchOpType(taicpu(p), top_const, top_reg) and
  11455. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11456. (taicpu(p).oper[0]^.val > 0) and
  11457. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11458. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11459. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11460. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11461. begin
  11462. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11463. taicpu(hp1).opcode := A_CWDE;
  11464. taicpu(hp1).clearop(0);
  11465. taicpu(hp1).clearop(1);
  11466. taicpu(hp1).ops := 0;
  11467. { A change was made, but not with p, so move forward 1 }
  11468. p := tai(p.Next);
  11469. Result := True;
  11470. end;
  11471. end;
  11472. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11473. var
  11474. hp1, hp2: tai;
  11475. Opposite, SecondOpposite: TAsmOp;
  11476. NewCond: TAsmCond;
  11477. begin
  11478. Result := False;
  11479. { Change:
  11480. add/sub 128,(dest)
  11481. To:
  11482. sub/add -128,(dest)
  11483. This generaally takes fewer bytes to encode because -128 can be stored
  11484. in a signed byte, whereas +128 cannot.
  11485. }
  11486. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11487. begin
  11488. if taicpu(p).opcode = A_ADD then
  11489. Opposite := A_SUB
  11490. else
  11491. Opposite := A_ADD;
  11492. { Be careful if the flags are in use, because the CF flag inverts
  11493. when changing from ADD to SUB and vice versa }
  11494. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11495. GetNextInstruction(p, hp1) then
  11496. begin
  11497. TransferUsedRegs(TmpUsedRegs);
  11498. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11499. hp2 := hp1;
  11500. { Scan ahead to check if everything's safe }
  11501. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11502. begin
  11503. if (hp1.typ <> ait_instruction) then
  11504. { Probably unsafe since the flags are still in use }
  11505. Exit;
  11506. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11507. { Stop searching at an unconditional jump }
  11508. Break;
  11509. if not
  11510. (
  11511. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11512. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11513. ) and
  11514. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11515. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11516. Exit;
  11517. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11518. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11519. { Move to the next instruction }
  11520. GetNextInstruction(hp1, hp1);
  11521. end;
  11522. while Assigned(hp2) and (hp2 <> hp1) do
  11523. begin
  11524. NewCond := C_None;
  11525. case taicpu(hp2).condition of
  11526. C_A, C_NBE:
  11527. NewCond := C_BE;
  11528. C_B, C_C, C_NAE:
  11529. NewCond := C_AE;
  11530. C_AE, C_NB, C_NC:
  11531. NewCond := C_B;
  11532. C_BE, C_NA:
  11533. NewCond := C_A;
  11534. else
  11535. { No change needed };
  11536. end;
  11537. if NewCond <> C_None then
  11538. begin
  11539. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11540. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11541. taicpu(hp2).condition := NewCond;
  11542. end
  11543. else
  11544. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11545. begin
  11546. { Because of the flipping of the carry bit, to ensure
  11547. the operation remains equivalent, ADC becomes SBB
  11548. and vice versa, and the constant is not-inverted.
  11549. If multiple ADCs or SBBs appear in a row, each one
  11550. changed causes the carry bit to invert, so they all
  11551. need to be flipped }
  11552. if taicpu(hp2).opcode = A_ADC then
  11553. SecondOpposite := A_SBB
  11554. else
  11555. SecondOpposite := A_ADC;
  11556. if taicpu(hp2).oper[0]^.typ <> top_const then
  11557. { Should have broken out of this optimisation already }
  11558. InternalError(2021112901);
  11559. 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]^) + ' -> ' +
  11560. 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);
  11561. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11562. taicpu(hp2).opcode := SecondOpposite;
  11563. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11564. end;
  11565. { Move to the next instruction }
  11566. GetNextInstruction(hp2, hp2);
  11567. end;
  11568. if (hp2 <> hp1) then
  11569. InternalError(2021111501);
  11570. end;
  11571. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11572. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11573. taicpu(p).opcode := Opposite;
  11574. taicpu(p).oper[0]^.val := -128;
  11575. { No further optimisations can be made on this instruction, so move
  11576. onto the next one to save time }
  11577. p := tai(p.Next);
  11578. UpdateUsedRegs(p);
  11579. Result := True;
  11580. Exit;
  11581. end;
  11582. { Detect:
  11583. add/sub %reg2,(dest)
  11584. add/sub x, (dest)
  11585. (dest can be a register or a reference)
  11586. Swap the instructions to minimise a pipeline stall. This reverses the
  11587. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11588. optimisations could be made.
  11589. }
  11590. if (taicpu(p).oper[0]^.typ = top_reg) and
  11591. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11592. (
  11593. (
  11594. (taicpu(p).oper[1]^.typ = top_reg) and
  11595. { We can try searching further ahead if we're writing to a register }
  11596. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11597. ) or
  11598. (
  11599. (taicpu(p).oper[1]^.typ = top_ref) and
  11600. GetNextInstruction(p, hp1)
  11601. )
  11602. ) and
  11603. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11604. (taicpu(hp1).oper[0]^.typ = top_const) and
  11605. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11606. begin
  11607. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11608. TransferUsedRegs(TmpUsedRegs);
  11609. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11610. hp2 := p;
  11611. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11612. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11613. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11614. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11615. begin
  11616. asml.remove(hp1);
  11617. asml.InsertBefore(hp1, p);
  11618. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11619. Result := True;
  11620. end;
  11621. end;
  11622. end;
  11623. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11624. begin
  11625. Result:=false;
  11626. { change "cmp $0, %reg" to "test %reg, %reg" }
  11627. if MatchOpType(taicpu(p),top_const,top_reg) and
  11628. (taicpu(p).oper[0]^.val = 0) then
  11629. begin
  11630. taicpu(p).opcode := A_TEST;
  11631. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11632. Result:=true;
  11633. end;
  11634. end;
  11635. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11636. var
  11637. IsTestConstX : Boolean;
  11638. hp1,hp2 : tai;
  11639. begin
  11640. Result:=false;
  11641. { removes the line marked with (x) from the sequence
  11642. and/or/xor/add/sub/... $x, %y
  11643. test/or %y, %y | test $-1, %y (x)
  11644. j(n)z _Label
  11645. as the first instruction already adjusts the ZF
  11646. %y operand may also be a reference }
  11647. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11648. MatchOperand(taicpu(p).oper[0]^,-1);
  11649. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11650. GetLastInstruction(p, hp1) and
  11651. (tai(hp1).typ = ait_instruction) and
  11652. GetNextInstruction(p,hp2) and
  11653. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11654. case taicpu(hp1).opcode Of
  11655. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11656. { These two instructions set the zero flag if the result is zero }
  11657. A_POPCNT, A_LZCNT:
  11658. begin
  11659. if (
  11660. { With POPCNT, an input of zero will set the zero flag
  11661. because the population count of zero is zero }
  11662. (taicpu(hp1).opcode = A_POPCNT) and
  11663. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11664. (
  11665. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11666. { Faster than going through the second half of the 'or'
  11667. condition below }
  11668. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11669. )
  11670. ) or (
  11671. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11672. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11673. { and in case of carry for A(E)/B(E)/C/NC }
  11674. (
  11675. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11676. (
  11677. (taicpu(hp1).opcode <> A_ADD) and
  11678. (taicpu(hp1).opcode <> A_SUB) and
  11679. (taicpu(hp1).opcode <> A_LZCNT)
  11680. )
  11681. )
  11682. ) then
  11683. begin
  11684. RemoveCurrentP(p, hp2);
  11685. Result:=true;
  11686. Exit;
  11687. end;
  11688. end;
  11689. A_SHL, A_SAL, A_SHR, A_SAR:
  11690. begin
  11691. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11692. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11693. { therefore, it's only safe to do this optimization for }
  11694. { shifts by a (nonzero) constant }
  11695. (taicpu(hp1).oper[0]^.typ = top_const) and
  11696. (taicpu(hp1).oper[0]^.val <> 0) and
  11697. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11698. { and in case of carry for A(E)/B(E)/C/NC }
  11699. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11700. begin
  11701. RemoveCurrentP(p, hp2);
  11702. Result:=true;
  11703. Exit;
  11704. end;
  11705. end;
  11706. A_DEC, A_INC, A_NEG:
  11707. begin
  11708. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11709. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11710. { and in case of carry for A(E)/B(E)/C/NC }
  11711. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11712. begin
  11713. RemoveCurrentP(p, hp2);
  11714. Result:=true;
  11715. Exit;
  11716. end;
  11717. end
  11718. else
  11719. ;
  11720. end; { case }
  11721. { change "test $-1,%reg" into "test %reg,%reg" }
  11722. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11723. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11724. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11725. if MatchInstruction(p, A_OR, []) and
  11726. { Can only match if they're both registers }
  11727. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11728. begin
  11729. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11730. taicpu(p).opcode := A_TEST;
  11731. { No need to set Result to True, as we've done all the optimisations we can }
  11732. end;
  11733. end;
  11734. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11735. var
  11736. hp1,hp3 : tai;
  11737. {$ifndef x86_64}
  11738. hp2 : taicpu;
  11739. {$endif x86_64}
  11740. begin
  11741. Result:=false;
  11742. hp3:=nil;
  11743. {$ifndef x86_64}
  11744. { don't do this on modern CPUs, this really hurts them due to
  11745. broken call/ret pairing }
  11746. if (current_settings.optimizecputype < cpu_Pentium2) and
  11747. not(cs_create_pic in current_settings.moduleswitches) and
  11748. GetNextInstruction(p, hp1) and
  11749. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11750. MatchOpType(taicpu(hp1),top_ref) and
  11751. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11752. begin
  11753. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11754. InsertLLItem(p.previous, p, hp2);
  11755. taicpu(p).opcode := A_JMP;
  11756. taicpu(p).is_jmp := true;
  11757. RemoveInstruction(hp1);
  11758. Result:=true;
  11759. end
  11760. else
  11761. {$endif x86_64}
  11762. { replace
  11763. call procname
  11764. ret
  11765. by
  11766. jmp procname
  11767. but do it only on level 4 because it destroys stack back traces
  11768. else if the subroutine is marked as no return, remove the ret
  11769. }
  11770. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11771. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11772. GetNextInstruction(p, hp1) and
  11773. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11774. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11775. SetAndTest(hp1,hp3) and
  11776. GetNextInstruction(hp1,hp1) and
  11777. MatchInstruction(hp1,A_RET,[S_NO])
  11778. )
  11779. ) and
  11780. (taicpu(hp1).ops=0) then
  11781. begin
  11782. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11783. { we might destroy stack alignment here if we do not do a call }
  11784. (target_info.stackalign<=sizeof(SizeUInt)) then
  11785. begin
  11786. taicpu(p).opcode := A_JMP;
  11787. taicpu(p).is_jmp := true;
  11788. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11789. end
  11790. else
  11791. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11792. RemoveInstruction(hp1);
  11793. if Assigned(hp3) then
  11794. begin
  11795. AsmL.Remove(hp3);
  11796. AsmL.InsertBefore(hp3,p)
  11797. end;
  11798. Result:=true;
  11799. end;
  11800. end;
  11801. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  11802. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  11803. begin
  11804. case OpSize of
  11805. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11806. Result := (Val <= $FF) and (Val >= -128);
  11807. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11808. Result := (Val <= $FFFF) and (Val >= -32768);
  11809. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  11810. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  11811. else
  11812. Result := True;
  11813. end;
  11814. end;
  11815. var
  11816. hp1, hp2 : tai;
  11817. SizeChange: Boolean;
  11818. PreMessage: string;
  11819. begin
  11820. Result := False;
  11821. if (taicpu(p).oper[0]^.typ = top_reg) and
  11822. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11823. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  11824. begin
  11825. { Change (using movzbl %al,%eax as an example):
  11826. movzbl %al, %eax movzbl %al, %eax
  11827. cmpl x, %eax testl %eax,%eax
  11828. To:
  11829. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  11830. movzbl %al, %eax movzbl %al, %eax
  11831. Smaller instruction and minimises pipeline stall as the CPU
  11832. doesn't have to wait for the register to get zero-extended. [Kit]
  11833. Also allow if the smaller of the two registers is being checked,
  11834. as this still removes the false dependency.
  11835. }
  11836. if
  11837. (
  11838. (
  11839. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  11840. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  11841. ) or (
  11842. { If MatchOperand returns True, they must both be registers }
  11843. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  11844. )
  11845. ) and
  11846. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  11847. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  11848. begin
  11849. 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);
  11850. asml.Remove(hp1);
  11851. asml.InsertBefore(hp1, p);
  11852. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  11853. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  11854. begin
  11855. taicpu(hp1).opcode := A_TEST;
  11856. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  11857. end;
  11858. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11859. case taicpu(p).opsize of
  11860. S_BW, S_BL:
  11861. begin
  11862. SizeChange := taicpu(hp1).opsize <> S_B;
  11863. taicpu(hp1).changeopsize(S_B);
  11864. end;
  11865. S_WL:
  11866. begin
  11867. SizeChange := taicpu(hp1).opsize <> S_W;
  11868. taicpu(hp1).changeopsize(S_W);
  11869. end
  11870. else
  11871. InternalError(2020112701);
  11872. end;
  11873. UpdateUsedRegs(tai(p.Next));
  11874. { Check if the register is used aferwards - if not, we can
  11875. remove the movzx instruction completely }
  11876. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  11877. begin
  11878. { Hp1 is a better position than p for debugging purposes }
  11879. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  11880. RemoveCurrentp(p, hp1);
  11881. Result := True;
  11882. end;
  11883. if SizeChange then
  11884. DebugMsg(SPeepholeOptimization + PreMessage +
  11885. 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)
  11886. else
  11887. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  11888. Exit;
  11889. end;
  11890. { Change (using movzwl %ax,%eax as an example):
  11891. movzwl %ax, %eax
  11892. movb %al, (dest) (Register is smaller than read register in movz)
  11893. To:
  11894. movb %al, (dest) (Move one back to avoid a false dependency)
  11895. movzwl %ax, %eax
  11896. }
  11897. if (taicpu(hp1).opcode = A_MOV) and
  11898. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11899. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  11900. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  11901. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  11902. begin
  11903. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  11904. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  11905. asml.Remove(hp1);
  11906. asml.InsertBefore(hp1, p);
  11907. if taicpu(hp1).oper[1]^.typ = top_reg then
  11908. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11909. { Check if the register is used aferwards - if not, we can
  11910. remove the movzx instruction completely }
  11911. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  11912. begin
  11913. { Hp1 is a better position than p for debugging purposes }
  11914. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  11915. RemoveCurrentp(p, hp1);
  11916. Result := True;
  11917. end;
  11918. Exit;
  11919. end;
  11920. end;
  11921. end;
  11922. {$ifdef x86_64}
  11923. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  11924. var
  11925. PreMessage, RegName: string;
  11926. begin
  11927. { Code size reduction by J. Gareth "Kit" Moreton }
  11928. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  11929. as this removes the REX prefix }
  11930. Result := False;
  11931. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  11932. Exit;
  11933. if taicpu(p).oper[0]^.typ <> top_reg then
  11934. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  11935. InternalError(2018011500);
  11936. case taicpu(p).opsize of
  11937. S_Q:
  11938. begin
  11939. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  11940. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  11941. { The actual optimization }
  11942. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11943. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11944. taicpu(p).changeopsize(S_L);
  11945. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  11946. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  11947. end;
  11948. else
  11949. ;
  11950. end;
  11951. end;
  11952. {$endif}
  11953. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  11954. var
  11955. XReg: TRegister;
  11956. begin
  11957. Result := False;
  11958. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  11959. Smaller encoding and slightly faster on some platforms (also works for
  11960. ZMM-sized registers) }
  11961. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  11962. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  11963. begin
  11964. XReg := taicpu(p).oper[0]^.reg;
  11965. if (taicpu(p).oper[1]^.reg = XReg) then
  11966. begin
  11967. taicpu(p).changeopsize(S_XMM);
  11968. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  11969. if (cs_opt_size in current_settings.optimizerswitches) then
  11970. begin
  11971. { Change input registers to %xmm0 to reduce size. Note that
  11972. there's a risk of a false dependency doing this, so only
  11973. optimise for size here }
  11974. XReg := NR_XMM0;
  11975. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  11976. end
  11977. else
  11978. begin
  11979. setsubreg(XReg, R_SUBMMX);
  11980. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  11981. end;
  11982. taicpu(p).oper[0]^.reg := XReg;
  11983. taicpu(p).oper[1]^.reg := XReg;
  11984. Result := True;
  11985. end;
  11986. end;
  11987. end;
  11988. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  11989. var
  11990. OperIdx: Integer;
  11991. begin
  11992. for OperIdx := 0 to p.ops - 1 do
  11993. if p.oper[OperIdx]^.typ = top_ref then
  11994. optimize_ref(p.oper[OperIdx]^.ref^, False);
  11995. end;
  11996. end.