aoptx86.pas 480 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192
  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. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  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. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  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. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  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 PrePeepholeOptSxx(var p : tai) : boolean;
  107. function PrePeepholeOptIMUL(var p : tai) : boolean;
  108. function PrePeepholeOptAND(var p : tai) : boolean;
  109. function OptPass1Test(var p: tai): boolean;
  110. function OptPass1Add(var p: tai): boolean;
  111. function OptPass1AND(var p : tai) : boolean;
  112. function OptPass1_V_MOVAP(var p : tai) : boolean;
  113. function OptPass1VOP(var p : tai) : boolean;
  114. function OptPass1MOV(var p : tai) : boolean;
  115. function OptPass1Movx(var p : tai) : boolean;
  116. function OptPass1MOVXX(var p : tai) : boolean;
  117. function OptPass1OP(var p : tai) : boolean;
  118. function OptPass1LEA(var p : tai) : boolean;
  119. function OptPass1Sub(var p : tai) : boolean;
  120. function OptPass1SHLSAL(var p : tai) : boolean;
  121. function OptPass1FSTP(var p : tai) : boolean;
  122. function OptPass1FLD(var p : tai) : boolean;
  123. function OptPass1Cmp(var p : tai) : boolean;
  124. function OptPass1PXor(var p : tai) : boolean;
  125. function OptPass1VPXor(var p: tai): boolean;
  126. function OptPass1Imul(var p : tai) : boolean;
  127. function OptPass1Jcc(var p : tai) : boolean;
  128. function OptPass1SHXX(var p: tai): boolean;
  129. function OptPass1VMOVDQ(var p: tai): Boolean;
  130. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  131. function OptPass2Movx(var p : tai): Boolean;
  132. function OptPass2MOV(var p : tai) : boolean;
  133. function OptPass2Imul(var p : tai) : boolean;
  134. function OptPass2Jmp(var p : tai) : boolean;
  135. function OptPass2Jcc(var p : tai) : boolean;
  136. function OptPass2Lea(var p: tai): Boolean;
  137. function OptPass2SUB(var p: tai): Boolean;
  138. function OptPass2ADD(var p : tai): Boolean;
  139. function OptPass2SETcc(var p : tai) : boolean;
  140. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  141. function PostPeepholeOptMov(var p : tai) : Boolean;
  142. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  143. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  144. function PostPeepholeOptXor(var p : tai) : Boolean;
  145. {$endif x86_64}
  146. function PostPeepholeOptAnd(var p : tai) : boolean;
  147. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  148. function PostPeepholeOptCmp(var p : tai) : Boolean;
  149. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  150. function PostPeepholeOptCall(var p : tai) : Boolean;
  151. function PostPeepholeOptLea(var p : tai) : Boolean;
  152. function PostPeepholeOptPush(var p: tai): Boolean;
  153. function PostPeepholeOptShr(var p : tai) : boolean;
  154. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  155. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  156. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  157. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  158. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  159. { Processor-dependent reference optimisation }
  160. class procedure OptimizeRefs(var p: taicpu); static;
  161. end;
  162. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  163. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  164. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  165. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  166. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  167. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  168. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  169. {$if max_operands>2}
  170. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  171. {$endif max_operands>2}
  172. function RefsEqual(const r1, r2: treference): boolean;
  173. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  174. { returns true, if ref is a reference using only the registers passed as base and index
  175. and having an offset }
  176. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  177. implementation
  178. uses
  179. cutils,verbose,
  180. systems,
  181. globals,
  182. cpuinfo,
  183. procinfo,
  184. paramgr,
  185. aasmbase,
  186. aoptbase,aoptutils,
  187. symconst,symsym,
  188. cgx86,
  189. itcpugas;
  190. {$ifdef DEBUG_AOPTCPU}
  191. const
  192. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  193. {$else DEBUG_AOPTCPU}
  194. { Empty strings help the optimizer to remove string concatenations that won't
  195. ever appear to the user on release builds. [Kit] }
  196. const
  197. SPeepholeOptimization = '';
  198. {$endif DEBUG_AOPTCPU}
  199. LIST_STEP_SIZE = 4;
  200. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  201. begin
  202. result :=
  203. (instr.typ = ait_instruction) and
  204. (taicpu(instr).opcode = op) and
  205. ((opsize = []) or (taicpu(instr).opsize in opsize));
  206. end;
  207. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  208. begin
  209. result :=
  210. (instr.typ = ait_instruction) and
  211. ((taicpu(instr).opcode = op1) or
  212. (taicpu(instr).opcode = op2)
  213. ) and
  214. ((opsize = []) or (taicpu(instr).opsize in opsize));
  215. end;
  216. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  217. begin
  218. result :=
  219. (instr.typ = ait_instruction) and
  220. ((taicpu(instr).opcode = op1) or
  221. (taicpu(instr).opcode = op2) or
  222. (taicpu(instr).opcode = op3)
  223. ) and
  224. ((opsize = []) or (taicpu(instr).opsize in opsize));
  225. end;
  226. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  227. const opsize : topsizes) : boolean;
  228. var
  229. op : TAsmOp;
  230. begin
  231. result:=false;
  232. if (instr.typ <> ait_instruction) or
  233. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  234. exit;
  235. for op in ops do
  236. begin
  237. if taicpu(instr).opcode = op then
  238. begin
  239. result:=true;
  240. exit;
  241. end;
  242. end;
  243. end;
  244. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  245. begin
  246. result := (oper.typ = top_reg) and (oper.reg = reg);
  247. end;
  248. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  249. begin
  250. result := (oper.typ = top_const) and (oper.val = a);
  251. end;
  252. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  253. begin
  254. result := oper1.typ = oper2.typ;
  255. if result then
  256. case oper1.typ of
  257. top_const:
  258. Result:=oper1.val = oper2.val;
  259. top_reg:
  260. Result:=oper1.reg = oper2.reg;
  261. top_ref:
  262. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  263. else
  264. internalerror(2013102801);
  265. end
  266. end;
  267. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  268. begin
  269. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  270. if result then
  271. case oper1.typ of
  272. top_const:
  273. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  274. top_reg:
  275. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  276. top_ref:
  277. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  278. else
  279. internalerror(2020052401);
  280. end
  281. end;
  282. function RefsEqual(const r1, r2: treference): boolean;
  283. begin
  284. RefsEqual :=
  285. (r1.offset = r2.offset) and
  286. (r1.segment = r2.segment) and (r1.base = r2.base) and
  287. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  288. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  289. (r1.relsymbol = r2.relsymbol) and
  290. (r1.volatility=[]) and
  291. (r2.volatility=[]);
  292. end;
  293. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  294. begin
  295. Result:=(ref.offset=0) and
  296. (ref.scalefactor in [0,1]) and
  297. (ref.segment=NR_NO) and
  298. (ref.symbol=nil) and
  299. (ref.relsymbol=nil) and
  300. ((base=NR_INVALID) or
  301. (ref.base=base)) and
  302. ((index=NR_INVALID) or
  303. (ref.index=index)) and
  304. (ref.volatility=[]);
  305. end;
  306. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  307. begin
  308. Result:=(ref.scalefactor in [0,1]) and
  309. (ref.segment=NR_NO) and
  310. (ref.symbol=nil) and
  311. (ref.relsymbol=nil) and
  312. ((base=NR_INVALID) or
  313. (ref.base=base)) and
  314. ((index=NR_INVALID) or
  315. (ref.index=index)) and
  316. (ref.volatility=[]);
  317. end;
  318. function InstrReadsFlags(p: tai): boolean;
  319. begin
  320. InstrReadsFlags := true;
  321. case p.typ of
  322. ait_instruction:
  323. if InsProp[taicpu(p).opcode].Ch*
  324. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  325. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  326. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  327. exit;
  328. ait_label:
  329. exit;
  330. else
  331. ;
  332. end;
  333. InstrReadsFlags := false;
  334. end;
  335. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  336. begin
  337. Next:=Current;
  338. repeat
  339. Result:=GetNextInstruction(Next,Next);
  340. until not (Result) or
  341. not(cs_opt_level3 in current_settings.optimizerswitches) or
  342. (Next.typ<>ait_instruction) or
  343. RegInInstruction(reg,Next) or
  344. is_calljmp(taicpu(Next).opcode);
  345. end;
  346. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  347. begin
  348. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  349. Next := Current;
  350. repeat
  351. Result := GetNextInstruction(Next,Next);
  352. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  353. if is_calljmpuncondret(taicpu(Next).opcode) then
  354. begin
  355. Result := False;
  356. Exit;
  357. end
  358. else
  359. CrossJump := True;
  360. until not Result or
  361. not (cs_opt_level3 in current_settings.optimizerswitches) or
  362. (Next.typ <> ait_instruction) or
  363. RegInInstruction(reg,Next);
  364. end;
  365. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  366. begin
  367. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  368. begin
  369. Result:=GetNextInstruction(Current,Next);
  370. exit;
  371. end;
  372. Next:=tai(Current.Next);
  373. Result:=false;
  374. while assigned(Next) do
  375. begin
  376. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  377. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  378. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  379. exit
  380. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  381. begin
  382. Result:=true;
  383. exit;
  384. end;
  385. Next:=tai(Next.Next);
  386. end;
  387. end;
  388. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  389. begin
  390. Result:=RegReadByInstruction(reg,hp);
  391. end;
  392. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  393. var
  394. p: taicpu;
  395. opcount: longint;
  396. begin
  397. RegReadByInstruction := false;
  398. if hp.typ <> ait_instruction then
  399. exit;
  400. p := taicpu(hp);
  401. case p.opcode of
  402. A_CALL:
  403. regreadbyinstruction := true;
  404. A_IMUL:
  405. case p.ops of
  406. 1:
  407. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  408. (
  409. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  410. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  411. );
  412. 2,3:
  413. regReadByInstruction :=
  414. reginop(reg,p.oper[0]^) or
  415. reginop(reg,p.oper[1]^);
  416. else
  417. InternalError(2019112801);
  418. end;
  419. A_MUL:
  420. begin
  421. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  422. (
  423. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  424. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  425. );
  426. end;
  427. A_IDIV,A_DIV:
  428. begin
  429. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  430. (
  431. (getregtype(reg)=R_INTREGISTER) and
  432. (
  433. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  434. )
  435. );
  436. end;
  437. else
  438. begin
  439. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  440. begin
  441. RegReadByInstruction := false;
  442. exit;
  443. end;
  444. for opcount := 0 to p.ops-1 do
  445. if (p.oper[opCount]^.typ = top_ref) and
  446. RegInRef(reg,p.oper[opcount]^.ref^) then
  447. begin
  448. RegReadByInstruction := true;
  449. exit
  450. end;
  451. { special handling for SSE MOVSD }
  452. if (p.opcode=A_MOVSD) and (p.ops>0) then
  453. begin
  454. if p.ops<>2 then
  455. internalerror(2017042702);
  456. regReadByInstruction := reginop(reg,p.oper[0]^) or
  457. (
  458. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  459. );
  460. exit;
  461. end;
  462. with insprop[p.opcode] do
  463. begin
  464. case getregtype(reg) of
  465. R_INTREGISTER:
  466. begin
  467. case getsupreg(reg) of
  468. RS_EAX:
  469. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  470. begin
  471. RegReadByInstruction := true;
  472. exit
  473. end;
  474. RS_ECX:
  475. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  476. begin
  477. RegReadByInstruction := true;
  478. exit
  479. end;
  480. RS_EDX:
  481. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  482. begin
  483. RegReadByInstruction := true;
  484. exit
  485. end;
  486. RS_EBX:
  487. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  488. begin
  489. RegReadByInstruction := true;
  490. exit
  491. end;
  492. RS_ESP:
  493. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  494. begin
  495. RegReadByInstruction := true;
  496. exit
  497. end;
  498. RS_EBP:
  499. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  500. begin
  501. RegReadByInstruction := true;
  502. exit
  503. end;
  504. RS_ESI:
  505. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  506. begin
  507. RegReadByInstruction := true;
  508. exit
  509. end;
  510. RS_EDI:
  511. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  512. begin
  513. RegReadByInstruction := true;
  514. exit
  515. end;
  516. end;
  517. end;
  518. R_MMREGISTER:
  519. begin
  520. case getsupreg(reg) of
  521. RS_XMM0:
  522. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  523. begin
  524. RegReadByInstruction := true;
  525. exit
  526. end;
  527. end;
  528. end;
  529. else
  530. ;
  531. end;
  532. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  533. begin
  534. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  535. begin
  536. case p.condition of
  537. C_A,C_NBE, { CF=0 and ZF=0 }
  538. C_BE,C_NA: { CF=1 or ZF=1 }
  539. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  540. C_AE,C_NB,C_NC, { CF=0 }
  541. C_B,C_NAE,C_C: { CF=1 }
  542. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  543. C_NE,C_NZ, { ZF=0 }
  544. C_E,C_Z: { ZF=1 }
  545. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  546. C_G,C_NLE, { ZF=0 and SF=OF }
  547. C_LE,C_NG: { ZF=1 or SF<>OF }
  548. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  549. C_GE,C_NL, { SF=OF }
  550. C_L,C_NGE: { SF<>OF }
  551. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  552. C_NO, { OF=0 }
  553. C_O: { OF=1 }
  554. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  555. C_NP,C_PO, { PF=0 }
  556. C_P,C_PE: { PF=1 }
  557. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  558. C_NS, { SF=0 }
  559. C_S: { SF=1 }
  560. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  561. else
  562. internalerror(2017042701);
  563. end;
  564. if RegReadByInstruction then
  565. exit;
  566. end;
  567. case getsubreg(reg) of
  568. R_SUBW,R_SUBD,R_SUBQ:
  569. RegReadByInstruction :=
  570. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  571. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  572. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  573. R_SUBFLAGCARRY:
  574. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  575. R_SUBFLAGPARITY:
  576. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  577. R_SUBFLAGAUXILIARY:
  578. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  579. R_SUBFLAGZERO:
  580. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  581. R_SUBFLAGSIGN:
  582. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  583. R_SUBFLAGOVERFLOW:
  584. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  585. R_SUBFLAGINTERRUPT:
  586. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  587. R_SUBFLAGDIRECTION:
  588. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  589. else
  590. internalerror(2017042601);
  591. end;
  592. exit;
  593. end;
  594. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  595. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  596. (p.oper[0]^.reg=p.oper[1]^.reg) then
  597. exit;
  598. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  599. begin
  600. RegReadByInstruction := true;
  601. exit
  602. end;
  603. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  604. begin
  605. RegReadByInstruction := true;
  606. exit
  607. end;
  608. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  609. begin
  610. RegReadByInstruction := true;
  611. exit
  612. end;
  613. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  614. begin
  615. RegReadByInstruction := true;
  616. exit
  617. end;
  618. end;
  619. end;
  620. end;
  621. end;
  622. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  623. begin
  624. result:=false;
  625. if p1.typ<>ait_instruction then
  626. exit;
  627. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  628. exit(true);
  629. if (getregtype(reg)=R_INTREGISTER) and
  630. { change information for xmm movsd are not correct }
  631. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  632. begin
  633. case getsupreg(reg) of
  634. { RS_EAX = RS_RAX on x86-64 }
  635. RS_EAX:
  636. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  637. RS_ECX:
  638. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  639. RS_EDX:
  640. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  641. RS_EBX:
  642. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  643. RS_ESP:
  644. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  645. RS_EBP:
  646. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  647. RS_ESI:
  648. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  649. RS_EDI:
  650. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  651. else
  652. ;
  653. end;
  654. if result then
  655. exit;
  656. end
  657. else if getregtype(reg)=R_MMREGISTER then
  658. begin
  659. case getsupreg(reg) of
  660. RS_XMM0:
  661. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  662. else
  663. ;
  664. end;
  665. if result then
  666. exit;
  667. end
  668. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  669. begin
  670. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  671. exit(true);
  672. case getsubreg(reg) of
  673. R_SUBFLAGCARRY:
  674. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  675. R_SUBFLAGPARITY:
  676. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  677. R_SUBFLAGAUXILIARY:
  678. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  679. R_SUBFLAGZERO:
  680. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  681. R_SUBFLAGSIGN:
  682. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  683. R_SUBFLAGOVERFLOW:
  684. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  685. R_SUBFLAGINTERRUPT:
  686. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  687. R_SUBFLAGDIRECTION:
  688. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  689. R_SUBW,R_SUBD,R_SUBQ:
  690. { Everything except the direction bits }
  691. Result:=
  692. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  693. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  694. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  695. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  696. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  697. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  698. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  699. else
  700. ;
  701. end;
  702. if result then
  703. exit;
  704. end
  705. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  706. exit(true);
  707. Result:=inherited RegInInstruction(Reg, p1);
  708. end;
  709. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  710. const
  711. WriteOps: array[0..3] of set of TInsChange =
  712. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  713. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  714. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  715. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  716. var
  717. OperIdx: Integer;
  718. begin
  719. Result := False;
  720. if p1.typ <> ait_instruction then
  721. exit;
  722. with insprop[taicpu(p1).opcode] do
  723. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  724. begin
  725. case getsubreg(reg) of
  726. R_SUBW,R_SUBD,R_SUBQ:
  727. Result :=
  728. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  729. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  730. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  731. R_SUBFLAGCARRY:
  732. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  733. R_SUBFLAGPARITY:
  734. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  735. R_SUBFLAGAUXILIARY:
  736. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  737. R_SUBFLAGZERO:
  738. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  739. R_SUBFLAGSIGN:
  740. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  741. R_SUBFLAGOVERFLOW:
  742. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  743. R_SUBFLAGINTERRUPT:
  744. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  745. R_SUBFLAGDIRECTION:
  746. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  747. else
  748. internalerror(2017042602);
  749. end;
  750. exit;
  751. end;
  752. case taicpu(p1).opcode of
  753. A_CALL:
  754. { We could potentially set Result to False if the register in
  755. question is non-volatile for the subroutine's calling convention,
  756. but this would require detecting the calling convention in use and
  757. also assuming that the routine doesn't contain malformed assembly
  758. language, for example... so it could only be done under -O4 as it
  759. would be considered a side-effect. [Kit] }
  760. Result := True;
  761. A_MOVSD:
  762. { special handling for SSE MOVSD }
  763. if (taicpu(p1).ops>0) then
  764. begin
  765. if taicpu(p1).ops<>2 then
  766. internalerror(2017042703);
  767. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  768. end;
  769. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  770. so fix it here (FK)
  771. }
  772. A_VMOVSS,
  773. A_VMOVSD:
  774. begin
  775. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  776. exit;
  777. end;
  778. A_IMUL:
  779. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  780. else
  781. ;
  782. end;
  783. if Result then
  784. exit;
  785. with insprop[taicpu(p1).opcode] do
  786. begin
  787. if getregtype(reg)=R_INTREGISTER then
  788. begin
  789. case getsupreg(reg) of
  790. RS_EAX:
  791. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  792. begin
  793. Result := True;
  794. exit
  795. end;
  796. RS_ECX:
  797. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  798. begin
  799. Result := True;
  800. exit
  801. end;
  802. RS_EDX:
  803. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  804. begin
  805. Result := True;
  806. exit
  807. end;
  808. RS_EBX:
  809. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  810. begin
  811. Result := True;
  812. exit
  813. end;
  814. RS_ESP:
  815. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  816. begin
  817. Result := True;
  818. exit
  819. end;
  820. RS_EBP:
  821. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  822. begin
  823. Result := True;
  824. exit
  825. end;
  826. RS_ESI:
  827. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  828. begin
  829. Result := True;
  830. exit
  831. end;
  832. RS_EDI:
  833. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  834. begin
  835. Result := True;
  836. exit
  837. end;
  838. end;
  839. end;
  840. for OperIdx := 0 to taicpu(p1).ops - 1 do
  841. if (WriteOps[OperIdx]*Ch<>[]) and
  842. { The register doesn't get modified inside a reference }
  843. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  844. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  845. begin
  846. Result := true;
  847. exit
  848. end;
  849. end;
  850. end;
  851. {$ifdef DEBUG_AOPTCPU}
  852. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  853. begin
  854. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  855. end;
  856. function debug_tostr(i: tcgint): string; inline;
  857. begin
  858. Result := tostr(i);
  859. end;
  860. function debug_regname(r: TRegister): string; inline;
  861. begin
  862. Result := '%' + std_regname(r);
  863. end;
  864. { Debug output function - creates a string representation of an operator }
  865. function debug_operstr(oper: TOper): string;
  866. begin
  867. case oper.typ of
  868. top_const:
  869. Result := '$' + debug_tostr(oper.val);
  870. top_reg:
  871. Result := debug_regname(oper.reg);
  872. top_ref:
  873. begin
  874. if oper.ref^.offset <> 0 then
  875. Result := debug_tostr(oper.ref^.offset) + '('
  876. else
  877. Result := '(';
  878. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  879. begin
  880. Result := Result + debug_regname(oper.ref^.base);
  881. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  882. Result := Result + ',' + debug_regname(oper.ref^.index);
  883. end
  884. else
  885. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  886. Result := Result + debug_regname(oper.ref^.index);
  887. if (oper.ref^.scalefactor > 1) then
  888. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  889. else
  890. Result := Result + ')';
  891. end;
  892. else
  893. Result := '[UNKNOWN]';
  894. end;
  895. end;
  896. function debug_op2str(opcode: tasmop): string; inline;
  897. begin
  898. Result := std_op2str[opcode];
  899. end;
  900. function debug_opsize2str(opsize: topsize): string; inline;
  901. begin
  902. Result := gas_opsize2str[opsize];
  903. end;
  904. {$else DEBUG_AOPTCPU}
  905. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  906. begin
  907. end;
  908. function debug_tostr(i: tcgint): string; inline;
  909. begin
  910. Result := '';
  911. end;
  912. function debug_regname(r: TRegister): string; inline;
  913. begin
  914. Result := '';
  915. end;
  916. function debug_operstr(oper: TOper): string; inline;
  917. begin
  918. Result := '';
  919. end;
  920. function debug_op2str(opcode: tasmop): string; inline;
  921. begin
  922. Result := '';
  923. end;
  924. function debug_opsize2str(opsize: topsize): string; inline;
  925. begin
  926. Result := '';
  927. end;
  928. {$endif DEBUG_AOPTCPU}
  929. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  930. begin
  931. {$ifdef x86_64}
  932. { Always fine on x86-64 }
  933. Result := True;
  934. {$else x86_64}
  935. Result :=
  936. {$ifdef i8086}
  937. (current_settings.cputype >= cpu_386) and
  938. {$endif i8086}
  939. (
  940. { Always accept if optimising for size }
  941. (cs_opt_size in current_settings.optimizerswitches) or
  942. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  943. (current_settings.optimizecputype >= cpu_Pentium2)
  944. );
  945. {$endif x86_64}
  946. end;
  947. { Attempts to allocate a volatile integer register for use between p and hp,
  948. using AUsedRegs for the current register usage information. Returns NR_NO
  949. if no free register could be found }
  950. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  951. var
  952. RegSet: TCPURegisterSet;
  953. CurrentSuperReg: Integer;
  954. CurrentReg: TRegister;
  955. Currentp: tai;
  956. Breakout: Boolean;
  957. begin
  958. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  959. Result := NR_NO;
  960. RegSet := paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption);
  961. for CurrentSuperReg in RegSet do
  962. begin
  963. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  964. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg) then
  965. begin
  966. Currentp := p;
  967. Breakout := False;
  968. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  969. begin
  970. case Currentp.typ of
  971. ait_instruction:
  972. begin
  973. if RegInInstruction(CurrentReg, Currentp) then
  974. begin
  975. Breakout := True;
  976. Break;
  977. end;
  978. { Cannot allocate across an unconditional jump }
  979. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  980. Exit;
  981. end;
  982. ait_marker:
  983. { Don't try anything more if a marker is hit }
  984. Exit;
  985. ait_regalloc:
  986. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  987. begin
  988. Breakout := True;
  989. Break;
  990. end;
  991. else
  992. ;
  993. end;
  994. end;
  995. if Breakout then
  996. { Try the next register }
  997. Continue;
  998. { We have a free register available }
  999. Result := CurrentReg;
  1000. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1001. Exit;
  1002. end;
  1003. end;
  1004. end;
  1005. { Attempts to allocate a volatile MM register for use between p and hp,
  1006. using AUsedRegs for the current register usage information. Returns NR_NO
  1007. if no free register could be found }
  1008. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1009. var
  1010. RegSet: TCPURegisterSet;
  1011. CurrentSuperReg: Integer;
  1012. CurrentReg: TRegister;
  1013. Currentp: tai;
  1014. Breakout: Boolean;
  1015. begin
  1016. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  1017. Result := NR_NO;
  1018. RegSet := paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption);
  1019. for CurrentSuperReg in RegSet do
  1020. begin
  1021. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1022. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1023. begin
  1024. Currentp := p;
  1025. Breakout := False;
  1026. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1027. begin
  1028. case Currentp.typ of
  1029. ait_instruction:
  1030. begin
  1031. if RegInInstruction(CurrentReg, Currentp) then
  1032. begin
  1033. Breakout := True;
  1034. Break;
  1035. end;
  1036. { Cannot allocate across an unconditional jump }
  1037. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1038. Exit;
  1039. end;
  1040. ait_marker:
  1041. { Don't try anything more if a marker is hit }
  1042. Exit;
  1043. ait_regalloc:
  1044. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1045. begin
  1046. Breakout := True;
  1047. Break;
  1048. end;
  1049. else
  1050. ;
  1051. end;
  1052. end;
  1053. if Breakout then
  1054. { Try the next register }
  1055. Continue;
  1056. { We have a free register available }
  1057. Result := CurrentReg;
  1058. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1059. Exit;
  1060. end;
  1061. end;
  1062. end;
  1063. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1064. begin
  1065. if not SuperRegistersEqual(reg1,reg2) then
  1066. exit(false);
  1067. if getregtype(reg1)<>R_INTREGISTER then
  1068. exit(true); {because SuperRegisterEqual is true}
  1069. case getsubreg(reg1) of
  1070. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1071. higher, it preserves the high bits, so the new value depends on
  1072. reg2's previous value. In other words, it is equivalent to doing:
  1073. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1074. R_SUBL:
  1075. exit(getsubreg(reg2)=R_SUBL);
  1076. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1077. higher, it actually does a:
  1078. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1079. R_SUBH:
  1080. exit(getsubreg(reg2)=R_SUBH);
  1081. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1082. bits of reg2:
  1083. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1084. R_SUBW:
  1085. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1086. { a write to R_SUBD always overwrites every other subregister,
  1087. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1088. R_SUBD,
  1089. R_SUBQ:
  1090. exit(true);
  1091. else
  1092. internalerror(2017042801);
  1093. end;
  1094. end;
  1095. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1096. begin
  1097. if not SuperRegistersEqual(reg1,reg2) then
  1098. exit(false);
  1099. if getregtype(reg1)<>R_INTREGISTER then
  1100. exit(true); {because SuperRegisterEqual is true}
  1101. case getsubreg(reg1) of
  1102. R_SUBL:
  1103. exit(getsubreg(reg2)<>R_SUBH);
  1104. R_SUBH:
  1105. exit(getsubreg(reg2)<>R_SUBL);
  1106. R_SUBW,
  1107. R_SUBD,
  1108. R_SUBQ:
  1109. exit(true);
  1110. else
  1111. internalerror(2017042802);
  1112. end;
  1113. end;
  1114. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1115. var
  1116. hp1 : tai;
  1117. l : TCGInt;
  1118. begin
  1119. result:=false;
  1120. { changes the code sequence
  1121. shr/sar const1, x
  1122. shl const2, x
  1123. to
  1124. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1125. if GetNextInstruction(p, hp1) and
  1126. MatchInstruction(hp1,A_SHL,[]) and
  1127. (taicpu(p).oper[0]^.typ = top_const) and
  1128. (taicpu(hp1).oper[0]^.typ = top_const) and
  1129. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1130. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1131. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1132. begin
  1133. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1134. not(cs_opt_size in current_settings.optimizerswitches) then
  1135. begin
  1136. { shr/sar const1, %reg
  1137. shl const2, %reg
  1138. with const1 > const2 }
  1139. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1140. taicpu(hp1).opcode := A_AND;
  1141. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1142. case taicpu(p).opsize Of
  1143. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1144. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1145. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1146. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1147. else
  1148. Internalerror(2017050703)
  1149. end;
  1150. end
  1151. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1152. not(cs_opt_size in current_settings.optimizerswitches) then
  1153. begin
  1154. { shr/sar const1, %reg
  1155. shl const2, %reg
  1156. with const1 < const2 }
  1157. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1158. taicpu(p).opcode := A_AND;
  1159. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1160. case taicpu(p).opsize Of
  1161. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1162. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1163. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1164. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1165. else
  1166. Internalerror(2017050702)
  1167. end;
  1168. end
  1169. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1170. begin
  1171. { shr/sar const1, %reg
  1172. shl const2, %reg
  1173. with const1 = const2 }
  1174. taicpu(p).opcode := A_AND;
  1175. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1176. case taicpu(p).opsize Of
  1177. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1178. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1179. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1180. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1181. else
  1182. Internalerror(2017050701)
  1183. end;
  1184. RemoveInstruction(hp1);
  1185. end;
  1186. end;
  1187. end;
  1188. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1189. var
  1190. opsize : topsize;
  1191. hp1 : tai;
  1192. tmpref : treference;
  1193. ShiftValue : Cardinal;
  1194. BaseValue : TCGInt;
  1195. begin
  1196. result:=false;
  1197. opsize:=taicpu(p).opsize;
  1198. { changes certain "imul const, %reg"'s to lea sequences }
  1199. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1200. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1201. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1202. if (taicpu(p).oper[0]^.val = 1) then
  1203. if (taicpu(p).ops = 2) then
  1204. { remove "imul $1, reg" }
  1205. begin
  1206. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1207. Result := RemoveCurrentP(p);
  1208. end
  1209. else
  1210. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1211. begin
  1212. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1213. InsertLLItem(p.previous, p.next, hp1);
  1214. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1215. p.free;
  1216. p := hp1;
  1217. end
  1218. else if ((taicpu(p).ops <= 2) or
  1219. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1220. not(cs_opt_size in current_settings.optimizerswitches) and
  1221. (not(GetNextInstruction(p, hp1)) or
  1222. not((tai(hp1).typ = ait_instruction) and
  1223. ((taicpu(hp1).opcode=A_Jcc) and
  1224. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1225. begin
  1226. {
  1227. imul X, reg1, reg2 to
  1228. lea (reg1,reg1,Y), reg2
  1229. shl ZZ,reg2
  1230. imul XX, reg1 to
  1231. lea (reg1,reg1,YY), reg1
  1232. shl ZZ,reg2
  1233. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1234. it does not exist as a separate optimization target in FPC though.
  1235. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1236. at most two zeros
  1237. }
  1238. reference_reset(tmpref,1,[]);
  1239. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1240. begin
  1241. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1242. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1243. TmpRef.base := taicpu(p).oper[1]^.reg;
  1244. TmpRef.index := taicpu(p).oper[1]^.reg;
  1245. if not(BaseValue in [3,5,9]) then
  1246. Internalerror(2018110101);
  1247. TmpRef.ScaleFactor := BaseValue-1;
  1248. if (taicpu(p).ops = 2) then
  1249. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1250. else
  1251. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1252. AsmL.InsertAfter(hp1,p);
  1253. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1254. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1255. RemoveCurrentP(p, hp1);
  1256. if ShiftValue>0 then
  1257. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1258. end;
  1259. end;
  1260. end;
  1261. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1262. begin
  1263. Result := False;
  1264. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1265. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1266. begin
  1267. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1268. taicpu(p).opcode := A_MOV;
  1269. Result := True;
  1270. end;
  1271. end;
  1272. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1273. var
  1274. p: taicpu absolute hp;
  1275. i: Integer;
  1276. begin
  1277. Result := False;
  1278. if not assigned(hp) or
  1279. (hp.typ <> ait_instruction) then
  1280. Exit;
  1281. // p := taicpu(hp);
  1282. Prefetch(insprop[p.opcode]);
  1283. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1284. with insprop[p.opcode] do
  1285. begin
  1286. case getsubreg(reg) of
  1287. R_SUBW,R_SUBD,R_SUBQ:
  1288. Result:=
  1289. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1290. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1291. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1292. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1293. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1294. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1295. R_SUBFLAGCARRY:
  1296. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1297. R_SUBFLAGPARITY:
  1298. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1299. R_SUBFLAGAUXILIARY:
  1300. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1301. R_SUBFLAGZERO:
  1302. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1303. R_SUBFLAGSIGN:
  1304. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1305. R_SUBFLAGOVERFLOW:
  1306. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1307. R_SUBFLAGINTERRUPT:
  1308. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1309. R_SUBFLAGDIRECTION:
  1310. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1311. else
  1312. begin
  1313. writeln(getsubreg(reg));
  1314. internalerror(2017050501);
  1315. end;
  1316. end;
  1317. exit;
  1318. end;
  1319. { Handle special cases first }
  1320. case p.opcode of
  1321. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1322. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1323. begin
  1324. Result :=
  1325. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1326. (p.oper[1]^.typ = top_reg) and
  1327. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1328. (
  1329. (p.oper[0]^.typ = top_const) or
  1330. (
  1331. (p.oper[0]^.typ = top_reg) and
  1332. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1333. ) or (
  1334. (p.oper[0]^.typ = top_ref) and
  1335. not RegInRef(reg,p.oper[0]^.ref^)
  1336. )
  1337. );
  1338. end;
  1339. A_MUL, A_IMUL:
  1340. Result :=
  1341. (
  1342. (p.ops=3) and { IMUL only }
  1343. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1344. (
  1345. (
  1346. (p.oper[1]^.typ=top_reg) and
  1347. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1348. ) or (
  1349. (p.oper[1]^.typ=top_ref) and
  1350. not RegInRef(reg,p.oper[1]^.ref^)
  1351. )
  1352. )
  1353. ) or (
  1354. (
  1355. (p.ops=1) and
  1356. (
  1357. (
  1358. (
  1359. (p.oper[0]^.typ=top_reg) and
  1360. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1361. )
  1362. ) or (
  1363. (p.oper[0]^.typ=top_ref) and
  1364. not RegInRef(reg,p.oper[0]^.ref^)
  1365. )
  1366. ) and (
  1367. (
  1368. (p.opsize=S_B) and
  1369. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1370. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1371. ) or (
  1372. (p.opsize=S_W) and
  1373. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1374. ) or (
  1375. (p.opsize=S_L) and
  1376. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1377. {$ifdef x86_64}
  1378. ) or (
  1379. (p.opsize=S_Q) and
  1380. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1381. {$endif x86_64}
  1382. )
  1383. )
  1384. )
  1385. );
  1386. A_CBW:
  1387. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1388. {$ifndef x86_64}
  1389. A_LDS:
  1390. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1391. A_LES:
  1392. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1393. {$endif not x86_64}
  1394. A_LFS:
  1395. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1396. A_LGS:
  1397. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1398. A_LSS:
  1399. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1400. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1401. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1402. A_LODSB:
  1403. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1404. A_LODSW:
  1405. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1406. {$ifdef x86_64}
  1407. A_LODSQ:
  1408. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1409. {$endif x86_64}
  1410. A_LODSD:
  1411. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1412. A_FSTSW, A_FNSTSW:
  1413. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1414. else
  1415. begin
  1416. with insprop[p.opcode] do
  1417. begin
  1418. if (
  1419. { xor %reg,%reg etc. is classed as a new value }
  1420. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1421. MatchOpType(p, top_reg, top_reg) and
  1422. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1423. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1424. ) then
  1425. begin
  1426. Result := True;
  1427. Exit;
  1428. end;
  1429. { Make sure the entire register is overwritten }
  1430. if (getregtype(reg) = R_INTREGISTER) then
  1431. begin
  1432. if (p.ops > 0) then
  1433. begin
  1434. if RegInOp(reg, p.oper[0]^) then
  1435. begin
  1436. if (p.oper[0]^.typ = top_ref) then
  1437. begin
  1438. if RegInRef(reg, p.oper[0]^.ref^) then
  1439. begin
  1440. Result := False;
  1441. Exit;
  1442. end;
  1443. end
  1444. else if (p.oper[0]^.typ = top_reg) then
  1445. begin
  1446. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1447. begin
  1448. Result := False;
  1449. Exit;
  1450. end
  1451. else if ([Ch_WOp1]*Ch<>[]) then
  1452. begin
  1453. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1454. Result := True
  1455. else
  1456. begin
  1457. Result := False;
  1458. Exit;
  1459. end;
  1460. end;
  1461. end;
  1462. end;
  1463. if (p.ops > 1) then
  1464. begin
  1465. if RegInOp(reg, p.oper[1]^) then
  1466. begin
  1467. if (p.oper[1]^.typ = top_ref) then
  1468. begin
  1469. if RegInRef(reg, p.oper[1]^.ref^) then
  1470. begin
  1471. Result := False;
  1472. Exit;
  1473. end;
  1474. end
  1475. else if (p.oper[1]^.typ = top_reg) then
  1476. begin
  1477. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1478. begin
  1479. Result := False;
  1480. Exit;
  1481. end
  1482. else if ([Ch_WOp2]*Ch<>[]) then
  1483. begin
  1484. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1485. Result := True
  1486. else
  1487. begin
  1488. Result := False;
  1489. Exit;
  1490. end;
  1491. end;
  1492. end;
  1493. end;
  1494. if (p.ops > 2) then
  1495. begin
  1496. if RegInOp(reg, p.oper[2]^) then
  1497. begin
  1498. if (p.oper[2]^.typ = top_ref) then
  1499. begin
  1500. if RegInRef(reg, p.oper[2]^.ref^) then
  1501. begin
  1502. Result := False;
  1503. Exit;
  1504. end;
  1505. end
  1506. else if (p.oper[2]^.typ = top_reg) then
  1507. begin
  1508. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1509. begin
  1510. Result := False;
  1511. Exit;
  1512. end
  1513. else if ([Ch_WOp3]*Ch<>[]) then
  1514. begin
  1515. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1516. Result := True
  1517. else
  1518. begin
  1519. Result := False;
  1520. Exit;
  1521. end;
  1522. end;
  1523. end;
  1524. end;
  1525. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1526. begin
  1527. if (p.oper[3]^.typ = top_ref) then
  1528. begin
  1529. if RegInRef(reg, p.oper[3]^.ref^) then
  1530. begin
  1531. Result := False;
  1532. Exit;
  1533. end;
  1534. end
  1535. else if (p.oper[3]^.typ = top_reg) then
  1536. begin
  1537. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1538. begin
  1539. Result := False;
  1540. Exit;
  1541. end
  1542. else if ([Ch_WOp4]*Ch<>[]) then
  1543. begin
  1544. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1545. Result := True
  1546. else
  1547. begin
  1548. Result := False;
  1549. Exit;
  1550. end;
  1551. end;
  1552. end;
  1553. end;
  1554. end;
  1555. end;
  1556. end;
  1557. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1558. case getsupreg(reg) of
  1559. RS_EAX:
  1560. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1561. begin
  1562. Result := True;
  1563. Exit;
  1564. end;
  1565. RS_ECX:
  1566. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1567. begin
  1568. Result := True;
  1569. Exit;
  1570. end;
  1571. RS_EDX:
  1572. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1573. begin
  1574. Result := True;
  1575. Exit;
  1576. end;
  1577. RS_EBX:
  1578. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1579. begin
  1580. Result := True;
  1581. Exit;
  1582. end;
  1583. RS_ESP:
  1584. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1585. begin
  1586. Result := True;
  1587. Exit;
  1588. end;
  1589. RS_EBP:
  1590. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1591. begin
  1592. Result := True;
  1593. Exit;
  1594. end;
  1595. RS_ESI:
  1596. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1597. begin
  1598. Result := True;
  1599. Exit;
  1600. end;
  1601. RS_EDI:
  1602. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1603. begin
  1604. Result := True;
  1605. Exit;
  1606. end;
  1607. else
  1608. ;
  1609. end;
  1610. end;
  1611. end;
  1612. end;
  1613. end;
  1614. end;
  1615. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1616. var
  1617. hp2,hp3 : tai;
  1618. begin
  1619. { some x86-64 issue a NOP before the real exit code }
  1620. if MatchInstruction(p,A_NOP,[]) then
  1621. GetNextInstruction(p,p);
  1622. result:=assigned(p) and (p.typ=ait_instruction) and
  1623. ((taicpu(p).opcode = A_RET) or
  1624. ((taicpu(p).opcode=A_LEAVE) and
  1625. GetNextInstruction(p,hp2) and
  1626. MatchInstruction(hp2,A_RET,[S_NO])
  1627. ) or
  1628. (((taicpu(p).opcode=A_LEA) and
  1629. MatchOpType(taicpu(p),top_ref,top_reg) and
  1630. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1631. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1632. ) and
  1633. GetNextInstruction(p,hp2) and
  1634. MatchInstruction(hp2,A_RET,[S_NO])
  1635. ) or
  1636. ((((taicpu(p).opcode=A_MOV) and
  1637. MatchOpType(taicpu(p),top_reg,top_reg) and
  1638. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1639. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1640. ((taicpu(p).opcode=A_LEA) and
  1641. MatchOpType(taicpu(p),top_ref,top_reg) and
  1642. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1643. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1644. )
  1645. ) and
  1646. GetNextInstruction(p,hp2) and
  1647. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1648. MatchOpType(taicpu(hp2),top_reg) and
  1649. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1650. GetNextInstruction(hp2,hp3) and
  1651. MatchInstruction(hp3,A_RET,[S_NO])
  1652. )
  1653. );
  1654. end;
  1655. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1656. begin
  1657. isFoldableArithOp := False;
  1658. case hp1.opcode of
  1659. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1660. isFoldableArithOp :=
  1661. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1662. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1663. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1664. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1665. (taicpu(hp1).oper[1]^.reg = reg);
  1666. A_INC,A_DEC,A_NEG,A_NOT:
  1667. isFoldableArithOp :=
  1668. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1669. (taicpu(hp1).oper[0]^.reg = reg);
  1670. else
  1671. ;
  1672. end;
  1673. end;
  1674. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1675. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1676. var
  1677. hp2: tai;
  1678. begin
  1679. hp2 := p;
  1680. repeat
  1681. hp2 := tai(hp2.previous);
  1682. if assigned(hp2) and
  1683. (hp2.typ = ait_regalloc) and
  1684. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1685. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1686. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1687. begin
  1688. RemoveInstruction(hp2);
  1689. break;
  1690. end;
  1691. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1692. end;
  1693. begin
  1694. case current_procinfo.procdef.returndef.typ of
  1695. arraydef,recorddef,pointerdef,
  1696. stringdef,enumdef,procdef,objectdef,errordef,
  1697. filedef,setdef,procvardef,
  1698. classrefdef,forwarddef:
  1699. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1700. orddef:
  1701. if current_procinfo.procdef.returndef.size <> 0 then
  1702. begin
  1703. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1704. { for int64/qword }
  1705. if current_procinfo.procdef.returndef.size = 8 then
  1706. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1707. end;
  1708. else
  1709. ;
  1710. end;
  1711. end;
  1712. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1713. var
  1714. hp1,hp2 : tai;
  1715. begin
  1716. result:=false;
  1717. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1718. begin
  1719. { vmova* reg1,reg1
  1720. =>
  1721. <nop> }
  1722. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1723. begin
  1724. RemoveCurrentP(p);
  1725. result:=true;
  1726. exit;
  1727. end
  1728. else if GetNextInstruction(p,hp1) then
  1729. begin
  1730. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1731. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1732. begin
  1733. { vmova* reg1,reg2
  1734. vmova* reg2,reg3
  1735. dealloc reg2
  1736. =>
  1737. vmova* reg1,reg3 }
  1738. TransferUsedRegs(TmpUsedRegs);
  1739. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1740. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1741. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1742. begin
  1743. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1744. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1745. RemoveInstruction(hp1);
  1746. result:=true;
  1747. exit;
  1748. end
  1749. { special case:
  1750. vmova* reg1,<op>
  1751. vmova* <op>,reg1
  1752. =>
  1753. vmova* reg1,<op> }
  1754. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1755. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1756. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1757. ) then
  1758. begin
  1759. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1760. RemoveInstruction(hp1);
  1761. result:=true;
  1762. exit;
  1763. end
  1764. end
  1765. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1766. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1767. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1768. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1769. ) and
  1770. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1771. begin
  1772. { vmova* reg1,reg2
  1773. vmovs* reg2,<op>
  1774. dealloc reg2
  1775. =>
  1776. vmovs* reg1,reg3 }
  1777. TransferUsedRegs(TmpUsedRegs);
  1778. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1779. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1780. begin
  1781. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1782. taicpu(p).opcode:=taicpu(hp1).opcode;
  1783. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1784. RemoveInstruction(hp1);
  1785. result:=true;
  1786. exit;
  1787. end
  1788. end;
  1789. end;
  1790. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1791. begin
  1792. if MatchInstruction(hp1,[A_VFMADDPD,
  1793. A_VFMADD132PD,
  1794. A_VFMADD132PS,
  1795. A_VFMADD132SD,
  1796. A_VFMADD132SS,
  1797. A_VFMADD213PD,
  1798. A_VFMADD213PS,
  1799. A_VFMADD213SD,
  1800. A_VFMADD213SS,
  1801. A_VFMADD231PD,
  1802. A_VFMADD231PS,
  1803. A_VFMADD231SD,
  1804. A_VFMADD231SS,
  1805. A_VFMADDSUB132PD,
  1806. A_VFMADDSUB132PS,
  1807. A_VFMADDSUB213PD,
  1808. A_VFMADDSUB213PS,
  1809. A_VFMADDSUB231PD,
  1810. A_VFMADDSUB231PS,
  1811. A_VFMSUB132PD,
  1812. A_VFMSUB132PS,
  1813. A_VFMSUB132SD,
  1814. A_VFMSUB132SS,
  1815. A_VFMSUB213PD,
  1816. A_VFMSUB213PS,
  1817. A_VFMSUB213SD,
  1818. A_VFMSUB213SS,
  1819. A_VFMSUB231PD,
  1820. A_VFMSUB231PS,
  1821. A_VFMSUB231SD,
  1822. A_VFMSUB231SS,
  1823. A_VFMSUBADD132PD,
  1824. A_VFMSUBADD132PS,
  1825. A_VFMSUBADD213PD,
  1826. A_VFMSUBADD213PS,
  1827. A_VFMSUBADD231PD,
  1828. A_VFMSUBADD231PS,
  1829. A_VFNMADD132PD,
  1830. A_VFNMADD132PS,
  1831. A_VFNMADD132SD,
  1832. A_VFNMADD132SS,
  1833. A_VFNMADD213PD,
  1834. A_VFNMADD213PS,
  1835. A_VFNMADD213SD,
  1836. A_VFNMADD213SS,
  1837. A_VFNMADD231PD,
  1838. A_VFNMADD231PS,
  1839. A_VFNMADD231SD,
  1840. A_VFNMADD231SS,
  1841. A_VFNMSUB132PD,
  1842. A_VFNMSUB132PS,
  1843. A_VFNMSUB132SD,
  1844. A_VFNMSUB132SS,
  1845. A_VFNMSUB213PD,
  1846. A_VFNMSUB213PS,
  1847. A_VFNMSUB213SD,
  1848. A_VFNMSUB213SS,
  1849. A_VFNMSUB231PD,
  1850. A_VFNMSUB231PS,
  1851. A_VFNMSUB231SD,
  1852. A_VFNMSUB231SS],[S_NO]) and
  1853. { we mix single and double opperations here because we assume that the compiler
  1854. generates vmovapd only after double operations and vmovaps only after single operations }
  1855. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1856. GetNextInstruction(hp1,hp2) and
  1857. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1858. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1859. begin
  1860. TransferUsedRegs(TmpUsedRegs);
  1861. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1862. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1863. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1864. begin
  1865. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1866. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1867. RemoveInstruction(hp2);
  1868. end;
  1869. end
  1870. else if (hp1.typ = ait_instruction) and
  1871. GetNextInstruction(hp1, hp2) and
  1872. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1873. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1874. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1875. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1876. (((taicpu(p).opcode=A_MOVAPS) and
  1877. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1878. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1879. ((taicpu(p).opcode=A_MOVAPD) and
  1880. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1881. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1882. ) then
  1883. { change
  1884. movapX reg,reg2
  1885. addsX/subsX/... reg3, reg2
  1886. movapX reg2,reg
  1887. to
  1888. addsX/subsX/... reg3,reg
  1889. }
  1890. begin
  1891. TransferUsedRegs(TmpUsedRegs);
  1892. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1893. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1894. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1895. begin
  1896. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1897. debug_op2str(taicpu(p).opcode)+' '+
  1898. debug_op2str(taicpu(hp1).opcode)+' '+
  1899. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1900. { we cannot eliminate the first move if
  1901. the operations uses the same register for source and dest }
  1902. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1903. RemoveCurrentP(p, nil);
  1904. p:=hp1;
  1905. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1906. RemoveInstruction(hp2);
  1907. result:=true;
  1908. end;
  1909. end;
  1910. end;
  1911. end;
  1912. end;
  1913. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1914. var
  1915. hp1 : tai;
  1916. begin
  1917. result:=false;
  1918. { replace
  1919. V<Op>X %mreg1,%mreg2,%mreg3
  1920. VMovX %mreg3,%mreg4
  1921. dealloc %mreg3
  1922. by
  1923. V<Op>X %mreg1,%mreg2,%mreg4
  1924. ?
  1925. }
  1926. if GetNextInstruction(p,hp1) and
  1927. { we mix single and double operations here because we assume that the compiler
  1928. generates vmovapd only after double operations and vmovaps only after single operations }
  1929. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1930. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1931. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1932. begin
  1933. TransferUsedRegs(TmpUsedRegs);
  1934. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1935. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1936. begin
  1937. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1938. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1939. RemoveInstruction(hp1);
  1940. result:=true;
  1941. end;
  1942. end;
  1943. end;
  1944. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1945. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1946. begin
  1947. Result := False;
  1948. { For safety reasons, only check for exact register matches }
  1949. { Check base register }
  1950. if (ref.base = AOldReg) then
  1951. begin
  1952. ref.base := ANewReg;
  1953. Result := True;
  1954. end;
  1955. { Check index register }
  1956. if (ref.index = AOldReg) then
  1957. begin
  1958. ref.index := ANewReg;
  1959. Result := True;
  1960. end;
  1961. end;
  1962. { Replaces all references to AOldReg in an operand to ANewReg }
  1963. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1964. var
  1965. OldSupReg, NewSupReg: TSuperRegister;
  1966. OldSubReg, NewSubReg: TSubRegister;
  1967. OldRegType: TRegisterType;
  1968. ThisOper: POper;
  1969. begin
  1970. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1971. Result := False;
  1972. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1973. InternalError(2020011801);
  1974. OldSupReg := getsupreg(AOldReg);
  1975. OldSubReg := getsubreg(AOldReg);
  1976. OldRegType := getregtype(AOldReg);
  1977. NewSupReg := getsupreg(ANewReg);
  1978. NewSubReg := getsubreg(ANewReg);
  1979. if OldRegType <> getregtype(ANewReg) then
  1980. InternalError(2020011802);
  1981. if OldSubReg <> NewSubReg then
  1982. InternalError(2020011803);
  1983. case ThisOper^.typ of
  1984. top_reg:
  1985. if (
  1986. (ThisOper^.reg = AOldReg) or
  1987. (
  1988. (OldRegType = R_INTREGISTER) and
  1989. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1990. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1991. (
  1992. (getsubreg(ThisOper^.reg) <= OldSubReg)
  1993. {$ifndef x86_64}
  1994. and (
  1995. { Under i386 and i8086, ESI, EDI, EBP and ESP
  1996. don't have an 8-bit representation }
  1997. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  1998. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  1999. )
  2000. {$endif x86_64}
  2001. )
  2002. )
  2003. ) then
  2004. begin
  2005. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2006. Result := True;
  2007. end;
  2008. top_ref:
  2009. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2010. Result := True;
  2011. else
  2012. ;
  2013. end;
  2014. end;
  2015. { Replaces all references to AOldReg in an instruction to ANewReg }
  2016. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2017. const
  2018. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2019. var
  2020. OperIdx: Integer;
  2021. begin
  2022. Result := False;
  2023. for OperIdx := 0 to p.ops - 1 do
  2024. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2025. begin
  2026. { The shift and rotate instructions can only use CL }
  2027. if not (
  2028. (OperIdx = 0) and
  2029. { This second condition just helps to avoid unnecessarily
  2030. calling MatchInstruction for 10 different opcodes }
  2031. (p.oper[0]^.reg = NR_CL) and
  2032. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2033. ) then
  2034. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2035. end
  2036. else if p.oper[OperIdx]^.typ = top_ref then
  2037. { It's okay to replace registers in references that get written to }
  2038. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2039. end;
  2040. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2041. begin
  2042. with ref^ do
  2043. Result :=
  2044. (index = NR_NO) and
  2045. (
  2046. {$ifdef x86_64}
  2047. (
  2048. (base = NR_RIP) and
  2049. (refaddr in [addr_pic, addr_pic_no_got])
  2050. ) or
  2051. {$endif x86_64}
  2052. (base = NR_STACK_POINTER_REG) or
  2053. (base = current_procinfo.framepointer)
  2054. );
  2055. end;
  2056. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2057. var
  2058. l: asizeint;
  2059. begin
  2060. Result := False;
  2061. { Should have been checked previously }
  2062. if p.opcode <> A_LEA then
  2063. InternalError(2020072501);
  2064. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2065. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2066. not(cs_opt_size in current_settings.optimizerswitches) then
  2067. exit;
  2068. with p.oper[0]^.ref^ do
  2069. begin
  2070. if (base <> p.oper[1]^.reg) or
  2071. (index <> NR_NO) or
  2072. assigned(symbol) then
  2073. exit;
  2074. l:=offset;
  2075. if (l=1) and UseIncDec then
  2076. begin
  2077. p.opcode:=A_INC;
  2078. p.loadreg(0,p.oper[1]^.reg);
  2079. p.ops:=1;
  2080. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2081. end
  2082. else if (l=-1) and UseIncDec then
  2083. begin
  2084. p.opcode:=A_DEC;
  2085. p.loadreg(0,p.oper[1]^.reg);
  2086. p.ops:=1;
  2087. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2088. end
  2089. else
  2090. begin
  2091. if (l<0) and (l<>-2147483648) then
  2092. begin
  2093. p.opcode:=A_SUB;
  2094. p.loadConst(0,-l);
  2095. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2096. end
  2097. else
  2098. begin
  2099. p.opcode:=A_ADD;
  2100. p.loadConst(0,l);
  2101. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2102. end;
  2103. end;
  2104. end;
  2105. Result := True;
  2106. end;
  2107. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2108. var
  2109. CurrentReg, ReplaceReg: TRegister;
  2110. begin
  2111. Result := False;
  2112. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2113. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2114. case hp.opcode of
  2115. A_FSTSW, A_FNSTSW,
  2116. A_IN, A_INS, A_OUT, A_OUTS,
  2117. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2118. { These routines have explicit operands, but they are restricted in
  2119. what they can be (e.g. IN and OUT can only read from AL, AX or
  2120. EAX. }
  2121. Exit;
  2122. A_IMUL:
  2123. begin
  2124. { The 1-operand version writes to implicit registers
  2125. The 2-operand version reads from the first operator, and reads
  2126. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2127. the 3-operand version reads from a register that it doesn't write to
  2128. }
  2129. case hp.ops of
  2130. 1:
  2131. if (
  2132. (
  2133. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2134. ) or
  2135. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2136. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2137. begin
  2138. Result := True;
  2139. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2140. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2141. end;
  2142. 2:
  2143. { Only modify the first parameter }
  2144. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2145. begin
  2146. Result := True;
  2147. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2148. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2149. end;
  2150. 3:
  2151. { Only modify the second parameter }
  2152. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2153. begin
  2154. Result := True;
  2155. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2156. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2157. end;
  2158. else
  2159. InternalError(2020012901);
  2160. end;
  2161. end;
  2162. else
  2163. if (hp.ops > 0) and
  2164. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2165. begin
  2166. Result := True;
  2167. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2168. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2169. end;
  2170. end;
  2171. end;
  2172. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2173. var
  2174. hp1, hp2, hp3: tai;
  2175. DoOptimisation, TempBool: Boolean;
  2176. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2177. begin
  2178. if taicpu(hp1).opcode = signed_movop then
  2179. begin
  2180. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2181. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2182. end
  2183. else
  2184. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2185. end;
  2186. var
  2187. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2188. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2189. NewSize: topsize;
  2190. CurrentReg, ActiveReg: TRegister;
  2191. SourceRef, TargetRef: TReference;
  2192. MovAligned, MovUnaligned: TAsmOp;
  2193. begin
  2194. Result:=false;
  2195. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2196. { remove mov reg1,reg1? }
  2197. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2198. then
  2199. begin
  2200. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2201. { take care of the register (de)allocs following p }
  2202. RemoveCurrentP(p, hp1);
  2203. Result:=true;
  2204. exit;
  2205. end;
  2206. { All the next optimisations require a next instruction }
  2207. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2208. Exit;
  2209. { Look for:
  2210. mov %reg1,%reg2
  2211. ??? %reg2,r/m
  2212. Change to:
  2213. mov %reg1,%reg2
  2214. ??? %reg1,r/m
  2215. }
  2216. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2217. begin
  2218. CurrentReg := taicpu(p).oper[1]^.reg;
  2219. if RegReadByInstruction(CurrentReg, hp1) and
  2220. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2221. begin
  2222. { A change has occurred, just not in p }
  2223. Result := True;
  2224. TransferUsedRegs(TmpUsedRegs);
  2225. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2226. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2227. { Just in case something didn't get modified (e.g. an
  2228. implicit register) }
  2229. not RegReadByInstruction(CurrentReg, hp1) then
  2230. begin
  2231. { We can remove the original MOV }
  2232. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2233. RemoveCurrentp(p, hp1);
  2234. { UsedRegs got updated by RemoveCurrentp }
  2235. Result := True;
  2236. Exit;
  2237. end;
  2238. { If we know a MOV instruction has become a null operation, we might as well
  2239. get rid of it now to save time. }
  2240. if (taicpu(hp1).opcode = A_MOV) and
  2241. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2242. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2243. { Just being a register is enough to confirm it's a null operation }
  2244. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2245. begin
  2246. Result := True;
  2247. { Speed-up to reduce a pipeline stall... if we had something like...
  2248. movl %eax,%edx
  2249. movw %dx,%ax
  2250. ... the second instruction would change to movw %ax,%ax, but
  2251. given that it is now %ax that's active rather than %eax,
  2252. penalties might occur due to a partial register write, so instead,
  2253. change it to a MOVZX instruction when optimising for speed.
  2254. }
  2255. if not (cs_opt_size in current_settings.optimizerswitches) and
  2256. IsMOVZXAcceptable and
  2257. (taicpu(hp1).opsize < taicpu(p).opsize)
  2258. {$ifdef x86_64}
  2259. { operations already implicitly set the upper 64 bits to zero }
  2260. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2261. {$endif x86_64}
  2262. then
  2263. begin
  2264. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2265. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2266. case taicpu(p).opsize of
  2267. S_W:
  2268. if taicpu(hp1).opsize = S_B then
  2269. taicpu(hp1).opsize := S_BL
  2270. else
  2271. InternalError(2020012911);
  2272. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2273. case taicpu(hp1).opsize of
  2274. S_B:
  2275. taicpu(hp1).opsize := S_BL;
  2276. S_W:
  2277. taicpu(hp1).opsize := S_WL;
  2278. else
  2279. InternalError(2020012912);
  2280. end;
  2281. else
  2282. InternalError(2020012910);
  2283. end;
  2284. taicpu(hp1).opcode := A_MOVZX;
  2285. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2286. end
  2287. else
  2288. begin
  2289. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2290. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2291. RemoveInstruction(hp1);
  2292. { The instruction after what was hp1 is now the immediate next instruction,
  2293. so we can continue to make optimisations if it's present }
  2294. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2295. Exit;
  2296. hp1 := hp2;
  2297. end;
  2298. end;
  2299. end;
  2300. end;
  2301. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2302. overwrites the original destination register. e.g.
  2303. movl ###,%reg2d
  2304. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2305. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2306. }
  2307. if (taicpu(p).oper[1]^.typ = top_reg) and
  2308. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2309. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2310. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2311. begin
  2312. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2313. begin
  2314. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2315. case taicpu(p).oper[0]^.typ of
  2316. top_const:
  2317. { We have something like:
  2318. movb $x, %regb
  2319. movzbl %regb,%regd
  2320. Change to:
  2321. movl $x, %regd
  2322. }
  2323. begin
  2324. case taicpu(hp1).opsize of
  2325. S_BW:
  2326. begin
  2327. convert_mov_value(A_MOVSX, $FF);
  2328. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2329. taicpu(p).opsize := S_W;
  2330. end;
  2331. S_BL:
  2332. begin
  2333. convert_mov_value(A_MOVSX, $FF);
  2334. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2335. taicpu(p).opsize := S_L;
  2336. end;
  2337. S_WL:
  2338. begin
  2339. convert_mov_value(A_MOVSX, $FFFF);
  2340. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2341. taicpu(p).opsize := S_L;
  2342. end;
  2343. {$ifdef x86_64}
  2344. S_BQ:
  2345. begin
  2346. convert_mov_value(A_MOVSX, $FF);
  2347. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2348. taicpu(p).opsize := S_Q;
  2349. end;
  2350. S_WQ:
  2351. begin
  2352. convert_mov_value(A_MOVSX, $FFFF);
  2353. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2354. taicpu(p).opsize := S_Q;
  2355. end;
  2356. S_LQ:
  2357. begin
  2358. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2359. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2360. taicpu(p).opsize := S_Q;
  2361. end;
  2362. {$endif x86_64}
  2363. else
  2364. { If hp1 was a MOV instruction, it should have been
  2365. optimised already }
  2366. InternalError(2020021001);
  2367. end;
  2368. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2369. RemoveInstruction(hp1);
  2370. Result := True;
  2371. Exit;
  2372. end;
  2373. top_ref:
  2374. { We have something like:
  2375. movb mem, %regb
  2376. movzbl %regb,%regd
  2377. Change to:
  2378. movzbl mem, %regd
  2379. }
  2380. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2381. begin
  2382. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2383. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2384. RemoveCurrentP(p, hp1);
  2385. Result:=True;
  2386. Exit;
  2387. end;
  2388. else
  2389. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2390. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2391. Exit;
  2392. end;
  2393. end
  2394. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2395. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2396. optimised }
  2397. else
  2398. begin
  2399. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2400. RemoveCurrentP(p, hp1);
  2401. Result := True;
  2402. Exit;
  2403. end;
  2404. end;
  2405. if (taicpu(hp1).opcode = A_AND) and
  2406. (taicpu(p).oper[1]^.typ = top_reg) and
  2407. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2408. begin
  2409. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2410. begin
  2411. case taicpu(p).opsize of
  2412. S_L:
  2413. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2414. begin
  2415. { Optimize out:
  2416. mov x, %reg
  2417. and ffffffffh, %reg
  2418. }
  2419. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2420. RemoveInstruction(hp1);
  2421. Result:=true;
  2422. exit;
  2423. end;
  2424. S_Q: { TODO: Confirm if this is even possible }
  2425. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2426. begin
  2427. { Optimize out:
  2428. mov x, %reg
  2429. and ffffffffffffffffh, %reg
  2430. }
  2431. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2432. RemoveInstruction(hp1);
  2433. Result:=true;
  2434. exit;
  2435. end;
  2436. else
  2437. ;
  2438. end;
  2439. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2440. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2441. GetNextInstruction(hp1,hp2) and
  2442. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2443. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2444. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2445. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2446. GetNextInstruction(hp2,hp3) and
  2447. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2448. (taicpu(hp3).condition in [C_E,C_NE]) then
  2449. begin
  2450. TransferUsedRegs(TmpUsedRegs);
  2451. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2452. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2453. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2454. begin
  2455. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2456. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2457. taicpu(hp1).opcode:=A_TEST;
  2458. RemoveInstruction(hp2);
  2459. RemoveCurrentP(p, hp1);
  2460. Result:=true;
  2461. exit;
  2462. end;
  2463. end;
  2464. end
  2465. else if IsMOVZXAcceptable and
  2466. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2467. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2468. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2469. then
  2470. begin
  2471. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2472. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2473. case taicpu(p).opsize of
  2474. S_B:
  2475. if (taicpu(hp1).oper[0]^.val = $ff) then
  2476. begin
  2477. { Convert:
  2478. movb x, %regl movb x, %regl
  2479. andw ffh, %regw andl ffh, %regd
  2480. To:
  2481. movzbw x, %regd movzbl x, %regd
  2482. (Identical registers, just different sizes)
  2483. }
  2484. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2485. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2486. case taicpu(hp1).opsize of
  2487. S_W: NewSize := S_BW;
  2488. S_L: NewSize := S_BL;
  2489. {$ifdef x86_64}
  2490. S_Q: NewSize := S_BQ;
  2491. {$endif x86_64}
  2492. else
  2493. InternalError(2018011510);
  2494. end;
  2495. end
  2496. else
  2497. NewSize := S_NO;
  2498. S_W:
  2499. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2500. begin
  2501. { Convert:
  2502. movw x, %regw
  2503. andl ffffh, %regd
  2504. To:
  2505. movzwl x, %regd
  2506. (Identical registers, just different sizes)
  2507. }
  2508. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2509. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2510. case taicpu(hp1).opsize of
  2511. S_L: NewSize := S_WL;
  2512. {$ifdef x86_64}
  2513. S_Q: NewSize := S_WQ;
  2514. {$endif x86_64}
  2515. else
  2516. InternalError(2018011511);
  2517. end;
  2518. end
  2519. else
  2520. NewSize := S_NO;
  2521. else
  2522. NewSize := S_NO;
  2523. end;
  2524. if NewSize <> S_NO then
  2525. begin
  2526. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2527. { The actual optimization }
  2528. taicpu(p).opcode := A_MOVZX;
  2529. taicpu(p).changeopsize(NewSize);
  2530. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2531. { Safeguard if "and" is followed by a conditional command }
  2532. TransferUsedRegs(TmpUsedRegs);
  2533. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2534. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2535. begin
  2536. { At this point, the "and" command is effectively equivalent to
  2537. "test %reg,%reg". This will be handled separately by the
  2538. Peephole Optimizer. [Kit] }
  2539. DebugMsg(SPeepholeOptimization + PreMessage +
  2540. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2541. end
  2542. else
  2543. begin
  2544. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2545. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2546. RemoveInstruction(hp1);
  2547. end;
  2548. Result := True;
  2549. Exit;
  2550. end;
  2551. end;
  2552. end;
  2553. if (taicpu(hp1).opcode = A_OR) and
  2554. (taicpu(p).oper[1]^.typ = top_reg) and
  2555. MatchOperand(taicpu(p).oper[0]^, 0) and
  2556. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2557. begin
  2558. { mov 0, %reg
  2559. or ###,%reg
  2560. Change to (only if the flags are not used):
  2561. mov ###,%reg
  2562. }
  2563. TransferUsedRegs(TmpUsedRegs);
  2564. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2565. DoOptimisation := True;
  2566. { Even if the flags are used, we might be able to do the optimisation
  2567. if the conditions are predictable }
  2568. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2569. begin
  2570. { Only perform if ### = %reg (the same register) or equal to 0,
  2571. so %reg is guaranteed to still have a value of zero }
  2572. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2573. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2574. begin
  2575. hp2 := hp1;
  2576. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2577. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2578. GetNextInstruction(hp2, hp3) do
  2579. begin
  2580. { Don't continue modifying if the flags state is getting changed }
  2581. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2582. Break;
  2583. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2584. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2585. begin
  2586. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2587. begin
  2588. { Condition is always true }
  2589. case taicpu(hp3).opcode of
  2590. A_Jcc:
  2591. begin
  2592. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2593. { Check for jump shortcuts before we destroy the condition }
  2594. DoJumpOptimizations(hp3, TempBool);
  2595. MakeUnconditional(taicpu(hp3));
  2596. Result := True;
  2597. end;
  2598. A_CMOVcc:
  2599. begin
  2600. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2601. taicpu(hp3).opcode := A_MOV;
  2602. taicpu(hp3).condition := C_None;
  2603. Result := True;
  2604. end;
  2605. A_SETcc:
  2606. begin
  2607. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2608. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2609. taicpu(hp3).opcode := A_MOV;
  2610. taicpu(hp3).ops := 2;
  2611. taicpu(hp3).condition := C_None;
  2612. taicpu(hp3).opsize := S_B;
  2613. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2614. taicpu(hp3).loadconst(0, 1);
  2615. Result := True;
  2616. end;
  2617. else
  2618. InternalError(2021090701);
  2619. end;
  2620. end
  2621. 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
  2622. begin
  2623. { Condition is always false }
  2624. case taicpu(hp3).opcode of
  2625. A_Jcc:
  2626. begin
  2627. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2628. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2629. RemoveInstruction(hp3);
  2630. Result := True;
  2631. { Since hp3 was deleted, hp2 must not be updated }
  2632. Continue;
  2633. end;
  2634. A_CMOVcc:
  2635. begin
  2636. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2637. RemoveInstruction(hp3);
  2638. Result := True;
  2639. { Since hp3 was deleted, hp2 must not be updated }
  2640. Continue;
  2641. end;
  2642. A_SETcc:
  2643. begin
  2644. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2645. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2646. taicpu(hp3).opcode := A_MOV;
  2647. taicpu(hp3).ops := 2;
  2648. taicpu(hp3).condition := C_None;
  2649. taicpu(hp3).opsize := S_B;
  2650. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2651. taicpu(hp3).loadconst(0, 0);
  2652. Result := True;
  2653. end;
  2654. else
  2655. InternalError(2021090702);
  2656. end;
  2657. end
  2658. else
  2659. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2660. DoOptimisation := False;
  2661. end;
  2662. hp2 := hp3;
  2663. end;
  2664. { Flags are still in use - don't optimise }
  2665. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2666. DoOptimisation := False;
  2667. end
  2668. else
  2669. DoOptimisation := False;
  2670. end;
  2671. if DoOptimisation then
  2672. begin
  2673. {$ifdef x86_64}
  2674. { OR only supports 32-bit sign-extended constants for 64-bit
  2675. instructions, so compensate for this if the constant is
  2676. encoded as a value greater than or equal to 2^31 }
  2677. if (taicpu(hp1).opsize = S_Q) and
  2678. (taicpu(hp1).oper[0]^.typ = top_const) and
  2679. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2680. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2681. {$endif x86_64}
  2682. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2683. taicpu(hp1).opcode := A_MOV;
  2684. RemoveCurrentP(p, hp1);
  2685. Result := True;
  2686. Exit;
  2687. end;
  2688. end;
  2689. { Next instruction is also a MOV ? }
  2690. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2691. begin
  2692. if (taicpu(p).oper[1]^.typ = top_reg) and
  2693. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2694. begin
  2695. CurrentReg := taicpu(p).oper[1]^.reg;
  2696. TransferUsedRegs(TmpUsedRegs);
  2697. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2698. { we have
  2699. mov x, %treg
  2700. mov %treg, y
  2701. }
  2702. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2703. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2704. { we've got
  2705. mov x, %treg
  2706. mov %treg, y
  2707. with %treg is not used after }
  2708. case taicpu(p).oper[0]^.typ Of
  2709. { top_reg is covered by DeepMOVOpt }
  2710. top_const:
  2711. begin
  2712. { change
  2713. mov const, %treg
  2714. mov %treg, y
  2715. to
  2716. mov const, y
  2717. }
  2718. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2719. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2720. begin
  2721. if taicpu(hp1).oper[1]^.typ=top_reg then
  2722. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2723. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2724. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2725. RemoveInstruction(hp1);
  2726. Result:=true;
  2727. Exit;
  2728. end;
  2729. end;
  2730. top_ref:
  2731. case taicpu(hp1).oper[1]^.typ of
  2732. top_reg:
  2733. begin
  2734. { change
  2735. mov mem, %treg
  2736. mov %treg, %reg
  2737. to
  2738. mov mem, %reg"
  2739. }
  2740. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2741. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2742. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2743. RemoveInstruction(hp1);
  2744. Result:=true;
  2745. Exit;
  2746. end;
  2747. top_ref:
  2748. begin
  2749. {$ifdef x86_64}
  2750. { Look for the following to simplify:
  2751. mov x(mem1), %reg
  2752. mov %reg, y(mem2)
  2753. mov x+8(mem1), %reg
  2754. mov %reg, y+8(mem2)
  2755. Change to:
  2756. movdqu x(mem1), %xmmreg
  2757. movdqu %xmmreg, y(mem2)
  2758. }
  2759. SourceRef := taicpu(p).oper[0]^.ref^;
  2760. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2761. if (taicpu(p).opsize = S_Q) and
  2762. GetNextInstruction(hp1, hp2) and
  2763. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2764. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2765. begin
  2766. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2767. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2768. Inc(SourceRef.offset, 8);
  2769. if UseAVX then
  2770. begin
  2771. MovAligned := A_VMOVDQA;
  2772. MovUnaligned := A_VMOVDQU;
  2773. end
  2774. else
  2775. begin
  2776. MovAligned := A_MOVDQA;
  2777. MovUnaligned := A_MOVDQU;
  2778. end;
  2779. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2780. begin
  2781. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2782. Inc(TargetRef.offset, 8);
  2783. if GetNextInstruction(hp2, hp3) and
  2784. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2785. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2786. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2787. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2788. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2789. begin
  2790. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2791. if CurrentReg <> NR_NO then
  2792. begin
  2793. { Remember that the offsets are 8 ahead }
  2794. if ((SourceRef.offset mod 16) = 8) and
  2795. (
  2796. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2797. (SourceRef.base = current_procinfo.framepointer) or
  2798. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2799. ) then
  2800. taicpu(p).opcode := MovAligned
  2801. else
  2802. taicpu(p).opcode := MovUnaligned;
  2803. taicpu(p).opsize := S_XMM;
  2804. taicpu(p).oper[1]^.reg := CurrentReg;
  2805. if ((TargetRef.offset mod 16) = 8) and
  2806. (
  2807. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2808. (TargetRef.base = current_procinfo.framepointer) or
  2809. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2810. ) then
  2811. taicpu(hp1).opcode := MovAligned
  2812. else
  2813. taicpu(hp1).opcode := MovUnaligned;
  2814. taicpu(hp1).opsize := S_XMM;
  2815. taicpu(hp1).oper[0]^.reg := CurrentReg;
  2816. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  2817. RemoveInstruction(hp2);
  2818. RemoveInstruction(hp3);
  2819. Result := True;
  2820. Exit;
  2821. end;
  2822. end;
  2823. end
  2824. else
  2825. begin
  2826. { See if the next references are 8 less rather than 8 greater }
  2827. Dec(SourceRef.offset, 16); { -8 the other way }
  2828. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2829. begin
  2830. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2831. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  2832. if GetNextInstruction(hp2, hp3) and
  2833. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2834. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2835. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2836. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2837. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2838. begin
  2839. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2840. if CurrentReg <> NR_NO then
  2841. begin
  2842. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  2843. if ((SourceRef.offset mod 16) = 0) and
  2844. (
  2845. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2846. (SourceRef.base = current_procinfo.framepointer) or
  2847. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2848. ) then
  2849. taicpu(hp2).opcode := MovAligned
  2850. else
  2851. taicpu(hp2).opcode := MovUnaligned;
  2852. taicpu(hp2).opsize := S_XMM;
  2853. taicpu(hp2).oper[1]^.reg := CurrentReg;
  2854. if ((TargetRef.offset mod 16) = 0) and
  2855. (
  2856. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2857. (TargetRef.base = current_procinfo.framepointer) or
  2858. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2859. ) then
  2860. taicpu(hp3).opcode := MovAligned
  2861. else
  2862. taicpu(hp3).opcode := MovUnaligned;
  2863. taicpu(hp3).opsize := S_XMM;
  2864. taicpu(hp3).oper[0]^.reg := CurrentReg;
  2865. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  2866. RemoveInstruction(hp1);
  2867. RemoveCurrentP(p, hp2);
  2868. Result := True;
  2869. Exit;
  2870. end;
  2871. end;
  2872. end;
  2873. end;
  2874. end;
  2875. {$endif x86_64}
  2876. end;
  2877. else
  2878. { The write target should be a reg or a ref }
  2879. InternalError(2021091601);
  2880. end;
  2881. else
  2882. ;
  2883. end
  2884. else
  2885. { %treg is used afterwards, but all eventualities
  2886. other than the first MOV instruction being a constant
  2887. are covered by DeepMOVOpt, so only check for that }
  2888. if (taicpu(p).oper[0]^.typ = top_const) and
  2889. (
  2890. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  2891. not (cs_opt_size in current_settings.optimizerswitches) or
  2892. (taicpu(hp1).opsize = S_B)
  2893. ) and
  2894. (
  2895. (taicpu(hp1).oper[1]^.typ = top_reg) or
  2896. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  2897. ) then
  2898. begin
  2899. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  2900. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  2901. end;
  2902. end;
  2903. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2904. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2905. { mov reg1, mem1 or mov mem1, reg1
  2906. mov mem2, reg2 mov reg2, mem2}
  2907. begin
  2908. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2909. { mov reg1, mem1 or mov mem1, reg1
  2910. mov mem2, reg1 mov reg2, mem1}
  2911. begin
  2912. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2913. { Removes the second statement from
  2914. mov reg1, mem1/reg2
  2915. mov mem1/reg2, reg1 }
  2916. begin
  2917. if taicpu(p).oper[0]^.typ=top_reg then
  2918. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2919. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  2920. RemoveInstruction(hp1);
  2921. Result:=true;
  2922. exit;
  2923. end
  2924. else
  2925. begin
  2926. TransferUsedRegs(TmpUsedRegs);
  2927. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2928. if (taicpu(p).oper[1]^.typ = top_ref) and
  2929. { mov reg1, mem1
  2930. mov mem2, reg1 }
  2931. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  2932. GetNextInstruction(hp1, hp2) and
  2933. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  2934. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  2935. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  2936. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  2937. { change to
  2938. mov reg1, mem1 mov reg1, mem1
  2939. mov mem2, reg1 cmp reg1, mem2
  2940. cmp mem1, reg1
  2941. }
  2942. begin
  2943. RemoveInstruction(hp2);
  2944. taicpu(hp1).opcode := A_CMP;
  2945. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  2946. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2947. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2948. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  2949. end;
  2950. end;
  2951. end
  2952. else if (taicpu(p).oper[1]^.typ=top_ref) and
  2953. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2954. begin
  2955. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2956. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2957. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  2958. end
  2959. else
  2960. begin
  2961. TransferUsedRegs(TmpUsedRegs);
  2962. if GetNextInstruction(hp1, hp2) and
  2963. MatchOpType(taicpu(p),top_ref,top_reg) and
  2964. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2965. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2966. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  2967. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  2968. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2969. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  2970. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  2971. { mov mem1, %reg1
  2972. mov %reg1, mem2
  2973. mov mem2, reg2
  2974. to:
  2975. mov mem1, reg2
  2976. mov reg2, mem2}
  2977. begin
  2978. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  2979. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  2980. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  2981. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  2982. RemoveInstruction(hp2);
  2983. Result := True;
  2984. end
  2985. {$ifdef i386}
  2986. { this is enabled for i386 only, as the rules to create the reg sets below
  2987. are too complicated for x86-64, so this makes this code too error prone
  2988. on x86-64
  2989. }
  2990. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  2991. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  2992. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  2993. { mov mem1, reg1 mov mem1, reg1
  2994. mov reg1, mem2 mov reg1, mem2
  2995. mov mem2, reg2 mov mem2, reg1
  2996. to: to:
  2997. mov mem1, reg1 mov mem1, reg1
  2998. mov mem1, reg2 mov reg1, mem2
  2999. mov reg1, mem2
  3000. or (if mem1 depends on reg1
  3001. and/or if mem2 depends on reg2)
  3002. to:
  3003. mov mem1, reg1
  3004. mov reg1, mem2
  3005. mov reg1, reg2
  3006. }
  3007. begin
  3008. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3009. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3010. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3011. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3012. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3013. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3014. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3015. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3016. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3017. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3018. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3019. end
  3020. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3021. begin
  3022. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3023. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3024. end
  3025. else
  3026. begin
  3027. RemoveInstruction(hp2);
  3028. end
  3029. {$endif i386}
  3030. ;
  3031. end;
  3032. end
  3033. { movl [mem1],reg1
  3034. movl [mem1],reg2
  3035. to
  3036. movl [mem1],reg1
  3037. movl reg1,reg2
  3038. }
  3039. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3040. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3041. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3042. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3043. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3044. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3045. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3046. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3047. begin
  3048. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3049. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3050. end;
  3051. { movl const1,[mem1]
  3052. movl [mem1],reg1
  3053. to
  3054. movl const1,reg1
  3055. movl reg1,[mem1]
  3056. }
  3057. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3058. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3059. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3060. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3061. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3062. begin
  3063. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3064. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3065. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3066. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3067. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3068. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3069. Result:=true;
  3070. exit;
  3071. end;
  3072. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3073. end;
  3074. { search further than the next instruction for a mov (as long as it's not a jump) }
  3075. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3076. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3077. (taicpu(p).oper[1]^.typ = top_reg) and
  3078. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3079. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3080. begin
  3081. { we work with hp2 here, so hp1 can be still used later on when
  3082. checking for GetNextInstruction_p }
  3083. hp3 := hp1;
  3084. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3085. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3086. { Saves on a large number of dereferences }
  3087. ActiveReg := taicpu(p).oper[1]^.reg;
  3088. TransferUsedRegs(TmpUsedRegs);
  3089. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3090. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3091. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3092. (hp2.typ=ait_instruction) do
  3093. begin
  3094. case taicpu(hp2).opcode of
  3095. A_POP:
  3096. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3097. begin
  3098. if not CrossJump and
  3099. not RegUsedBetween(ActiveReg, p, hp2) then
  3100. begin
  3101. { We can remove the original MOV since the register
  3102. wasn't used between it and its popping from the stack }
  3103. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3104. RemoveCurrentp(p, hp1);
  3105. Result := True;
  3106. Exit;
  3107. end;
  3108. { Can't go any further }
  3109. Break;
  3110. end;
  3111. A_MOV:
  3112. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3113. ((taicpu(p).oper[0]^.typ=top_const) or
  3114. ((taicpu(p).oper[0]^.typ=top_reg) and
  3115. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3116. )
  3117. ) then
  3118. begin
  3119. { we have
  3120. mov x, %treg
  3121. mov %treg, y
  3122. }
  3123. { We don't need to call UpdateUsedRegs for every instruction between
  3124. p and hp2 because the register we're concerned about will not
  3125. become deallocated (otherwise GetNextInstructionUsingReg would
  3126. have stopped at an earlier instruction). [Kit] }
  3127. TempRegUsed :=
  3128. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3129. RegReadByInstruction(ActiveReg, hp3) or
  3130. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3131. case taicpu(p).oper[0]^.typ Of
  3132. top_reg:
  3133. begin
  3134. { change
  3135. mov %reg, %treg
  3136. mov %treg, y
  3137. to
  3138. mov %reg, y
  3139. }
  3140. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3141. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3142. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3143. begin
  3144. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3145. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3146. if TempRegUsed then
  3147. begin
  3148. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3149. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3150. { Set the start of the next GetNextInstructionUsingRegCond search
  3151. to start at the entry right before hp2 (which is about to be removed) }
  3152. hp3 := tai(hp2.Previous);
  3153. RemoveInstruction(hp2);
  3154. { See if there's more we can optimise }
  3155. Continue;
  3156. end
  3157. else
  3158. begin
  3159. RemoveInstruction(hp2);
  3160. { We can remove the original MOV too }
  3161. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3162. RemoveCurrentP(p, hp1);
  3163. Result:=true;
  3164. Exit;
  3165. end;
  3166. end
  3167. else
  3168. begin
  3169. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3170. taicpu(hp2).loadReg(0, CurrentReg);
  3171. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3172. { Check to see if the register also appears in the reference }
  3173. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3174. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3175. { Don't remove the first instruction if the temporary register is in use }
  3176. if not TempRegUsed and
  3177. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3178. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3179. begin
  3180. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3181. RemoveCurrentP(p, hp1);
  3182. Result:=true;
  3183. Exit;
  3184. end;
  3185. { No need to set Result to True here. If there's another instruction later
  3186. on that can be optimised, it will be detected when the main Pass 1 loop
  3187. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3188. end;
  3189. end;
  3190. top_const:
  3191. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3192. begin
  3193. { change
  3194. mov const, %treg
  3195. mov %treg, y
  3196. to
  3197. mov const, y
  3198. }
  3199. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3200. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3201. begin
  3202. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3203. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3204. if TempRegUsed then
  3205. begin
  3206. { Don't remove the first instruction if the temporary register is in use }
  3207. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3208. { No need to set Result to True. If there's another instruction later on
  3209. that can be optimised, it will be detected when the main Pass 1 loop
  3210. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3211. end
  3212. else
  3213. begin
  3214. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3215. RemoveCurrentP(p, hp1);
  3216. Result:=true;
  3217. Exit;
  3218. end;
  3219. end;
  3220. end;
  3221. else
  3222. Internalerror(2019103001);
  3223. end;
  3224. end
  3225. else
  3226. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3227. begin
  3228. if not CrossJump and
  3229. not RegUsedBetween(ActiveReg, p, hp2) and
  3230. not RegReadByInstruction(ActiveReg, hp2) then
  3231. begin
  3232. { Register is not used before it is overwritten }
  3233. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3234. RemoveCurrentp(p, hp1);
  3235. Result := True;
  3236. Exit;
  3237. end;
  3238. if (taicpu(p).oper[0]^.typ = top_const) and
  3239. (taicpu(hp2).oper[0]^.typ = top_const) then
  3240. begin
  3241. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3242. begin
  3243. { Same value - register hasn't changed }
  3244. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3245. RemoveInstruction(hp2);
  3246. Result := True;
  3247. { See if there's more we can optimise }
  3248. Continue;
  3249. end;
  3250. end;
  3251. end;
  3252. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3253. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3254. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3255. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3256. begin
  3257. {
  3258. Change from:
  3259. mov ###, %reg
  3260. ...
  3261. movs/z %reg,%reg (Same register, just different sizes)
  3262. To:
  3263. movs/z ###, %reg (Longer version)
  3264. ...
  3265. (remove)
  3266. }
  3267. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3268. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3269. { Keep the first instruction as mov if ### is a constant }
  3270. if taicpu(p).oper[0]^.typ = top_const then
  3271. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3272. else
  3273. begin
  3274. taicpu(p).opcode := taicpu(hp2).opcode;
  3275. taicpu(p).opsize := taicpu(hp2).opsize;
  3276. end;
  3277. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3278. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3279. RemoveInstruction(hp2);
  3280. Result := True;
  3281. Exit;
  3282. end;
  3283. else
  3284. { Move down to the MatchOpType if-block below };
  3285. end;
  3286. { Also catches MOV/S/Z instructions that aren't modified }
  3287. if taicpu(p).oper[0]^.typ = top_reg then
  3288. begin
  3289. CurrentReg := taicpu(p).oper[0]^.reg;
  3290. if
  3291. not RegModifiedByInstruction(CurrentReg, hp3) and
  3292. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3293. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3294. begin
  3295. Result := True;
  3296. { Just in case something didn't get modified (e.g. an
  3297. implicit register). Also, if it does read from this
  3298. register, then there's no longer an advantage to
  3299. changing the register on subsequent instructions.}
  3300. if not RegReadByInstruction(ActiveReg, hp2) then
  3301. begin
  3302. { If a conditional jump was crossed, do not delete
  3303. the original MOV no matter what }
  3304. if not CrossJump and
  3305. { RegEndOfLife returns True if the register is
  3306. deallocated before the next instruction or has
  3307. been loaded with a new value }
  3308. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3309. begin
  3310. { We can remove the original MOV }
  3311. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3312. RemoveCurrentp(p, hp1);
  3313. Exit;
  3314. end;
  3315. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3316. begin
  3317. { See if there's more we can optimise }
  3318. hp3 := hp2;
  3319. Continue;
  3320. end;
  3321. end;
  3322. end;
  3323. end;
  3324. { Break out of the while loop under normal circumstances }
  3325. Break;
  3326. end;
  3327. end;
  3328. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3329. (taicpu(p).oper[1]^.typ = top_reg) and
  3330. (taicpu(p).opsize = S_L) and
  3331. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3332. (taicpu(hp2).opcode = A_AND) and
  3333. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3334. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3335. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3336. ) then
  3337. begin
  3338. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3339. begin
  3340. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3341. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3342. begin
  3343. { Optimize out:
  3344. mov x, %reg
  3345. and ffffffffh, %reg
  3346. }
  3347. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3348. RemoveInstruction(hp2);
  3349. Result:=true;
  3350. exit;
  3351. end;
  3352. end;
  3353. end;
  3354. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3355. x >= RetOffset) as it doesn't do anything (it writes either to a
  3356. parameter or to the temporary storage room for the function
  3357. result)
  3358. }
  3359. if IsExitCode(hp1) and
  3360. (taicpu(p).oper[1]^.typ = top_ref) and
  3361. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3362. (
  3363. (
  3364. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3365. not (
  3366. assigned(current_procinfo.procdef.funcretsym) and
  3367. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3368. )
  3369. ) or
  3370. { Also discard writes to the stack that are below the base pointer,
  3371. as this is temporary storage rather than a function result on the
  3372. stack, say. }
  3373. (
  3374. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3375. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3376. )
  3377. ) then
  3378. begin
  3379. RemoveCurrentp(p, hp1);
  3380. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3381. RemoveLastDeallocForFuncRes(p);
  3382. Result:=true;
  3383. exit;
  3384. end;
  3385. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3386. begin
  3387. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3388. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3389. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3390. begin
  3391. { change
  3392. mov reg1, mem1
  3393. test/cmp x, mem1
  3394. to
  3395. mov reg1, mem1
  3396. test/cmp x, reg1
  3397. }
  3398. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3399. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3400. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3401. Result := True;
  3402. Exit;
  3403. end;
  3404. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3405. { The x86 assemblers have difficulty comparing values against absolute addresses }
  3406. (taicpu(p).oper[0]^.ref^.refaddr in [addr_no, addr_pic, addr_pic_no_got]) and
  3407. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  3408. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  3409. (
  3410. (
  3411. (taicpu(hp1).opcode = A_TEST)
  3412. ) or (
  3413. (taicpu(hp1).opcode = A_CMP) and
  3414. { A sanity check more than anything }
  3415. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  3416. )
  3417. ) then
  3418. begin
  3419. { change
  3420. mov mem, %reg
  3421. cmp/test x, %reg / test %reg,%reg
  3422. (reg deallocated)
  3423. to
  3424. cmp/test x, mem / cmp 0, mem
  3425. }
  3426. TransferUsedRegs(TmpUsedRegs);
  3427. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3428. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3429. begin
  3430. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  3431. if (taicpu(hp1).opcode = A_TEST) and
  3432. (
  3433. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  3434. MatchOperand(taicpu(hp1).oper[0]^, -1)
  3435. ) then
  3436. begin
  3437. taicpu(hp1).opcode := A_CMP;
  3438. taicpu(hp1).loadconst(0, 0);
  3439. end;
  3440. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  3441. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  3442. RemoveCurrentP(p, hp1);
  3443. Result := True;
  3444. Exit;
  3445. end;
  3446. end;
  3447. end;
  3448. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3449. { If the flags register is in use, don't change the instruction to an
  3450. ADD otherwise this will scramble the flags. [Kit] }
  3451. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3452. begin
  3453. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3454. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3455. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3456. ) or
  3457. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3458. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3459. )
  3460. ) then
  3461. { mov reg1,ref
  3462. lea reg2,[reg1,reg2]
  3463. to
  3464. add reg2,ref}
  3465. begin
  3466. TransferUsedRegs(TmpUsedRegs);
  3467. { reg1 may not be used afterwards }
  3468. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3469. begin
  3470. Taicpu(hp1).opcode:=A_ADD;
  3471. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3472. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3473. RemoveCurrentp(p, hp1);
  3474. result:=true;
  3475. exit;
  3476. end;
  3477. end;
  3478. { If the LEA instruction can be converted into an arithmetic instruction,
  3479. it may be possible to then fold it in the next optimisation, otherwise
  3480. there's nothing more that can be optimised here. }
  3481. if not ConvertLEA(taicpu(hp1)) then
  3482. Exit;
  3483. end;
  3484. if (taicpu(p).oper[1]^.typ = top_reg) and
  3485. (hp1.typ = ait_instruction) and
  3486. GetNextInstruction(hp1, hp2) and
  3487. MatchInstruction(hp2,A_MOV,[]) and
  3488. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3489. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3490. (
  3491. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3492. {$ifdef x86_64}
  3493. or
  3494. (
  3495. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3496. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3497. )
  3498. {$endif x86_64}
  3499. ) then
  3500. begin
  3501. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3502. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3503. { change movsX/movzX reg/ref, reg2
  3504. add/sub/or/... reg3/$const, reg2
  3505. mov reg2 reg/ref
  3506. dealloc reg2
  3507. to
  3508. add/sub/or/... reg3/$const, reg/ref }
  3509. begin
  3510. TransferUsedRegs(TmpUsedRegs);
  3511. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3512. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3513. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3514. begin
  3515. { by example:
  3516. movswl %si,%eax movswl %si,%eax p
  3517. decl %eax addl %edx,%eax hp1
  3518. movw %ax,%si movw %ax,%si hp2
  3519. ->
  3520. movswl %si,%eax movswl %si,%eax p
  3521. decw %eax addw %edx,%eax hp1
  3522. movw %ax,%si movw %ax,%si hp2
  3523. }
  3524. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3525. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3526. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3527. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3528. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3529. {
  3530. ->
  3531. movswl %si,%eax movswl %si,%eax p
  3532. decw %si addw %dx,%si hp1
  3533. movw %ax,%si movw %ax,%si hp2
  3534. }
  3535. case taicpu(hp1).ops of
  3536. 1:
  3537. begin
  3538. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3539. if taicpu(hp1).oper[0]^.typ=top_reg then
  3540. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3541. end;
  3542. 2:
  3543. begin
  3544. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3545. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3546. (taicpu(hp1).opcode<>A_SHL) and
  3547. (taicpu(hp1).opcode<>A_SHR) and
  3548. (taicpu(hp1).opcode<>A_SAR) then
  3549. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3550. end;
  3551. else
  3552. internalerror(2008042701);
  3553. end;
  3554. {
  3555. ->
  3556. decw %si addw %dx,%si p
  3557. }
  3558. RemoveInstruction(hp2);
  3559. RemoveCurrentP(p, hp1);
  3560. Result:=True;
  3561. Exit;
  3562. end;
  3563. end;
  3564. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3565. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3566. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3567. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3568. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3569. )
  3570. {$ifdef i386}
  3571. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3572. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3573. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3574. {$endif i386}
  3575. then
  3576. { change movsX/movzX reg/ref, reg2
  3577. add/sub/or/... regX/$const, reg2
  3578. mov reg2, reg3
  3579. dealloc reg2
  3580. to
  3581. movsX/movzX reg/ref, reg3
  3582. add/sub/or/... reg3/$const, reg3
  3583. }
  3584. begin
  3585. TransferUsedRegs(TmpUsedRegs);
  3586. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3587. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3588. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3589. begin
  3590. { by example:
  3591. movswl %si,%eax movswl %si,%eax p
  3592. decl %eax addl %edx,%eax hp1
  3593. movw %ax,%si movw %ax,%si hp2
  3594. ->
  3595. movswl %si,%eax movswl %si,%eax p
  3596. decw %eax addw %edx,%eax hp1
  3597. movw %ax,%si movw %ax,%si hp2
  3598. }
  3599. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3600. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3601. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3602. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3603. { limit size of constants as well to avoid assembler errors, but
  3604. check opsize to avoid overflow when left shifting the 1 }
  3605. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3606. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3607. {$ifdef x86_64}
  3608. { Be careful of, for example:
  3609. movl %reg1,%reg2
  3610. addl %reg3,%reg2
  3611. movq %reg2,%reg4
  3612. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3613. }
  3614. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3615. begin
  3616. taicpu(hp2).changeopsize(S_L);
  3617. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3618. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3619. end;
  3620. {$endif x86_64}
  3621. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3622. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3623. if taicpu(p).oper[0]^.typ=top_reg then
  3624. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3625. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3626. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3627. {
  3628. ->
  3629. movswl %si,%eax movswl %si,%eax p
  3630. decw %si addw %dx,%si hp1
  3631. movw %ax,%si movw %ax,%si hp2
  3632. }
  3633. case taicpu(hp1).ops of
  3634. 1:
  3635. begin
  3636. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3637. if taicpu(hp1).oper[0]^.typ=top_reg then
  3638. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3639. end;
  3640. 2:
  3641. begin
  3642. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3643. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3644. (taicpu(hp1).opcode<>A_SHL) and
  3645. (taicpu(hp1).opcode<>A_SHR) and
  3646. (taicpu(hp1).opcode<>A_SAR) then
  3647. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3648. end;
  3649. else
  3650. internalerror(2018111801);
  3651. end;
  3652. {
  3653. ->
  3654. decw %si addw %dx,%si p
  3655. }
  3656. RemoveInstruction(hp2);
  3657. end;
  3658. end;
  3659. end;
  3660. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3661. GetNextInstruction(hp1, hp2) and
  3662. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3663. MatchOperand(Taicpu(p).oper[0]^,0) and
  3664. (Taicpu(p).oper[1]^.typ = top_reg) and
  3665. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3666. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3667. { mov reg1,0
  3668. bts reg1,operand1 --> mov reg1,operand2
  3669. or reg1,operand2 bts reg1,operand1}
  3670. begin
  3671. Taicpu(hp2).opcode:=A_MOV;
  3672. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3673. asml.remove(hp1);
  3674. insertllitem(hp2,hp2.next,hp1);
  3675. RemoveCurrentp(p, hp1);
  3676. Result:=true;
  3677. exit;
  3678. end;
  3679. {
  3680. mov ref,reg0
  3681. <op> reg0,reg1
  3682. dealloc reg0
  3683. to
  3684. <op> ref,reg1
  3685. }
  3686. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3687. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3688. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3689. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3690. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3691. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3692. begin
  3693. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3694. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3695. RemoveCurrentp(p, hp1);
  3696. Result:=true;
  3697. exit;
  3698. end;
  3699. {$ifdef x86_64}
  3700. { Convert:
  3701. movq x(ref),%reg64
  3702. shrq y,%reg64
  3703. To:
  3704. movq x+4(ref),%reg32
  3705. shrq y-32,%reg32 (Remove if y = 32)
  3706. }
  3707. if (taicpu(p).opsize = S_Q) and
  3708. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3709. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3710. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3711. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3712. (taicpu(hp1).oper[0]^.val >= 32) and
  3713. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3714. begin
  3715. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3716. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3717. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3718. { Convert to 32-bit }
  3719. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3720. taicpu(p).opsize := S_L;
  3721. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3722. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3723. if (taicpu(hp1).oper[0]^.val = 32) then
  3724. begin
  3725. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3726. RemoveInstruction(hp1);
  3727. end
  3728. else
  3729. begin
  3730. { This will potentially open up more arithmetic operations since
  3731. the peephole optimizer now has a big hint that only the lower
  3732. 32 bits are currently in use (and opcodes are smaller in size) }
  3733. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3734. taicpu(hp1).opsize := S_L;
  3735. Dec(taicpu(hp1).oper[0]^.val, 32);
  3736. DebugMsg(SPeepholeOptimization + PreMessage +
  3737. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3738. end;
  3739. Result := True;
  3740. Exit;
  3741. end;
  3742. {$endif x86_64}
  3743. end;
  3744. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3745. var
  3746. hp1 : tai;
  3747. begin
  3748. Result:=false;
  3749. if taicpu(p).ops <> 2 then
  3750. exit;
  3751. if ((taicpu(p).oper[1]^.typ=top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  3752. GetNextInstruction(p,hp1) then
  3753. begin
  3754. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3755. (taicpu(hp1).ops = 2) then
  3756. begin
  3757. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3758. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3759. { movXX reg1, mem1 or movXX mem1, reg1
  3760. movXX mem2, reg2 movXX reg2, mem2}
  3761. begin
  3762. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3763. { movXX reg1, mem1 or movXX mem1, reg1
  3764. movXX mem2, reg1 movXX reg2, mem1}
  3765. begin
  3766. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3767. begin
  3768. { Removes the second statement from
  3769. movXX reg1, mem1/reg2
  3770. movXX mem1/reg2, reg1
  3771. }
  3772. if taicpu(p).oper[0]^.typ=top_reg then
  3773. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3774. { Removes the second statement from
  3775. movXX mem1/reg1, reg2
  3776. movXX reg2, mem1/reg1
  3777. }
  3778. if (taicpu(p).oper[1]^.typ=top_reg) and
  3779. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3780. begin
  3781. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3782. RemoveInstruction(hp1);
  3783. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3784. Result:=true;
  3785. exit;
  3786. end
  3787. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  3788. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  3789. begin
  3790. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3791. RemoveInstruction(hp1);
  3792. Result:=true;
  3793. exit;
  3794. end;
  3795. end
  3796. end;
  3797. end;
  3798. end;
  3799. end;
  3800. end;
  3801. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3802. var
  3803. hp1 : tai;
  3804. begin
  3805. result:=false;
  3806. { replace
  3807. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3808. MovX %mreg2,%mreg1
  3809. dealloc %mreg2
  3810. by
  3811. <Op>X %mreg2,%mreg1
  3812. ?
  3813. }
  3814. if GetNextInstruction(p,hp1) and
  3815. { we mix single and double opperations here because we assume that the compiler
  3816. generates vmovapd only after double operations and vmovaps only after single operations }
  3817. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3818. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3819. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3820. (taicpu(p).oper[0]^.typ=top_reg) then
  3821. begin
  3822. TransferUsedRegs(TmpUsedRegs);
  3823. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3824. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3825. begin
  3826. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3827. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3828. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3829. RemoveInstruction(hp1);
  3830. result:=true;
  3831. end;
  3832. end;
  3833. end;
  3834. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3835. var
  3836. hp1, p_label, p_dist, hp1_dist: tai;
  3837. JumpLabel, JumpLabel_dist: TAsmLabel;
  3838. begin
  3839. Result := False;
  3840. if GetNextInstruction(p, hp1) and
  3841. TrySwapMovCmp(p, hp1) then
  3842. begin
  3843. Result := True;
  3844. Exit;
  3845. end;
  3846. { Search for:
  3847. test %reg,%reg
  3848. j(c1) @lbl1
  3849. ...
  3850. @lbl:
  3851. test %reg,%reg (same register)
  3852. j(c2) @lbl2
  3853. If c2 is a subset of c1, change to:
  3854. test %reg,%reg
  3855. j(c1) @lbl2
  3856. (@lbl1 may become a dead label as a result)
  3857. }
  3858. if (taicpu(p).oper[1]^.typ = top_reg) and
  3859. (taicpu(p).oper[0]^.typ = top_reg) and
  3860. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  3861. MatchInstruction(hp1, A_JCC, []) and
  3862. IsJumpToLabel(taicpu(hp1)) then
  3863. begin
  3864. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  3865. p_label := nil;
  3866. if Assigned(JumpLabel) then
  3867. p_label := getlabelwithsym(JumpLabel);
  3868. if Assigned(p_label) and
  3869. GetNextInstruction(p_label, p_dist) and
  3870. MatchInstruction(p_dist, A_TEST, []) and
  3871. { It's fine if the second test uses smaller sub-registers }
  3872. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  3873. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  3874. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  3875. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  3876. GetNextInstruction(p_dist, hp1_dist) and
  3877. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  3878. begin
  3879. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  3880. if JumpLabel = JumpLabel_dist then
  3881. { This is an infinite loop }
  3882. Exit;
  3883. { Best optimisation when the first condition is a subset (or equal) of the second }
  3884. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  3885. begin
  3886. { Any registers used here will already be allocated }
  3887. if Assigned(JumpLabel_dist) then
  3888. JumpLabel_dist.IncRefs;
  3889. if Assigned(JumpLabel) then
  3890. JumpLabel.DecRefs;
  3891. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  3892. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  3893. Result := True;
  3894. Exit;
  3895. end;
  3896. end;
  3897. end;
  3898. end;
  3899. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  3900. var
  3901. hp1, hp2: tai;
  3902. ActiveReg: TRegister;
  3903. OldOffset: asizeint;
  3904. ThisConst: TCGInt;
  3905. function RegDeallocated: Boolean;
  3906. begin
  3907. TransferUsedRegs(TmpUsedRegs);
  3908. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3909. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  3910. end;
  3911. begin
  3912. result:=false;
  3913. hp1 := nil;
  3914. { replace
  3915. addX const,%reg1
  3916. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  3917. dealloc %reg1
  3918. by
  3919. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  3920. }
  3921. if MatchOpType(taicpu(p),top_const,top_reg) then
  3922. begin
  3923. ActiveReg := taicpu(p).oper[1]^.reg;
  3924. { Ensures the entire register was updated }
  3925. if (taicpu(p).opsize >= S_L) and
  3926. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  3927. MatchInstruction(hp1,A_LEA,[]) and
  3928. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  3929. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  3930. (
  3931. { Cover the case where the register in the reference is also the destination register }
  3932. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  3933. (
  3934. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  3935. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  3936. RegDeallocated
  3937. )
  3938. ) then
  3939. begin
  3940. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  3941. {$push}
  3942. {$R-}{$Q-}
  3943. { Explicitly disable overflow checking for these offset calculation
  3944. as those do not matter for the final result }
  3945. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  3946. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  3947. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  3948. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3949. {$pop}
  3950. {$ifdef x86_64}
  3951. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  3952. begin
  3953. { Overflow; abort }
  3954. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  3955. end
  3956. else
  3957. {$endif x86_64}
  3958. begin
  3959. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  3960. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  3961. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  3962. RemoveCurrentP(p, hp1)
  3963. else
  3964. RemoveCurrentP(p);
  3965. result:=true;
  3966. Exit;
  3967. end;
  3968. end;
  3969. if (
  3970. { Save calling GetNextInstructionUsingReg again }
  3971. Assigned(hp1) or
  3972. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  3973. ) and
  3974. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  3975. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  3976. begin
  3977. if taicpu(hp1).oper[0]^.typ = top_const then
  3978. begin
  3979. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  3980. if taicpu(hp1).opcode = A_ADD then
  3981. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  3982. else
  3983. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  3984. Result := True;
  3985. { Handle any overflows }
  3986. case taicpu(p).opsize of
  3987. S_B:
  3988. taicpu(p).oper[0]^.val := ThisConst and $FF;
  3989. S_W:
  3990. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  3991. S_L:
  3992. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  3993. {$ifdef x86_64}
  3994. S_Q:
  3995. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  3996. { Overflow; abort }
  3997. Result := False
  3998. else
  3999. taicpu(p).oper[0]^.val := ThisConst;
  4000. {$endif x86_64}
  4001. else
  4002. InternalError(2021102610);
  4003. end;
  4004. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4005. if Result then
  4006. begin
  4007. if (taicpu(p).oper[0]^.val < 0) and
  4008. (
  4009. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4010. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4011. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4012. ) then
  4013. begin
  4014. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4015. taicpu(p).opcode := A_SUB;
  4016. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4017. end
  4018. else
  4019. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4020. RemoveInstruction(hp1);
  4021. end;
  4022. end
  4023. else
  4024. begin
  4025. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4026. TransferUsedRegs(TmpUsedRegs);
  4027. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4028. hp2 := p;
  4029. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4030. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4031. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4032. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4033. begin
  4034. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4035. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4036. Asml.Remove(p);
  4037. Asml.InsertAfter(p, hp1);
  4038. p := hp1;
  4039. Result := True;
  4040. end;
  4041. end;
  4042. end;
  4043. end;
  4044. end;
  4045. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4046. var
  4047. hp1: tai;
  4048. ref: Integer;
  4049. saveref: treference;
  4050. TempReg: TRegister;
  4051. Multiple: TCGInt;
  4052. begin
  4053. Result:=false;
  4054. { removes seg register prefixes from LEA operations, as they
  4055. don't do anything}
  4056. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  4057. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4058. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4059. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4060. (
  4061. { do not mess with leas accessing the stack pointer
  4062. unless it's a null operation }
  4063. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4064. (
  4065. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4066. (taicpu(p).oper[0]^.ref^.offset = 0)
  4067. )
  4068. ) and
  4069. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4070. begin
  4071. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4072. begin
  4073. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4074. begin
  4075. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4076. taicpu(p).oper[1]^.reg);
  4077. InsertLLItem(p.previous,p.next, hp1);
  4078. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4079. p.free;
  4080. p:=hp1;
  4081. end
  4082. else
  4083. begin
  4084. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4085. RemoveCurrentP(p);
  4086. end;
  4087. Result:=true;
  4088. exit;
  4089. end
  4090. else if (
  4091. { continue to use lea to adjust the stack pointer,
  4092. it is the recommended way, but only if not optimizing for size }
  4093. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4094. (cs_opt_size in current_settings.optimizerswitches)
  4095. ) and
  4096. { If the flags register is in use, don't change the instruction
  4097. to an ADD otherwise this will scramble the flags. [Kit] }
  4098. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4099. ConvertLEA(taicpu(p)) then
  4100. begin
  4101. Result:=true;
  4102. exit;
  4103. end;
  4104. end;
  4105. if GetNextInstruction(p,hp1) and
  4106. (hp1.typ=ait_instruction) then
  4107. begin
  4108. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4109. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4110. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  4111. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  4112. begin
  4113. TransferUsedRegs(TmpUsedRegs);
  4114. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4115. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4116. begin
  4117. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4118. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4119. RemoveInstruction(hp1);
  4120. result:=true;
  4121. exit;
  4122. end;
  4123. end;
  4124. { changes
  4125. lea <ref1>, reg1
  4126. <op> ...,<ref. with reg1>,...
  4127. to
  4128. <op> ...,<ref1>,... }
  4129. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  4130. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4131. not(MatchInstruction(hp1,A_LEA,[])) then
  4132. begin
  4133. { find a reference which uses reg1 }
  4134. 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
  4135. ref:=0
  4136. 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
  4137. ref:=1
  4138. else
  4139. ref:=-1;
  4140. if (ref<>-1) and
  4141. { reg1 must be either the base or the index }
  4142. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4143. begin
  4144. { reg1 can be removed from the reference }
  4145. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4146. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4147. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4148. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4149. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4150. else
  4151. Internalerror(2019111201);
  4152. { check if the can insert all data of the lea into the second instruction }
  4153. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4154. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4155. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4156. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4157. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4158. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4159. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4160. {$ifdef x86_64}
  4161. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4162. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4163. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4164. )
  4165. {$endif x86_64}
  4166. then
  4167. begin
  4168. { reg1 might not used by the second instruction after it is remove from the reference }
  4169. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4170. begin
  4171. TransferUsedRegs(TmpUsedRegs);
  4172. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4173. { reg1 is not updated so it might not be used afterwards }
  4174. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4175. begin
  4176. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4177. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4178. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4179. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4180. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4181. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4182. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4183. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4184. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4185. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4186. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4187. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4188. RemoveCurrentP(p, hp1);
  4189. result:=true;
  4190. exit;
  4191. end
  4192. end;
  4193. end;
  4194. { recover }
  4195. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4196. end;
  4197. end;
  4198. end;
  4199. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4200. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4201. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4202. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4203. begin
  4204. { Check common LEA/LEA conditions }
  4205. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4206. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4207. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4208. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4209. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4210. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4211. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4212. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4213. (
  4214. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4215. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4216. ) and (
  4217. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4218. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4219. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4220. ) then
  4221. begin
  4222. { changes
  4223. lea (regX,scale), reg1
  4224. lea offset(reg1,reg1), reg1
  4225. to
  4226. lea offset(regX,scale*2), reg1
  4227. and
  4228. lea (regX,scale1), reg1
  4229. lea offset(reg1,scale2), reg1
  4230. to
  4231. lea offset(regX,scale1*scale2), reg1
  4232. ... so long as the final scale does not exceed 8
  4233. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4234. }
  4235. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4236. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4237. (
  4238. (
  4239. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4240. ) or (
  4241. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4242. (
  4243. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4244. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4245. )
  4246. )
  4247. ) and (
  4248. (
  4249. { lea (reg1,scale2), reg1 variant }
  4250. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4251. (
  4252. (
  4253. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4254. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4255. ) or (
  4256. { lea (regX,regX), reg1 variant }
  4257. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4258. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4259. )
  4260. )
  4261. ) or (
  4262. { lea (reg1,reg1), reg1 variant }
  4263. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4264. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4265. )
  4266. ) then
  4267. begin
  4268. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4269. { Make everything homogeneous to make calculations easier }
  4270. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4271. begin
  4272. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4273. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4274. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4275. else
  4276. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4277. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4278. end;
  4279. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4280. begin
  4281. { Just to prevent miscalculations }
  4282. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4283. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4284. else
  4285. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4286. end
  4287. else
  4288. begin
  4289. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4290. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4291. end;
  4292. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4293. RemoveCurrentP(p);
  4294. result:=true;
  4295. exit;
  4296. end
  4297. { changes
  4298. lea offset1(regX), reg1
  4299. lea offset2(reg1), reg1
  4300. to
  4301. lea offset1+offset2(regX), reg1 }
  4302. else if
  4303. (
  4304. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4305. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4306. ) or (
  4307. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4308. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4309. (
  4310. (
  4311. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4312. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4313. ) or (
  4314. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4315. (
  4316. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4317. (
  4318. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4319. (
  4320. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4321. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4322. )
  4323. )
  4324. )
  4325. )
  4326. )
  4327. ) then
  4328. begin
  4329. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4330. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4331. begin
  4332. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4333. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4334. { if the register is used as index and base, we have to increase for base as well
  4335. and adapt base }
  4336. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4337. begin
  4338. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4339. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4340. end;
  4341. end
  4342. else
  4343. begin
  4344. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4345. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4346. end;
  4347. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4348. begin
  4349. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4350. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4351. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4352. end;
  4353. RemoveCurrentP(p);
  4354. result:=true;
  4355. exit;
  4356. end;
  4357. end;
  4358. { Change:
  4359. leal/q $x(%reg1),%reg2
  4360. ...
  4361. shll/q $y,%reg2
  4362. To:
  4363. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4364. }
  4365. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4366. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4367. (taicpu(hp1).oper[0]^.val <= 3) then
  4368. begin
  4369. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4370. TransferUsedRegs(TmpUsedRegs);
  4371. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4372. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4373. if
  4374. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4375. (this works even if scalefactor is zero) }
  4376. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4377. { Ensure offset doesn't go out of bounds }
  4378. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4379. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4380. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4381. (
  4382. (
  4383. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4384. (
  4385. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4386. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4387. (
  4388. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4389. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4390. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4391. )
  4392. )
  4393. ) or (
  4394. (
  4395. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4396. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4397. ) and
  4398. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4399. )
  4400. ) then
  4401. begin
  4402. repeat
  4403. with taicpu(p).oper[0]^.ref^ do
  4404. begin
  4405. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4406. if index = base then
  4407. begin
  4408. if Multiple > 4 then
  4409. { Optimisation will no longer work because resultant
  4410. scale factor will exceed 8 }
  4411. Break;
  4412. base := NR_NO;
  4413. scalefactor := 2;
  4414. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4415. end
  4416. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4417. begin
  4418. { Scale factor only works on the index register }
  4419. index := base;
  4420. base := NR_NO;
  4421. end;
  4422. { For safety }
  4423. if scalefactor <= 1 then
  4424. begin
  4425. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4426. scalefactor := Multiple;
  4427. end
  4428. else
  4429. begin
  4430. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4431. scalefactor := scalefactor * Multiple;
  4432. end;
  4433. offset := offset * Multiple;
  4434. end;
  4435. RemoveInstruction(hp1);
  4436. Result := True;
  4437. Exit;
  4438. { This repeat..until loop exists for the benefit of Break }
  4439. until True;
  4440. end;
  4441. end;
  4442. end;
  4443. end;
  4444. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4445. var
  4446. hp1 : tai;
  4447. begin
  4448. DoSubAddOpt := False;
  4449. if taicpu(p).oper[0]^.typ <> top_const then
  4450. { Should have been confirmed before calling }
  4451. InternalError(2021102601);
  4452. if GetLastInstruction(p, hp1) and
  4453. (hp1.typ = ait_instruction) and
  4454. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4455. case taicpu(hp1).opcode Of
  4456. A_DEC:
  4457. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4458. begin
  4459. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4460. RemoveInstruction(hp1);
  4461. end;
  4462. A_SUB:
  4463. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4464. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4465. begin
  4466. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4467. RemoveInstruction(hp1);
  4468. end;
  4469. A_ADD:
  4470. begin
  4471. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4472. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4473. begin
  4474. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4475. RemoveInstruction(hp1);
  4476. if (taicpu(p).oper[0]^.val = 0) then
  4477. begin
  4478. hp1 := tai(p.next);
  4479. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4480. if not GetLastInstruction(hp1, p) then
  4481. p := hp1;
  4482. DoSubAddOpt := True;
  4483. end
  4484. end;
  4485. end;
  4486. else
  4487. ;
  4488. end;
  4489. end;
  4490. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  4491. var
  4492. hp1, hp2: tai;
  4493. ActiveReg: TRegister;
  4494. OldOffset: asizeint;
  4495. ThisConst: TCGInt;
  4496. function RegDeallocated: Boolean;
  4497. begin
  4498. TransferUsedRegs(TmpUsedRegs);
  4499. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4500. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4501. end;
  4502. begin
  4503. Result:=false;
  4504. hp1 := nil;
  4505. { replace
  4506. subX const,%reg1
  4507. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4508. dealloc %reg1
  4509. by
  4510. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  4511. }
  4512. if MatchOpType(taicpu(p),top_const,top_reg) then
  4513. begin
  4514. ActiveReg := taicpu(p).oper[1]^.reg;
  4515. { Ensures the entire register was updated }
  4516. if (taicpu(p).opsize >= S_L) and
  4517. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4518. MatchInstruction(hp1,A_LEA,[]) and
  4519. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4520. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4521. (
  4522. { Cover the case where the register in the reference is also the destination register }
  4523. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4524. (
  4525. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4526. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4527. RegDeallocated
  4528. )
  4529. ) then
  4530. begin
  4531. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4532. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4533. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4534. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4535. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4536. {$ifdef x86_64}
  4537. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4538. begin
  4539. { Overflow; abort }
  4540. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4541. end
  4542. else
  4543. {$endif x86_64}
  4544. begin
  4545. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  4546. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4547. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4548. RemoveCurrentP(p, hp1)
  4549. else
  4550. RemoveCurrentP(p);
  4551. result:=true;
  4552. Exit;
  4553. end;
  4554. end;
  4555. if (
  4556. { Save calling GetNextInstructionUsingReg again }
  4557. Assigned(hp1) or
  4558. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4559. ) and
  4560. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  4561. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4562. begin
  4563. if taicpu(hp1).oper[0]^.typ = top_const then
  4564. begin
  4565. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  4566. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  4567. Result := True;
  4568. { Handle any overflows }
  4569. case taicpu(p).opsize of
  4570. S_B:
  4571. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4572. S_W:
  4573. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4574. S_L:
  4575. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4576. {$ifdef x86_64}
  4577. S_Q:
  4578. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4579. { Overflow; abort }
  4580. Result := False
  4581. else
  4582. taicpu(p).oper[0]^.val := ThisConst;
  4583. {$endif x86_64}
  4584. else
  4585. InternalError(2021102610);
  4586. end;
  4587. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4588. if Result then
  4589. begin
  4590. if (taicpu(p).oper[0]^.val < 0) and
  4591. (
  4592. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4593. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4594. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4595. ) then
  4596. begin
  4597. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  4598. taicpu(p).opcode := A_SUB;
  4599. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4600. end
  4601. else
  4602. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  4603. RemoveInstruction(hp1);
  4604. end;
  4605. end
  4606. else
  4607. begin
  4608. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  4609. TransferUsedRegs(TmpUsedRegs);
  4610. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4611. hp2 := p;
  4612. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4613. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4614. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4615. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4616. begin
  4617. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  4618. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  4619. Asml.Remove(p);
  4620. Asml.InsertAfter(p, hp1);
  4621. p := hp1;
  4622. Result := True;
  4623. Exit;
  4624. end;
  4625. end;
  4626. end;
  4627. { * change "subl $2, %esp; pushw x" to "pushl x"}
  4628. { * change "sub/add const1, reg" or "dec reg" followed by
  4629. "sub const2, reg" to one "sub ..., reg" }
  4630. {$ifdef i386}
  4631. if (taicpu(p).oper[0]^.val = 2) and
  4632. (ActiveReg = NR_ESP) and
  4633. { Don't do the sub/push optimization if the sub }
  4634. { comes from setting up the stack frame (JM) }
  4635. (not(GetLastInstruction(p,hp1)) or
  4636. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  4637. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  4638. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  4639. begin
  4640. hp1 := tai(p.next);
  4641. while Assigned(hp1) and
  4642. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  4643. not RegReadByInstruction(NR_ESP,hp1) and
  4644. not RegModifiedByInstruction(NR_ESP,hp1) do
  4645. hp1 := tai(hp1.next);
  4646. if Assigned(hp1) and
  4647. MatchInstruction(hp1,A_PUSH,[S_W]) then
  4648. begin
  4649. taicpu(hp1).changeopsize(S_L);
  4650. if taicpu(hp1).oper[0]^.typ=top_reg then
  4651. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  4652. hp1 := tai(p.next);
  4653. RemoveCurrentp(p, hp1);
  4654. Result:=true;
  4655. exit;
  4656. end;
  4657. end;
  4658. {$endif i386}
  4659. if DoSubAddOpt(p) then
  4660. Result:=true;
  4661. end;
  4662. end;
  4663. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  4664. var
  4665. TmpBool1,TmpBool2 : Boolean;
  4666. tmpref : treference;
  4667. hp1,hp2: tai;
  4668. mask: tcgint;
  4669. begin
  4670. Result:=false;
  4671. { All these optimisations work on "shl/sal const,%reg" }
  4672. if not MatchOpType(taicpu(p),top_const,top_reg) then
  4673. Exit;
  4674. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4675. (taicpu(p).oper[0]^.val <= 3) then
  4676. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  4677. begin
  4678. { should we check the next instruction? }
  4679. TmpBool1 := True;
  4680. { have we found an add/sub which could be
  4681. integrated in the lea? }
  4682. TmpBool2 := False;
  4683. reference_reset(tmpref,2,[]);
  4684. TmpRef.index := taicpu(p).oper[1]^.reg;
  4685. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4686. while TmpBool1 and
  4687. GetNextInstruction(p, hp1) and
  4688. (tai(hp1).typ = ait_instruction) and
  4689. ((((taicpu(hp1).opcode = A_ADD) or
  4690. (taicpu(hp1).opcode = A_SUB)) and
  4691. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  4692. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  4693. (((taicpu(hp1).opcode = A_INC) or
  4694. (taicpu(hp1).opcode = A_DEC)) and
  4695. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4696. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  4697. ((taicpu(hp1).opcode = A_LEA) and
  4698. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4699. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  4700. (not GetNextInstruction(hp1,hp2) or
  4701. not instrReadsFlags(hp2)) Do
  4702. begin
  4703. TmpBool1 := False;
  4704. if taicpu(hp1).opcode=A_LEA then
  4705. begin
  4706. if (TmpRef.base = NR_NO) and
  4707. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  4708. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  4709. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  4710. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  4711. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  4712. begin
  4713. TmpBool1 := True;
  4714. TmpBool2 := True;
  4715. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  4716. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  4717. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  4718. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  4719. RemoveInstruction(hp1);
  4720. end
  4721. end
  4722. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  4723. begin
  4724. TmpBool1 := True;
  4725. TmpBool2 := True;
  4726. case taicpu(hp1).opcode of
  4727. A_ADD:
  4728. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4729. A_SUB:
  4730. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4731. else
  4732. internalerror(2019050536);
  4733. end;
  4734. RemoveInstruction(hp1);
  4735. end
  4736. else
  4737. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4738. (((taicpu(hp1).opcode = A_ADD) and
  4739. (TmpRef.base = NR_NO)) or
  4740. (taicpu(hp1).opcode = A_INC) or
  4741. (taicpu(hp1).opcode = A_DEC)) then
  4742. begin
  4743. TmpBool1 := True;
  4744. TmpBool2 := True;
  4745. case taicpu(hp1).opcode of
  4746. A_ADD:
  4747. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  4748. A_INC:
  4749. inc(TmpRef.offset);
  4750. A_DEC:
  4751. dec(TmpRef.offset);
  4752. else
  4753. internalerror(2019050535);
  4754. end;
  4755. RemoveInstruction(hp1);
  4756. end;
  4757. end;
  4758. if TmpBool2
  4759. {$ifndef x86_64}
  4760. or
  4761. ((current_settings.optimizecputype < cpu_Pentium2) and
  4762. (taicpu(p).oper[0]^.val <= 3) and
  4763. not(cs_opt_size in current_settings.optimizerswitches))
  4764. {$endif x86_64}
  4765. then
  4766. begin
  4767. if not(TmpBool2) and
  4768. (taicpu(p).oper[0]^.val=1) then
  4769. begin
  4770. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4771. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  4772. end
  4773. else
  4774. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  4775. taicpu(p).oper[1]^.reg);
  4776. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  4777. InsertLLItem(p.previous, p.next, hp1);
  4778. p.free;
  4779. p := hp1;
  4780. end;
  4781. end
  4782. {$ifndef x86_64}
  4783. else if (current_settings.optimizecputype < cpu_Pentium2) then
  4784. begin
  4785. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  4786. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  4787. (unlike shl, which is only Tairable in the U pipe) }
  4788. if taicpu(p).oper[0]^.val=1 then
  4789. begin
  4790. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4791. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  4792. InsertLLItem(p.previous, p.next, hp1);
  4793. p.free;
  4794. p := hp1;
  4795. end
  4796. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  4797. "shl $3, %reg" to "lea (,%reg,8), %reg }
  4798. else if (taicpu(p).opsize = S_L) and
  4799. (taicpu(p).oper[0]^.val<= 3) then
  4800. begin
  4801. reference_reset(tmpref,2,[]);
  4802. TmpRef.index := taicpu(p).oper[1]^.reg;
  4803. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4804. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  4805. InsertLLItem(p.previous, p.next, hp1);
  4806. p.free;
  4807. p := hp1;
  4808. end;
  4809. end
  4810. {$endif x86_64}
  4811. else if
  4812. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  4813. (
  4814. (
  4815. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  4816. SetAndTest(hp1, hp2)
  4817. {$ifdef x86_64}
  4818. ) or
  4819. (
  4820. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4821. GetNextInstruction(hp1, hp2) and
  4822. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  4823. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4824. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  4825. {$endif x86_64}
  4826. )
  4827. ) and
  4828. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  4829. begin
  4830. { Change:
  4831. shl x, %reg1
  4832. mov -(1<<x), %reg2
  4833. and %reg2, %reg1
  4834. Or:
  4835. shl x, %reg1
  4836. and -(1<<x), %reg1
  4837. To just:
  4838. shl x, %reg1
  4839. Since the and operation only zeroes bits that are already zero from the shl operation
  4840. }
  4841. case taicpu(p).oper[0]^.val of
  4842. 8:
  4843. mask:=$FFFFFFFFFFFFFF00;
  4844. 16:
  4845. mask:=$FFFFFFFFFFFF0000;
  4846. 32:
  4847. mask:=$FFFFFFFF00000000;
  4848. 63:
  4849. { Constant pre-calculated to prevent overflow errors with Int64 }
  4850. mask:=$8000000000000000;
  4851. else
  4852. begin
  4853. if taicpu(p).oper[0]^.val >= 64 then
  4854. { Shouldn't happen realistically, since the register
  4855. is guaranteed to be set to zero at this point }
  4856. mask := 0
  4857. else
  4858. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  4859. end;
  4860. end;
  4861. if taicpu(hp1).oper[0]^.val = mask then
  4862. begin
  4863. { Everything checks out, perform the optimisation, as long as
  4864. the FLAGS register isn't being used}
  4865. TransferUsedRegs(TmpUsedRegs);
  4866. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4867. {$ifdef x86_64}
  4868. if (hp1 <> hp2) then
  4869. begin
  4870. { "shl/mov/and" version }
  4871. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4872. { Don't do the optimisation if the FLAGS register is in use }
  4873. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  4874. begin
  4875. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  4876. { Don't remove the 'mov' instruction if its register is used elsewhere }
  4877. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  4878. begin
  4879. RemoveInstruction(hp1);
  4880. Result := True;
  4881. end;
  4882. { Only set Result to True if the 'mov' instruction was removed }
  4883. RemoveInstruction(hp2);
  4884. end;
  4885. end
  4886. else
  4887. {$endif x86_64}
  4888. begin
  4889. { "shl/and" version }
  4890. { Don't do the optimisation if the FLAGS register is in use }
  4891. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  4892. begin
  4893. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  4894. RemoveInstruction(hp1);
  4895. Result := True;
  4896. end;
  4897. end;
  4898. Exit;
  4899. end
  4900. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  4901. begin
  4902. { Even if the mask doesn't allow for its removal, we might be
  4903. able to optimise the mask for the "shl/and" version, which
  4904. may permit other peephole optimisations }
  4905. {$ifdef DEBUG_AOPTCPU}
  4906. mask := taicpu(hp1).oper[0]^.val and mask;
  4907. if taicpu(hp1).oper[0]^.val <> mask then
  4908. begin
  4909. DebugMsg(
  4910. SPeepholeOptimization +
  4911. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  4912. ' to $' + debug_tostr(mask) +
  4913. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  4914. taicpu(hp1).oper[0]^.val := mask;
  4915. end;
  4916. {$else DEBUG_AOPTCPU}
  4917. { If debugging is off, just set the operand even if it's the same }
  4918. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  4919. {$endif DEBUG_AOPTCPU}
  4920. end;
  4921. end;
  4922. {
  4923. change
  4924. shl/sal const,reg
  4925. <op> ...(...,reg,1),...
  4926. into
  4927. <op> ...(...,reg,1 shl const),...
  4928. if const in 1..3
  4929. }
  4930. if MatchOpType(taicpu(p), top_const, top_reg) and
  4931. (taicpu(p).oper[0]^.val in [1..3]) and
  4932. GetNextInstruction(p, hp1) and
  4933. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  4934. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  4935. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  4936. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  4937. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  4938. begin
  4939. TransferUsedRegs(TmpUsedRegs);
  4940. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4941. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4942. begin
  4943. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  4944. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  4945. RemoveCurrentP(p);
  4946. Result:=true;
  4947. end;
  4948. end;
  4949. end;
  4950. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  4951. var
  4952. CurrentRef: TReference;
  4953. FullReg: TRegister;
  4954. hp1, hp2: tai;
  4955. begin
  4956. Result := False;
  4957. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  4958. Exit;
  4959. { We assume you've checked if the operand is actually a reference by
  4960. this point. If it isn't, you'll most likely get an access violation }
  4961. CurrentRef := first_mov.oper[1]^.ref^;
  4962. { Memory must be aligned }
  4963. if (CurrentRef.offset mod 4) <> 0 then
  4964. Exit;
  4965. Inc(CurrentRef.offset);
  4966. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4967. if MatchOperand(second_mov.oper[0]^, 0) and
  4968. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  4969. GetNextInstruction(second_mov, hp1) and
  4970. (hp1.typ = ait_instruction) and
  4971. (taicpu(hp1).opcode = A_MOV) and
  4972. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4973. (taicpu(hp1).oper[0]^.val = 0) then
  4974. begin
  4975. Inc(CurrentRef.offset);
  4976. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  4977. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  4978. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  4979. begin
  4980. case taicpu(hp1).opsize of
  4981. S_B:
  4982. if GetNextInstruction(hp1, hp2) and
  4983. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  4984. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4985. (taicpu(hp2).oper[0]^.val = 0) then
  4986. begin
  4987. Inc(CurrentRef.offset);
  4988. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4989. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  4990. (taicpu(hp2).opsize = S_B) then
  4991. begin
  4992. RemoveInstruction(hp1);
  4993. RemoveInstruction(hp2);
  4994. first_mov.opsize := S_L;
  4995. if first_mov.oper[0]^.typ = top_reg then
  4996. begin
  4997. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  4998. { Reuse second_mov as a MOVZX instruction }
  4999. second_mov.opcode := A_MOVZX;
  5000. second_mov.opsize := S_BL;
  5001. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5002. second_mov.loadreg(1, FullReg);
  5003. first_mov.oper[0]^.reg := FullReg;
  5004. asml.Remove(second_mov);
  5005. asml.InsertBefore(second_mov, first_mov);
  5006. end
  5007. else
  5008. { It's a value }
  5009. begin
  5010. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5011. RemoveInstruction(second_mov);
  5012. end;
  5013. Result := True;
  5014. Exit;
  5015. end;
  5016. end;
  5017. S_W:
  5018. begin
  5019. RemoveInstruction(hp1);
  5020. first_mov.opsize := S_L;
  5021. if first_mov.oper[0]^.typ = top_reg then
  5022. begin
  5023. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5024. { Reuse second_mov as a MOVZX instruction }
  5025. second_mov.opcode := A_MOVZX;
  5026. second_mov.opsize := S_BL;
  5027. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5028. second_mov.loadreg(1, FullReg);
  5029. first_mov.oper[0]^.reg := FullReg;
  5030. asml.Remove(second_mov);
  5031. asml.InsertBefore(second_mov, first_mov);
  5032. end
  5033. else
  5034. { It's a value }
  5035. begin
  5036. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5037. RemoveInstruction(second_mov);
  5038. end;
  5039. Result := True;
  5040. Exit;
  5041. end;
  5042. else
  5043. ;
  5044. end;
  5045. end;
  5046. end;
  5047. end;
  5048. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5049. { returns true if a "continue" should be done after this optimization }
  5050. var
  5051. hp1, hp2: tai;
  5052. begin
  5053. Result := false;
  5054. if MatchOpType(taicpu(p),top_ref) and
  5055. GetNextInstruction(p, hp1) and
  5056. (hp1.typ = ait_instruction) and
  5057. (((taicpu(hp1).opcode = A_FLD) and
  5058. (taicpu(p).opcode = A_FSTP)) or
  5059. ((taicpu(p).opcode = A_FISTP) and
  5060. (taicpu(hp1).opcode = A_FILD))) and
  5061. MatchOpType(taicpu(hp1),top_ref) and
  5062. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5063. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5064. begin
  5065. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5066. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5067. GetNextInstruction(hp1, hp2) and
  5068. (hp2.typ = ait_instruction) and
  5069. IsExitCode(hp2) and
  5070. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5071. not(assigned(current_procinfo.procdef.funcretsym) and
  5072. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5073. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5074. begin
  5075. RemoveInstruction(hp1);
  5076. RemoveCurrentP(p, hp2);
  5077. RemoveLastDeallocForFuncRes(p);
  5078. Result := true;
  5079. end
  5080. else
  5081. { we can do this only in fast math mode as fstp is rounding ...
  5082. ... still disabled as it breaks the compiler and/or rtl }
  5083. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5084. { ... or if another fstp equal to the first one follows }
  5085. (GetNextInstruction(hp1,hp2) and
  5086. (hp2.typ = ait_instruction) and
  5087. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5088. (taicpu(p).opsize=taicpu(hp2).opsize))
  5089. ) and
  5090. { fst can't store an extended/comp value }
  5091. (taicpu(p).opsize <> S_FX) and
  5092. (taicpu(p).opsize <> S_IQ) then
  5093. begin
  5094. if (taicpu(p).opcode = A_FSTP) then
  5095. taicpu(p).opcode := A_FST
  5096. else
  5097. taicpu(p).opcode := A_FIST;
  5098. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5099. RemoveInstruction(hp1);
  5100. end;
  5101. end;
  5102. end;
  5103. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5104. var
  5105. hp1, hp2: tai;
  5106. begin
  5107. result:=false;
  5108. if MatchOpType(taicpu(p),top_reg) and
  5109. GetNextInstruction(p, hp1) and
  5110. (hp1.typ = Ait_Instruction) and
  5111. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5112. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5113. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5114. { change to
  5115. fld reg fxxx reg,st
  5116. fxxxp st, st1 (hp1)
  5117. Remark: non commutative operations must be reversed!
  5118. }
  5119. begin
  5120. case taicpu(hp1).opcode Of
  5121. A_FMULP,A_FADDP,
  5122. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5123. begin
  5124. case taicpu(hp1).opcode Of
  5125. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5126. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5127. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5128. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5129. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5130. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5131. else
  5132. internalerror(2019050534);
  5133. end;
  5134. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5135. taicpu(hp1).oper[1]^.reg := NR_ST;
  5136. RemoveCurrentP(p, hp1);
  5137. Result:=true;
  5138. exit;
  5139. end;
  5140. else
  5141. ;
  5142. end;
  5143. end
  5144. else
  5145. if MatchOpType(taicpu(p),top_ref) and
  5146. GetNextInstruction(p, hp2) and
  5147. (hp2.typ = Ait_Instruction) and
  5148. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5149. (taicpu(p).opsize in [S_FS, S_FL]) and
  5150. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5151. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5152. if GetLastInstruction(p, hp1) and
  5153. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5154. MatchOpType(taicpu(hp1),top_ref) and
  5155. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5156. if ((taicpu(hp2).opcode = A_FMULP) or
  5157. (taicpu(hp2).opcode = A_FADDP)) then
  5158. { change to
  5159. fld/fst mem1 (hp1) fld/fst mem1
  5160. fld mem1 (p) fadd/
  5161. faddp/ fmul st, st
  5162. fmulp st, st1 (hp2) }
  5163. begin
  5164. RemoveCurrentP(p, hp1);
  5165. if (taicpu(hp2).opcode = A_FADDP) then
  5166. taicpu(hp2).opcode := A_FADD
  5167. else
  5168. taicpu(hp2).opcode := A_FMUL;
  5169. taicpu(hp2).oper[1]^.reg := NR_ST;
  5170. end
  5171. else
  5172. { change to
  5173. fld/fst mem1 (hp1) fld/fst mem1
  5174. fld mem1 (p) fld st}
  5175. begin
  5176. taicpu(p).changeopsize(S_FL);
  5177. taicpu(p).loadreg(0,NR_ST);
  5178. end
  5179. else
  5180. begin
  5181. case taicpu(hp2).opcode Of
  5182. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5183. { change to
  5184. fld/fst mem1 (hp1) fld/fst mem1
  5185. fld mem2 (p) fxxx mem2
  5186. fxxxp st, st1 (hp2) }
  5187. begin
  5188. case taicpu(hp2).opcode Of
  5189. A_FADDP: taicpu(p).opcode := A_FADD;
  5190. A_FMULP: taicpu(p).opcode := A_FMUL;
  5191. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5192. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5193. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5194. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5195. else
  5196. internalerror(2019050533);
  5197. end;
  5198. RemoveInstruction(hp2);
  5199. end
  5200. else
  5201. ;
  5202. end
  5203. end
  5204. end;
  5205. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5206. begin
  5207. Result := condition_in(cond1, cond2) or
  5208. { Not strictly subsets due to the actual flags checked, but because we're
  5209. comparing integers, E is a subset of AE and GE and their aliases }
  5210. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5211. end;
  5212. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5213. var
  5214. v: TCGInt;
  5215. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5216. FirstMatch: Boolean;
  5217. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5218. begin
  5219. Result:=false;
  5220. { All these optimisations need a next instruction }
  5221. if not GetNextInstruction(p, hp1) then
  5222. Exit;
  5223. { Search for:
  5224. cmp ###,###
  5225. j(c1) @lbl1
  5226. ...
  5227. @lbl:
  5228. cmp ###.### (same comparison as above)
  5229. j(c2) @lbl2
  5230. If c1 is a subset of c2, change to:
  5231. cmp ###,###
  5232. j(c2) @lbl2
  5233. (@lbl1 may become a dead label as a result)
  5234. }
  5235. { Also handle cases where there are multiple jumps in a row }
  5236. p_jump := hp1;
  5237. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5238. begin
  5239. if IsJumpToLabel(taicpu(p_jump)) then
  5240. begin
  5241. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5242. p_label := nil;
  5243. if Assigned(JumpLabel) then
  5244. p_label := getlabelwithsym(JumpLabel);
  5245. if Assigned(p_label) and
  5246. GetNextInstruction(p_label, p_dist) and
  5247. MatchInstruction(p_dist, A_CMP, []) and
  5248. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5249. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5250. GetNextInstruction(p_dist, hp1_dist) and
  5251. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5252. begin
  5253. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5254. if JumpLabel = JumpLabel_dist then
  5255. { This is an infinite loop }
  5256. Exit;
  5257. { Best optimisation when the first condition is a subset (or equal) of the second }
  5258. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5259. begin
  5260. { Any registers used here will already be allocated }
  5261. if Assigned(JumpLabel_dist) then
  5262. JumpLabel_dist.IncRefs;
  5263. if Assigned(JumpLabel) then
  5264. JumpLabel.DecRefs;
  5265. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5266. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5267. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5268. Result := True;
  5269. { Don't exit yet. Since p and p_jump haven't actually been
  5270. removed, we can check for more on this iteration }
  5271. end
  5272. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5273. GetNextInstruction(hp1_dist, hp1_label) and
  5274. SkipAligns(hp1_label, hp1_label) and
  5275. (hp1_label.typ = ait_label) then
  5276. begin
  5277. JumpLabel_far := tai_label(hp1_label).labsym;
  5278. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5279. { This is an infinite loop }
  5280. Exit;
  5281. if Assigned(JumpLabel_far) then
  5282. begin
  5283. { In this situation, if the first jump branches, the second one will never,
  5284. branch so change the destination label to after the second jump }
  5285. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5286. if Assigned(JumpLabel) then
  5287. JumpLabel.DecRefs;
  5288. JumpLabel_far.IncRefs;
  5289. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5290. Result := True;
  5291. { Don't exit yet. Since p and p_jump haven't actually been
  5292. removed, we can check for more on this iteration }
  5293. Continue;
  5294. end;
  5295. end;
  5296. end;
  5297. end;
  5298. { Search for:
  5299. cmp ###,###
  5300. j(c1) @lbl1
  5301. cmp ###,### (same as first)
  5302. Remove second cmp
  5303. }
  5304. if GetNextInstruction(p_jump, hp2) and
  5305. (
  5306. (
  5307. MatchInstruction(hp2, A_CMP, []) and
  5308. (
  5309. (
  5310. MatchOpType(taicpu(p), top_const, top_reg) and
  5311. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5312. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  5313. ) or (
  5314. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5315. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5316. )
  5317. )
  5318. ) or (
  5319. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5320. MatchOperand(taicpu(p).oper[0]^, 0) and
  5321. (taicpu(p).oper[1]^.typ = top_reg) and
  5322. MatchInstruction(hp2, A_TEST, []) and
  5323. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5324. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5325. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  5326. )
  5327. ) then
  5328. begin
  5329. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5330. RemoveInstruction(hp2);
  5331. Result := True;
  5332. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5333. end;
  5334. GetNextInstruction(p_jump, p_jump);
  5335. end;
  5336. if taicpu(p).oper[0]^.typ = top_const then
  5337. begin
  5338. if (taicpu(p).oper[0]^.val = 0) and
  5339. (taicpu(p).oper[1]^.typ = top_reg) and
  5340. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  5341. begin
  5342. hp2 := p;
  5343. FirstMatch := True;
  5344. { When dealing with "cmp $0,%reg", only ZF and SF contain
  5345. anything meaningful once it's converted to "test %reg,%reg";
  5346. additionally, some jumps will always (or never) branch, so
  5347. evaluate every jump immediately following the
  5348. comparison, optimising the conditions if possible.
  5349. Similarly with SETcc... those that are always set to 0 or 1
  5350. are changed to MOV instructions }
  5351. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  5352. (
  5353. GetNextInstruction(hp2, hp1) and
  5354. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  5355. ) do
  5356. begin
  5357. FirstMatch := False;
  5358. case taicpu(hp1).condition of
  5359. C_B, C_C, C_NAE, C_O:
  5360. { For B/NAE:
  5361. Will never branch since an unsigned integer can never be below zero
  5362. For C/O:
  5363. Result cannot overflow because 0 is being subtracted
  5364. }
  5365. begin
  5366. if taicpu(hp1).opcode = A_Jcc then
  5367. begin
  5368. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  5369. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  5370. RemoveInstruction(hp1);
  5371. { Since hp1 was deleted, hp2 must not be updated }
  5372. Continue;
  5373. end
  5374. else
  5375. begin
  5376. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  5377. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  5378. taicpu(hp1).opcode := A_MOV;
  5379. taicpu(hp1).ops := 2;
  5380. taicpu(hp1).condition := C_None;
  5381. taicpu(hp1).opsize := S_B;
  5382. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5383. taicpu(hp1).loadconst(0, 0);
  5384. end;
  5385. end;
  5386. C_BE, C_NA:
  5387. begin
  5388. { Will only branch if equal to zero }
  5389. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  5390. taicpu(hp1).condition := C_E;
  5391. end;
  5392. C_A, C_NBE:
  5393. begin
  5394. { Will only branch if not equal to zero }
  5395. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  5396. taicpu(hp1).condition := C_NE;
  5397. end;
  5398. C_AE, C_NB, C_NC, C_NO:
  5399. begin
  5400. { Will always branch }
  5401. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  5402. if taicpu(hp1).opcode = A_Jcc then
  5403. begin
  5404. MakeUnconditional(taicpu(hp1));
  5405. { Any jumps/set that follow will now be dead code }
  5406. RemoveDeadCodeAfterJump(taicpu(hp1));
  5407. Break;
  5408. end
  5409. else
  5410. begin
  5411. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  5412. taicpu(hp1).opcode := A_MOV;
  5413. taicpu(hp1).ops := 2;
  5414. taicpu(hp1).condition := C_None;
  5415. taicpu(hp1).opsize := S_B;
  5416. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5417. taicpu(hp1).loadconst(0, 1);
  5418. end;
  5419. end;
  5420. C_None:
  5421. InternalError(2020012201);
  5422. C_P, C_PE, C_NP, C_PO:
  5423. { We can't handle parity checks and they should never be generated
  5424. after a general-purpose CMP (it's used in some floating-point
  5425. comparisons that don't use CMP) }
  5426. InternalError(2020012202);
  5427. else
  5428. { Zero/Equality, Sign, their complements and all of the
  5429. signed comparisons do not need to be converted };
  5430. end;
  5431. hp2 := hp1;
  5432. end;
  5433. { Convert the instruction to a TEST }
  5434. taicpu(p).opcode := A_TEST;
  5435. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5436. Result := True;
  5437. Exit;
  5438. end
  5439. else if (taicpu(p).oper[0]^.val = 1) and
  5440. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5441. (taicpu(hp1).condition in [C_L, C_NGE]) then
  5442. begin
  5443. { Convert; To:
  5444. cmp $1,r/m cmp $0,r/m
  5445. jl @lbl jle @lbl
  5446. }
  5447. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  5448. taicpu(p).oper[0]^.val := 0;
  5449. taicpu(hp1).condition := C_LE;
  5450. { If the instruction is now "cmp $0,%reg", convert it to a
  5451. TEST (and effectively do the work of the "cmp $0,%reg" in
  5452. the block above)
  5453. If it's a reference, we can get away with not setting
  5454. Result to True because he haven't evaluated the jump
  5455. in this pass yet.
  5456. }
  5457. if (taicpu(p).oper[1]^.typ = top_reg) then
  5458. begin
  5459. taicpu(p).opcode := A_TEST;
  5460. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5461. Result := True;
  5462. end;
  5463. Exit;
  5464. end
  5465. else if (taicpu(p).oper[1]^.typ = top_reg)
  5466. {$ifdef x86_64}
  5467. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  5468. {$endif x86_64}
  5469. then
  5470. begin
  5471. { cmp register,$8000 neg register
  5472. je target --> jo target
  5473. .... only if register is deallocated before jump.}
  5474. case Taicpu(p).opsize of
  5475. S_B: v:=$80;
  5476. S_W: v:=$8000;
  5477. S_L: v:=qword($80000000);
  5478. else
  5479. internalerror(2013112905);
  5480. end;
  5481. if (taicpu(p).oper[0]^.val=v) and
  5482. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5483. (Taicpu(hp1).condition in [C_E,C_NE]) then
  5484. begin
  5485. TransferUsedRegs(TmpUsedRegs);
  5486. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  5487. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  5488. begin
  5489. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  5490. Taicpu(p).opcode:=A_NEG;
  5491. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  5492. Taicpu(p).clearop(1);
  5493. Taicpu(p).ops:=1;
  5494. if Taicpu(hp1).condition=C_E then
  5495. Taicpu(hp1).condition:=C_O
  5496. else
  5497. Taicpu(hp1).condition:=C_NO;
  5498. Result:=true;
  5499. exit;
  5500. end;
  5501. end;
  5502. end;
  5503. end;
  5504. if TrySwapMovCmp(p, hp1) then
  5505. begin
  5506. Result := True;
  5507. Exit;
  5508. end;
  5509. end;
  5510. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  5511. var
  5512. hp1: tai;
  5513. begin
  5514. {
  5515. remove the second (v)pxor from
  5516. pxor reg,reg
  5517. ...
  5518. pxor reg,reg
  5519. }
  5520. Result:=false;
  5521. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5522. MatchOpType(taicpu(p),top_reg,top_reg) and
  5523. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5524. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5525. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5526. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  5527. begin
  5528. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  5529. RemoveInstruction(hp1);
  5530. Result:=true;
  5531. Exit;
  5532. end
  5533. {
  5534. replace
  5535. pxor reg1,reg1
  5536. movapd/s reg1,reg2
  5537. dealloc reg1
  5538. by
  5539. pxor reg2,reg2
  5540. }
  5541. else if GetNextInstruction(p,hp1) and
  5542. { we mix single and double opperations here because we assume that the compiler
  5543. generates vmovapd only after double operations and vmovaps only after single operations }
  5544. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5545. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5546. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5547. (taicpu(p).oper[0]^.typ=top_reg) then
  5548. begin
  5549. TransferUsedRegs(TmpUsedRegs);
  5550. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5551. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5552. begin
  5553. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  5554. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5555. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  5556. RemoveInstruction(hp1);
  5557. result:=true;
  5558. end;
  5559. end;
  5560. end;
  5561. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  5562. var
  5563. hp1: tai;
  5564. begin
  5565. {
  5566. remove the second (v)pxor from
  5567. (v)pxor reg,reg
  5568. ...
  5569. (v)pxor reg,reg
  5570. }
  5571. Result:=false;
  5572. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  5573. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  5574. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5575. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5576. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5577. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  5578. begin
  5579. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  5580. RemoveInstruction(hp1);
  5581. Result:=true;
  5582. Exit;
  5583. end
  5584. else
  5585. Result:=OptPass1VOP(p);
  5586. end;
  5587. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  5588. var
  5589. hp1 : tai;
  5590. begin
  5591. result:=false;
  5592. { replace
  5593. IMul const,%mreg1,%mreg2
  5594. Mov %reg2,%mreg3
  5595. dealloc %mreg3
  5596. by
  5597. Imul const,%mreg1,%mreg23
  5598. }
  5599. if (taicpu(p).ops=3) and
  5600. GetNextInstruction(p,hp1) and
  5601. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5602. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5603. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5604. begin
  5605. TransferUsedRegs(TmpUsedRegs);
  5606. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5607. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5608. begin
  5609. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5610. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  5611. RemoveInstruction(hp1);
  5612. result:=true;
  5613. end;
  5614. end;
  5615. end;
  5616. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  5617. var
  5618. hp1 : tai;
  5619. begin
  5620. result:=false;
  5621. { replace
  5622. IMul %reg0,%reg1,%reg2
  5623. Mov %reg2,%reg3
  5624. dealloc %reg2
  5625. by
  5626. Imul %reg0,%reg1,%reg3
  5627. }
  5628. if GetNextInstruction(p,hp1) and
  5629. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5630. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5631. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5632. begin
  5633. TransferUsedRegs(TmpUsedRegs);
  5634. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5635. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5636. begin
  5637. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5638. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  5639. RemoveInstruction(hp1);
  5640. result:=true;
  5641. end;
  5642. end;
  5643. end;
  5644. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  5645. var
  5646. hp1: tai;
  5647. begin
  5648. Result:=false;
  5649. { get rid of
  5650. (v)cvtss2sd reg0,<reg1,>reg2
  5651. (v)cvtss2sd reg2,<reg2,>reg0
  5652. }
  5653. if GetNextInstruction(p,hp1) and
  5654. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  5655. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  5656. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  5657. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  5658. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  5659. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  5660. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5661. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  5662. )
  5663. ) then
  5664. begin
  5665. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  5666. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  5667. begin
  5668. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  5669. RemoveCurrentP(p);
  5670. RemoveInstruction(hp1);
  5671. end
  5672. else
  5673. begin
  5674. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  5675. if taicpu(hp1).opcode=A_CVTSD2SS then
  5676. begin
  5677. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  5678. taicpu(p).opcode:=A_MOVAPS;
  5679. end
  5680. else
  5681. begin
  5682. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  5683. taicpu(p).opcode:=A_VMOVAPS;
  5684. end;
  5685. taicpu(p).ops:=2;
  5686. RemoveInstruction(hp1);
  5687. end;
  5688. Result:=true;
  5689. Exit;
  5690. end;
  5691. end;
  5692. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  5693. var
  5694. hp1, hp2, hp3, hp4, hp5: tai;
  5695. ThisReg: TRegister;
  5696. begin
  5697. Result := False;
  5698. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  5699. Exit;
  5700. {
  5701. convert
  5702. j<c> .L1
  5703. mov 1,reg
  5704. jmp .L2
  5705. .L1
  5706. mov 0,reg
  5707. .L2
  5708. into
  5709. mov 0,reg
  5710. set<not(c)> reg
  5711. take care of alignment and that the mov 0,reg is not converted into a xor as this
  5712. would destroy the flag contents
  5713. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  5714. executed at the same time as a previous comparison.
  5715. set<not(c)> reg
  5716. movzx reg, reg
  5717. }
  5718. if MatchInstruction(hp1,A_MOV,[]) and
  5719. (taicpu(hp1).oper[0]^.typ = top_const) and
  5720. (
  5721. (
  5722. (taicpu(hp1).oper[1]^.typ = top_reg)
  5723. {$ifdef i386}
  5724. { Under i386, ESI, EDI, EBP and ESP
  5725. don't have an 8-bit representation }
  5726. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5727. {$endif i386}
  5728. ) or (
  5729. {$ifdef i386}
  5730. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  5731. {$endif i386}
  5732. (taicpu(hp1).opsize = S_B)
  5733. )
  5734. ) and
  5735. GetNextInstruction(hp1,hp2) and
  5736. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  5737. GetNextInstruction(hp2,hp3) and
  5738. SkipAligns(hp3, hp3) and
  5739. (hp3.typ=ait_label) and
  5740. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  5741. GetNextInstruction(hp3,hp4) and
  5742. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  5743. (taicpu(hp4).oper[0]^.typ = top_const) and
  5744. (
  5745. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  5746. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  5747. ) and
  5748. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  5749. GetNextInstruction(hp4,hp5) and
  5750. SkipAligns(hp5, hp5) and
  5751. (hp5.typ=ait_label) and
  5752. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  5753. begin
  5754. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5755. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5756. tai_label(hp3).labsym.DecRefs;
  5757. { If this isn't the only reference to the middle label, we can
  5758. still make a saving - only that the first jump and everything
  5759. that follows will remain. }
  5760. if (tai_label(hp3).labsym.getrefs = 0) then
  5761. begin
  5762. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5763. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  5764. else
  5765. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  5766. { remove jump, first label and second MOV (also catching any aligns) }
  5767. repeat
  5768. if not GetNextInstruction(hp2, hp3) then
  5769. InternalError(2021040810);
  5770. RemoveInstruction(hp2);
  5771. hp2 := hp3;
  5772. until hp2 = hp5;
  5773. { Don't decrement reference count before the removal loop
  5774. above, otherwise GetNextInstruction won't stop on the
  5775. the label }
  5776. tai_label(hp5).labsym.DecRefs;
  5777. end
  5778. else
  5779. begin
  5780. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5781. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  5782. else
  5783. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  5784. end;
  5785. taicpu(p).opcode:=A_SETcc;
  5786. taicpu(p).opsize:=S_B;
  5787. taicpu(p).is_jmp:=False;
  5788. if taicpu(hp1).opsize=S_B then
  5789. begin
  5790. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  5791. if taicpu(hp1).oper[1]^.typ = top_reg then
  5792. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  5793. RemoveInstruction(hp1);
  5794. end
  5795. else
  5796. begin
  5797. { Will be a register because the size can't be S_B otherwise }
  5798. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  5799. taicpu(p).loadreg(0, ThisReg);
  5800. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  5801. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  5802. begin
  5803. case taicpu(hp1).opsize of
  5804. S_W:
  5805. taicpu(hp1).opsize := S_BW;
  5806. S_L:
  5807. taicpu(hp1).opsize := S_BL;
  5808. {$ifdef x86_64}
  5809. S_Q:
  5810. begin
  5811. taicpu(hp1).opsize := S_BL;
  5812. { Change the destination register to 32-bit }
  5813. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  5814. end;
  5815. {$endif x86_64}
  5816. else
  5817. InternalError(2021040820);
  5818. end;
  5819. taicpu(hp1).opcode := A_MOVZX;
  5820. taicpu(hp1).loadreg(0, ThisReg);
  5821. end
  5822. else
  5823. begin
  5824. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  5825. { hp1 is already a MOV instruction with the correct register }
  5826. taicpu(hp1).loadconst(0, 0);
  5827. { Inserting it right before p will guarantee that the flags are also tracked }
  5828. asml.Remove(hp1);
  5829. asml.InsertBefore(hp1, p);
  5830. end;
  5831. end;
  5832. Result:=true;
  5833. exit;
  5834. end
  5835. end;
  5836. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  5837. var
  5838. hp1, hp2, hp3: tai;
  5839. SourceRef, TargetRef: TReference;
  5840. CurrentReg: TRegister;
  5841. begin
  5842. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  5843. if not UseAVX then
  5844. InternalError(2021100501);
  5845. Result := False;
  5846. { Look for the following to simplify:
  5847. vmovdqa/u x(mem1), %xmmreg
  5848. vmovdqa/u %xmmreg, y(mem2)
  5849. vmovdqa/u x+16(mem1), %xmmreg
  5850. vmovdqa/u %xmmreg, y+16(mem2)
  5851. Change to:
  5852. vmovdqa/u x(mem1), %ymmreg
  5853. vmovdqa/u %ymmreg, y(mem2)
  5854. vpxor %ymmreg, %ymmreg, %ymmreg
  5855. ( The VPXOR instruction is to zero the upper half, thus removing the
  5856. need to call the potentially expensive VZEROUPPER instruction. Other
  5857. peephole optimisations can remove VPXOR if it's unnecessary )
  5858. }
  5859. TransferUsedRegs(TmpUsedRegs);
  5860. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5861. { NOTE: In the optimisations below, if the references dictate that an
  5862. aligned move is possible (i.e. VMOVDQA), the existing instructions
  5863. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  5864. if (taicpu(p).opsize = S_XMM) and
  5865. MatchOpType(taicpu(p), top_ref, top_reg) and
  5866. GetNextInstruction(p, hp1) and
  5867. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  5868. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  5869. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5870. begin
  5871. SourceRef := taicpu(p).oper[0]^.ref^;
  5872. TargetRef := taicpu(hp1).oper[1]^.ref^;
  5873. if GetNextInstruction(hp1, hp2) and
  5874. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  5875. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  5876. begin
  5877. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  5878. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5879. Inc(SourceRef.offset, 16);
  5880. { Reuse the register in the first block move }
  5881. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  5882. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  5883. begin
  5884. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5885. Inc(TargetRef.offset, 16);
  5886. if GetNextInstruction(hp2, hp3) and
  5887. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  5888. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  5889. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  5890. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  5891. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  5892. begin
  5893. { Update the register tracking to the new size }
  5894. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  5895. { Remember that the offsets are 16 ahead }
  5896. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  5897. if not (
  5898. ((SourceRef.offset mod 32) = 16) and
  5899. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  5900. ) then
  5901. taicpu(p).opcode := A_VMOVDQU;
  5902. taicpu(p).opsize := S_YMM;
  5903. taicpu(p).oper[1]^.reg := CurrentReg;
  5904. if not (
  5905. ((TargetRef.offset mod 32) = 16) and
  5906. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  5907. ) then
  5908. taicpu(hp1).opcode := A_VMOVDQU;
  5909. taicpu(hp1).opsize := S_YMM;
  5910. taicpu(hp1).oper[0]^.reg := CurrentReg;
  5911. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  5912. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  5913. if (pi_uses_ymm in current_procinfo.flags) then
  5914. RemoveInstruction(hp2)
  5915. else
  5916. begin
  5917. taicpu(hp2).opcode := A_VPXOR;
  5918. taicpu(hp2).opsize := S_YMM;
  5919. taicpu(hp2).loadreg(0, CurrentReg);
  5920. taicpu(hp2).loadreg(1, CurrentReg);
  5921. taicpu(hp2).loadreg(2, CurrentReg);
  5922. taicpu(hp2).ops := 3;
  5923. end;
  5924. RemoveInstruction(hp3);
  5925. Result := True;
  5926. Exit;
  5927. end;
  5928. end
  5929. else
  5930. begin
  5931. { See if the next references are 16 less rather than 16 greater }
  5932. Dec(SourceRef.offset, 32); { -16 the other way }
  5933. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  5934. begin
  5935. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5936. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  5937. if GetNextInstruction(hp2, hp3) and
  5938. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  5939. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  5940. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  5941. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  5942. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  5943. begin
  5944. { Update the register tracking to the new size }
  5945. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  5946. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  5947. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  5948. if not(
  5949. ((SourceRef.offset mod 32) = 0) and
  5950. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  5951. ) then
  5952. taicpu(hp2).opcode := A_VMOVDQU;
  5953. taicpu(hp2).opsize := S_YMM;
  5954. taicpu(hp2).oper[1]^.reg := CurrentReg;
  5955. if not (
  5956. ((TargetRef.offset mod 32) = 0) and
  5957. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  5958. ) then
  5959. taicpu(hp3).opcode := A_VMOVDQU;
  5960. taicpu(hp3).opsize := S_YMM;
  5961. taicpu(hp3).oper[0]^.reg := CurrentReg;
  5962. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  5963. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  5964. if (pi_uses_ymm in current_procinfo.flags) then
  5965. RemoveInstruction(hp1)
  5966. else
  5967. begin
  5968. taicpu(hp1).opcode := A_VPXOR;
  5969. taicpu(hp1).opsize := S_YMM;
  5970. taicpu(hp1).loadreg(0, CurrentReg);
  5971. taicpu(hp1).loadreg(1, CurrentReg);
  5972. taicpu(hp1).loadreg(2, CurrentReg);
  5973. taicpu(hp1).ops := 3;
  5974. Asml.Remove(hp1);
  5975. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  5976. end;
  5977. RemoveCurrentP(p, hp2);
  5978. Result := True;
  5979. Exit;
  5980. end;
  5981. end;
  5982. end;
  5983. end;
  5984. end;
  5985. end;
  5986. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  5987. var
  5988. hp2, hp3, first_assignment: tai;
  5989. IncCount, OperIdx: Integer;
  5990. OrigLabel: TAsmLabel;
  5991. begin
  5992. Count := 0;
  5993. Result := False;
  5994. first_assignment := nil;
  5995. if (LoopCount >= 20) then
  5996. begin
  5997. { Guard against infinite loops }
  5998. Exit;
  5999. end;
  6000. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6001. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6002. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6003. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6004. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6005. Exit;
  6006. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6007. {
  6008. change
  6009. jmp .L1
  6010. ...
  6011. .L1:
  6012. mov ##, ## ( multiple movs possible )
  6013. jmp/ret
  6014. into
  6015. mov ##, ##
  6016. jmp/ret
  6017. }
  6018. if not Assigned(hp1) then
  6019. begin
  6020. hp1 := GetLabelWithSym(OrigLabel);
  6021. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6022. Exit;
  6023. end;
  6024. hp2 := hp1;
  6025. while Assigned(hp2) do
  6026. begin
  6027. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6028. SkipLabels(hp2,hp2);
  6029. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6030. Break;
  6031. case taicpu(hp2).opcode of
  6032. A_MOVSS:
  6033. begin
  6034. if taicpu(hp2).ops = 0 then
  6035. { Wrong MOVSS }
  6036. Break;
  6037. Inc(Count);
  6038. if Count >= 5 then
  6039. { Too many to be worthwhile }
  6040. Break;
  6041. GetNextInstruction(hp2, hp2);
  6042. Continue;
  6043. end;
  6044. A_MOV,
  6045. A_MOVD,
  6046. A_MOVQ,
  6047. A_MOVSX,
  6048. {$ifdef x86_64}
  6049. A_MOVSXD,
  6050. {$endif x86_64}
  6051. A_MOVZX,
  6052. A_MOVAPS,
  6053. A_MOVUPS,
  6054. A_MOVSD,
  6055. A_MOVAPD,
  6056. A_MOVUPD,
  6057. A_MOVDQA,
  6058. A_MOVDQU,
  6059. A_VMOVSS,
  6060. A_VMOVAPS,
  6061. A_VMOVUPS,
  6062. A_VMOVSD,
  6063. A_VMOVAPD,
  6064. A_VMOVUPD,
  6065. A_VMOVDQA,
  6066. A_VMOVDQU:
  6067. begin
  6068. Inc(Count);
  6069. if Count >= 5 then
  6070. { Too many to be worthwhile }
  6071. Break;
  6072. GetNextInstruction(hp2, hp2);
  6073. Continue;
  6074. end;
  6075. A_JMP:
  6076. begin
  6077. { Guard against infinite loops }
  6078. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6079. Exit;
  6080. { Analyse this jump first in case it also duplicates assignments }
  6081. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6082. begin
  6083. { Something did change! }
  6084. Result := True;
  6085. Inc(Count, IncCount);
  6086. if Count >= 5 then
  6087. begin
  6088. { Too many to be worthwhile }
  6089. Exit;
  6090. end;
  6091. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6092. Break;
  6093. end;
  6094. Result := True;
  6095. Break;
  6096. end;
  6097. A_RET:
  6098. begin
  6099. Result := True;
  6100. Break;
  6101. end;
  6102. else
  6103. Break;
  6104. end;
  6105. end;
  6106. if Result then
  6107. begin
  6108. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6109. if Count = 0 then
  6110. begin
  6111. Result := False;
  6112. Exit;
  6113. end;
  6114. hp3 := p;
  6115. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6116. while True do
  6117. begin
  6118. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6119. SkipLabels(hp1,hp1);
  6120. if (hp1.typ <> ait_instruction) then
  6121. InternalError(2021040720);
  6122. case taicpu(hp1).opcode of
  6123. A_JMP:
  6124. begin
  6125. { Change the original jump to the new destination }
  6126. OrigLabel.decrefs;
  6127. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6128. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6129. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6130. if not Assigned(first_assignment) then
  6131. InternalError(2021040810)
  6132. else
  6133. p := first_assignment;
  6134. Exit;
  6135. end;
  6136. A_RET:
  6137. begin
  6138. { Now change the jump into a RET instruction }
  6139. ConvertJumpToRET(p, hp1);
  6140. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6141. if not Assigned(first_assignment) then
  6142. InternalError(2021040811)
  6143. else
  6144. p := first_assignment;
  6145. Exit;
  6146. end;
  6147. else
  6148. begin
  6149. { Duplicate the MOV instruction }
  6150. hp3:=tai(hp1.getcopy);
  6151. if first_assignment = nil then
  6152. first_assignment := hp3;
  6153. asml.InsertBefore(hp3, p);
  6154. { Make sure the compiler knows about any final registers written here }
  6155. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6156. with taicpu(hp3).oper[OperIdx]^ do
  6157. begin
  6158. case typ of
  6159. top_ref:
  6160. begin
  6161. if (ref^.base <> NR_NO) and
  6162. (getsupreg(ref^.base) <> RS_ESP) and
  6163. (getsupreg(ref^.base) <> RS_EBP)
  6164. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6165. then
  6166. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6167. if (ref^.index <> NR_NO) and
  6168. (getsupreg(ref^.index) <> RS_ESP) and
  6169. (getsupreg(ref^.index) <> RS_EBP)
  6170. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6171. (ref^.index <> ref^.base) then
  6172. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6173. end;
  6174. top_reg:
  6175. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6176. else
  6177. ;
  6178. end;
  6179. end;
  6180. end;
  6181. end;
  6182. if not GetNextInstruction(hp1, hp1) then
  6183. { Should have dropped out earlier }
  6184. InternalError(2021040710);
  6185. end;
  6186. end;
  6187. end;
  6188. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6189. var
  6190. hp2: tai;
  6191. X: Integer;
  6192. const
  6193. WriteOp: array[0..3] of set of TInsChange = (
  6194. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6195. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6196. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6197. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6198. RegWriteFlags: array[0..7] of set of TInsChange = (
  6199. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6200. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6201. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6202. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6203. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6204. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6205. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6206. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6207. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6208. begin
  6209. { If we have something like:
  6210. cmp ###,%reg1
  6211. mov 0,%reg2
  6212. And no modified registers are shared, move the instruction to before
  6213. the comparison as this means it can be optimised without worrying
  6214. about the FLAGS register. (CMP/MOV is generated by
  6215. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6216. As long as the second instruction doesn't use the flags or one of the
  6217. registers used by CMP or TEST (also check any references that use the
  6218. registers), then it can be moved prior to the comparison.
  6219. }
  6220. Result := False;
  6221. if (hp1.typ <> ait_instruction) or
  6222. taicpu(hp1).is_jmp or
  6223. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6224. Exit;
  6225. { NOP is a pipeline fence, likely marking the beginning of the function
  6226. epilogue, so drop out. Similarly, drop out if POP or RET are
  6227. encountered }
  6228. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6229. Exit;
  6230. if (taicpu(hp1).opcode = A_MOVSS) and
  6231. (taicpu(hp1).ops = 0) then
  6232. { Wrong MOVSS }
  6233. Exit;
  6234. { Check for writes to specific registers first }
  6235. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  6236. for X := 0 to 7 do
  6237. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  6238. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  6239. Exit;
  6240. for X := 0 to taicpu(hp1).ops - 1 do
  6241. begin
  6242. { Check to see if this operand writes to something }
  6243. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  6244. { And matches something in the CMP/TEST instruction }
  6245. (
  6246. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  6247. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  6248. (
  6249. { If it's a register, make sure the register written to doesn't
  6250. appear in the cmp instruction as part of a reference }
  6251. (taicpu(hp1).oper[X]^.typ = top_reg) and
  6252. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  6253. )
  6254. ) then
  6255. Exit;
  6256. end;
  6257. { The instruction can be safely moved }
  6258. asml.Remove(hp1);
  6259. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  6260. if not GetLastInstruction(p, hp2) then
  6261. asml.InsertBefore(hp1, p)
  6262. else
  6263. asml.InsertAfter(hp1, hp2);
  6264. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  6265. for X := 0 to taicpu(hp1).ops - 1 do
  6266. case taicpu(hp1).oper[X]^.typ of
  6267. top_reg:
  6268. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  6269. top_ref:
  6270. begin
  6271. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  6272. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  6273. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  6274. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  6275. end;
  6276. else
  6277. ;
  6278. end;
  6279. if taicpu(hp1).opcode = A_LEA then
  6280. { The flags will be overwritten by the CMP/TEST instruction }
  6281. ConvertLEA(taicpu(hp1));
  6282. Result := True;
  6283. end;
  6284. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  6285. function IsXCHGAcceptable: Boolean; inline;
  6286. begin
  6287. { Always accept if optimising for size }
  6288. Result := (cs_opt_size in current_settings.optimizerswitches) or
  6289. (
  6290. {$ifdef x86_64}
  6291. { XCHG takes 3 cycles on AMD Athlon64 }
  6292. (current_settings.optimizecputype >= cpu_core_i)
  6293. {$else x86_64}
  6294. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  6295. than 3, so it becomes a saving compared to three MOVs with two of
  6296. them able to execute simultaneously. [Kit] }
  6297. (current_settings.optimizecputype >= cpu_PentiumM)
  6298. {$endif x86_64}
  6299. );
  6300. end;
  6301. var
  6302. NewRef: TReference;
  6303. hp1, hp2, hp3, hp4: Tai;
  6304. {$ifndef x86_64}
  6305. OperIdx: Integer;
  6306. {$endif x86_64}
  6307. NewInstr : Taicpu;
  6308. NewAligh : Tai_align;
  6309. DestLabel: TAsmLabel;
  6310. function TryMovArith2Lea(InputInstr: tai): Boolean;
  6311. var
  6312. NextInstr: tai;
  6313. begin
  6314. Result := False;
  6315. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  6316. if not GetNextInstruction(InputInstr, NextInstr) or
  6317. (
  6318. { The FLAGS register isn't always tracked properly, so do not
  6319. perform this optimisation if a conditional statement follows }
  6320. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  6321. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  6322. ) then
  6323. begin
  6324. reference_reset(NewRef, 1, []);
  6325. NewRef.base := taicpu(p).oper[0]^.reg;
  6326. NewRef.scalefactor := 1;
  6327. if taicpu(InputInstr).opcode = A_ADD then
  6328. begin
  6329. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  6330. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  6331. end
  6332. else
  6333. begin
  6334. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  6335. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  6336. end;
  6337. taicpu(p).opcode := A_LEA;
  6338. taicpu(p).loadref(0, NewRef);
  6339. RemoveInstruction(InputInstr);
  6340. Result := True;
  6341. end;
  6342. end;
  6343. begin
  6344. Result:=false;
  6345. { This optimisation adds an instruction, so only do it for speed }
  6346. if not (cs_opt_size in current_settings.optimizerswitches) and
  6347. MatchOpType(taicpu(p), top_const, top_reg) and
  6348. (taicpu(p).oper[0]^.val = 0) then
  6349. begin
  6350. { To avoid compiler warning }
  6351. DestLabel := nil;
  6352. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  6353. InternalError(2021040750);
  6354. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  6355. Exit;
  6356. case hp1.typ of
  6357. ait_label:
  6358. begin
  6359. { Change:
  6360. mov $0,%reg mov $0,%reg
  6361. @Lbl1: @Lbl1:
  6362. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  6363. je @Lbl2 jne @Lbl2
  6364. To: To:
  6365. mov $0,%reg mov $0,%reg
  6366. jmp @Lbl2 jmp @Lbl3
  6367. (align) (align)
  6368. @Lbl1: @Lbl1:
  6369. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  6370. je @Lbl2 je @Lbl2
  6371. @Lbl3: <-- Only if label exists
  6372. (Not if it's optimised for size)
  6373. }
  6374. if not GetNextInstruction(hp1, hp2) then
  6375. Exit;
  6376. if not (cs_opt_size in current_settings.optimizerswitches) and
  6377. (hp2.typ = ait_instruction) and
  6378. (
  6379. { Register sizes must exactly match }
  6380. (
  6381. (taicpu(hp2).opcode = A_CMP) and
  6382. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  6383. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6384. ) or (
  6385. (taicpu(hp2).opcode = A_TEST) and
  6386. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6387. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6388. )
  6389. ) and GetNextInstruction(hp2, hp3) and
  6390. (hp3.typ = ait_instruction) and
  6391. (taicpu(hp3).opcode = A_JCC) and
  6392. (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
  6393. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  6394. begin
  6395. { Check condition of jump }
  6396. { Always true? }
  6397. if condition_in(C_E, taicpu(hp3).condition) then
  6398. begin
  6399. { Copy label symbol and obtain matching label entry for the
  6400. conditional jump, as this will be our destination}
  6401. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  6402. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  6403. Result := True;
  6404. end
  6405. { Always false? }
  6406. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  6407. begin
  6408. { This is only worth it if there's a jump to take }
  6409. case hp2.typ of
  6410. ait_instruction:
  6411. begin
  6412. if taicpu(hp2).opcode = A_JMP then
  6413. begin
  6414. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6415. { An unconditional jump follows the conditional jump which will always be false,
  6416. so use this jump's destination for the new jump }
  6417. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  6418. Result := True;
  6419. end
  6420. else if taicpu(hp2).opcode = A_JCC then
  6421. begin
  6422. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6423. if condition_in(C_E, taicpu(hp2).condition) then
  6424. begin
  6425. { A second conditional jump follows the conditional jump which will always be false,
  6426. while the second jump is always True, so use this jump's destination for the new jump }
  6427. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  6428. Result := True;
  6429. end;
  6430. { Don't risk it if the jump isn't always true (Result remains False) }
  6431. end;
  6432. end;
  6433. else
  6434. { If anything else don't optimise };
  6435. end;
  6436. end;
  6437. if Result then
  6438. begin
  6439. { Just so we have something to insert as a paremeter}
  6440. reference_reset(NewRef, 1, []);
  6441. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  6442. { Now actually load the correct parameter }
  6443. NewInstr.loadsymbol(0, DestLabel, 0);
  6444. { Get instruction before original label (may not be p under -O3) }
  6445. if not GetLastInstruction(hp1, hp2) then
  6446. { Shouldn't fail here }
  6447. InternalError(2021040701);
  6448. DestLabel.increfs;
  6449. AsmL.InsertAfter(NewInstr, hp2);
  6450. { Add new alignment field }
  6451. (* AsmL.InsertAfter(
  6452. cai_align.create_max(
  6453. current_settings.alignment.jumpalign,
  6454. current_settings.alignment.jumpalignskipmax
  6455. ),
  6456. NewInstr
  6457. ); *)
  6458. end;
  6459. Exit;
  6460. end;
  6461. end;
  6462. else
  6463. ;
  6464. end;
  6465. end;
  6466. if not GetNextInstruction(p, hp1) then
  6467. Exit;
  6468. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  6469. begin
  6470. { Sometimes the MOVs that OptPass2JMP produces can be improved
  6471. further, but we can't just put this jump optimisation in pass 1
  6472. because it tends to perform worse when conditional jumps are
  6473. nearby (e.g. when converting CMOV instructions). [Kit] }
  6474. if OptPass2JMP(hp1) then
  6475. { call OptPass1MOV once to potentially merge any MOVs that were created }
  6476. Result := OptPass1MOV(p)
  6477. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  6478. returned True and the instruction is still a MOV, thus checking
  6479. the optimisations below }
  6480. { If OptPass2JMP returned False, no optimisations were done to
  6481. the jump and there are no further optimisations that can be done
  6482. to the MOV instruction on this pass }
  6483. end
  6484. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6485. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  6486. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  6487. (taicpu(hp1).oper[1]^.typ = top_reg) and
  6488. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6489. begin
  6490. { Change:
  6491. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  6492. addl/q $x,%reg2 subl/q $x,%reg2
  6493. To:
  6494. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  6495. }
  6496. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6497. { be lazy, checking separately for sub would be slightly better }
  6498. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  6499. begin
  6500. TransferUsedRegs(TmpUsedRegs);
  6501. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6502. if TryMovArith2Lea(hp1) then
  6503. begin
  6504. Result := True;
  6505. Exit;
  6506. end
  6507. end
  6508. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  6509. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  6510. { Same as above, but also adds or subtracts to %reg2 in between.
  6511. It's still valid as long as the flags aren't in use }
  6512. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  6513. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6514. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6515. { be lazy, checking separately for sub would be slightly better }
  6516. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  6517. begin
  6518. TransferUsedRegs(TmpUsedRegs);
  6519. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6520. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6521. if TryMovArith2Lea(hp2) then
  6522. begin
  6523. Result := True;
  6524. Exit;
  6525. end;
  6526. end;
  6527. end
  6528. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6529. {$ifdef x86_64}
  6530. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  6531. {$else x86_64}
  6532. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  6533. {$endif x86_64}
  6534. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6535. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  6536. { mov reg1, reg2 mov reg1, reg2
  6537. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  6538. begin
  6539. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6540. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  6541. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  6542. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  6543. TransferUsedRegs(TmpUsedRegs);
  6544. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6545. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  6546. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  6547. then
  6548. begin
  6549. RemoveCurrentP(p, hp1);
  6550. Result:=true;
  6551. end;
  6552. exit;
  6553. end
  6554. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6555. IsXCHGAcceptable and
  6556. { XCHG doesn't support 8-byte registers }
  6557. (taicpu(p).opsize <> S_B) and
  6558. MatchInstruction(hp1, A_MOV, []) and
  6559. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6560. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  6561. GetNextInstruction(hp1, hp2) and
  6562. MatchInstruction(hp2, A_MOV, []) and
  6563. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  6564. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6565. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  6566. begin
  6567. { mov %reg1,%reg2
  6568. mov %reg3,%reg1 -> xchg %reg3,%reg1
  6569. mov %reg2,%reg3
  6570. (%reg2 not used afterwards)
  6571. Note that xchg takes 3 cycles to execute, and generally mov's take
  6572. only one cycle apiece, but the first two mov's can be executed in
  6573. parallel, only taking 2 cycles overall. Older processors should
  6574. therefore only optimise for size. [Kit]
  6575. }
  6576. TransferUsedRegs(TmpUsedRegs);
  6577. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6578. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6579. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  6580. begin
  6581. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  6582. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  6583. taicpu(hp1).opcode := A_XCHG;
  6584. RemoveCurrentP(p, hp1);
  6585. RemoveInstruction(hp2);
  6586. Result := True;
  6587. Exit;
  6588. end;
  6589. end
  6590. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6591. MatchInstruction(hp1, A_SAR, []) then
  6592. begin
  6593. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  6594. begin
  6595. { the use of %edx also covers the opsize being S_L }
  6596. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  6597. begin
  6598. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  6599. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  6600. (taicpu(p).oper[1]^.reg = NR_EDX) then
  6601. begin
  6602. { Change:
  6603. movl %eax,%edx
  6604. sarl $31,%edx
  6605. To:
  6606. cltd
  6607. }
  6608. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  6609. RemoveInstruction(hp1);
  6610. taicpu(p).opcode := A_CDQ;
  6611. taicpu(p).opsize := S_NO;
  6612. taicpu(p).clearop(1);
  6613. taicpu(p).clearop(0);
  6614. taicpu(p).ops:=0;
  6615. Result := True;
  6616. end
  6617. else if (cs_opt_size in current_settings.optimizerswitches) and
  6618. (taicpu(p).oper[0]^.reg = NR_EDX) and
  6619. (taicpu(p).oper[1]^.reg = NR_EAX) then
  6620. begin
  6621. { Change:
  6622. movl %edx,%eax
  6623. sarl $31,%edx
  6624. To:
  6625. movl %edx,%eax
  6626. cltd
  6627. Note that this creates a dependency between the two instructions,
  6628. so only perform if optimising for size.
  6629. }
  6630. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  6631. taicpu(hp1).opcode := A_CDQ;
  6632. taicpu(hp1).opsize := S_NO;
  6633. taicpu(hp1).clearop(1);
  6634. taicpu(hp1).clearop(0);
  6635. taicpu(hp1).ops:=0;
  6636. end;
  6637. {$ifndef x86_64}
  6638. end
  6639. { Don't bother if CMOV is supported, because a more optimal
  6640. sequence would have been generated for the Abs() intrinsic }
  6641. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  6642. { the use of %eax also covers the opsize being S_L }
  6643. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  6644. (taicpu(p).oper[0]^.reg = NR_EAX) and
  6645. (taicpu(p).oper[1]^.reg = NR_EDX) and
  6646. GetNextInstruction(hp1, hp2) and
  6647. MatchInstruction(hp2, A_XOR, [S_L]) and
  6648. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  6649. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  6650. GetNextInstruction(hp2, hp3) and
  6651. MatchInstruction(hp3, A_SUB, [S_L]) and
  6652. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  6653. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  6654. begin
  6655. { Change:
  6656. movl %eax,%edx
  6657. sarl $31,%eax
  6658. xorl %eax,%edx
  6659. subl %eax,%edx
  6660. (Instruction that uses %edx)
  6661. (%eax deallocated)
  6662. (%edx deallocated)
  6663. To:
  6664. cltd
  6665. xorl %edx,%eax <-- Note the registers have swapped
  6666. subl %edx,%eax
  6667. (Instruction that uses %eax) <-- %eax rather than %edx
  6668. }
  6669. TransferUsedRegs(TmpUsedRegs);
  6670. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6671. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6672. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6673. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  6674. begin
  6675. if GetNextInstruction(hp3, hp4) and
  6676. not RegModifiedByInstruction(NR_EDX, hp4) and
  6677. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  6678. begin
  6679. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  6680. taicpu(p).opcode := A_CDQ;
  6681. taicpu(p).clearop(1);
  6682. taicpu(p).clearop(0);
  6683. taicpu(p).ops:=0;
  6684. RemoveInstruction(hp1);
  6685. taicpu(hp2).loadreg(0, NR_EDX);
  6686. taicpu(hp2).loadreg(1, NR_EAX);
  6687. taicpu(hp3).loadreg(0, NR_EDX);
  6688. taicpu(hp3).loadreg(1, NR_EAX);
  6689. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  6690. { Convert references in the following instruction (hp4) from %edx to %eax }
  6691. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  6692. with taicpu(hp4).oper[OperIdx]^ do
  6693. case typ of
  6694. top_reg:
  6695. if getsupreg(reg) = RS_EDX then
  6696. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6697. top_ref:
  6698. begin
  6699. if getsupreg(reg) = RS_EDX then
  6700. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6701. if getsupreg(reg) = RS_EDX then
  6702. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6703. end;
  6704. else
  6705. ;
  6706. end;
  6707. end;
  6708. end;
  6709. {$else x86_64}
  6710. end;
  6711. end
  6712. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  6713. { the use of %rdx also covers the opsize being S_Q }
  6714. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  6715. begin
  6716. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  6717. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  6718. (taicpu(p).oper[1]^.reg = NR_RDX) then
  6719. begin
  6720. { Change:
  6721. movq %rax,%rdx
  6722. sarq $63,%rdx
  6723. To:
  6724. cqto
  6725. }
  6726. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  6727. RemoveInstruction(hp1);
  6728. taicpu(p).opcode := A_CQO;
  6729. taicpu(p).opsize := S_NO;
  6730. taicpu(p).clearop(1);
  6731. taicpu(p).clearop(0);
  6732. taicpu(p).ops:=0;
  6733. Result := True;
  6734. end
  6735. else if (cs_opt_size in current_settings.optimizerswitches) and
  6736. (taicpu(p).oper[0]^.reg = NR_RDX) and
  6737. (taicpu(p).oper[1]^.reg = NR_RAX) then
  6738. begin
  6739. { Change:
  6740. movq %rdx,%rax
  6741. sarq $63,%rdx
  6742. To:
  6743. movq %rdx,%rax
  6744. cqto
  6745. Note that this creates a dependency between the two instructions,
  6746. so only perform if optimising for size.
  6747. }
  6748. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  6749. taicpu(hp1).opcode := A_CQO;
  6750. taicpu(hp1).opsize := S_NO;
  6751. taicpu(hp1).clearop(1);
  6752. taicpu(hp1).clearop(0);
  6753. taicpu(hp1).ops:=0;
  6754. {$endif x86_64}
  6755. end;
  6756. end;
  6757. end
  6758. else if MatchInstruction(hp1, A_MOV, []) and
  6759. (taicpu(hp1).oper[1]^.typ = top_reg) then
  6760. { Though "GetNextInstruction" could be factored out, along with
  6761. the instructions that depend on hp2, it is an expensive call that
  6762. should be delayed for as long as possible, hence we do cheaper
  6763. checks first that are likely to be False. [Kit] }
  6764. begin
  6765. if (
  6766. (
  6767. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  6768. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  6769. (
  6770. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6771. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  6772. )
  6773. ) or
  6774. (
  6775. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  6776. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  6777. (
  6778. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6779. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  6780. )
  6781. )
  6782. ) and
  6783. GetNextInstruction(hp1, hp2) and
  6784. MatchInstruction(hp2, A_SAR, []) and
  6785. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  6786. begin
  6787. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  6788. begin
  6789. { Change:
  6790. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  6791. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  6792. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  6793. To:
  6794. movl r/m,%eax <- Note the change in register
  6795. cltd
  6796. }
  6797. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  6798. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  6799. taicpu(p).loadreg(1, NR_EAX);
  6800. taicpu(hp1).opcode := A_CDQ;
  6801. taicpu(hp1).clearop(1);
  6802. taicpu(hp1).clearop(0);
  6803. taicpu(hp1).ops:=0;
  6804. RemoveInstruction(hp2);
  6805. (*
  6806. {$ifdef x86_64}
  6807. end
  6808. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  6809. { This code sequence does not get generated - however it might become useful
  6810. if and when 128-bit signed integer types make an appearance, so the code
  6811. is kept here for when it is eventually needed. [Kit] }
  6812. (
  6813. (
  6814. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  6815. (
  6816. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6817. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  6818. )
  6819. ) or
  6820. (
  6821. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  6822. (
  6823. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6824. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  6825. )
  6826. )
  6827. ) and
  6828. GetNextInstruction(hp1, hp2) and
  6829. MatchInstruction(hp2, A_SAR, [S_Q]) and
  6830. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  6831. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  6832. begin
  6833. { Change:
  6834. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  6835. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  6836. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  6837. To:
  6838. movq r/m,%rax <- Note the change in register
  6839. cqto
  6840. }
  6841. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  6842. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  6843. taicpu(p).loadreg(1, NR_RAX);
  6844. taicpu(hp1).opcode := A_CQO;
  6845. taicpu(hp1).clearop(1);
  6846. taicpu(hp1).clearop(0);
  6847. taicpu(hp1).ops:=0;
  6848. RemoveInstruction(hp2);
  6849. {$endif x86_64}
  6850. *)
  6851. end;
  6852. end;
  6853. {$ifdef x86_64}
  6854. end
  6855. else if (taicpu(p).opsize = S_L) and
  6856. (taicpu(p).oper[1]^.typ = top_reg) and
  6857. (
  6858. MatchInstruction(hp1, A_MOV,[]) and
  6859. (taicpu(hp1).opsize = S_L) and
  6860. (taicpu(hp1).oper[1]^.typ = top_reg)
  6861. ) and (
  6862. GetNextInstruction(hp1, hp2) and
  6863. (tai(hp2).typ=ait_instruction) and
  6864. (taicpu(hp2).opsize = S_Q) and
  6865. (
  6866. (
  6867. MatchInstruction(hp2, A_ADD,[]) and
  6868. (taicpu(hp2).opsize = S_Q) and
  6869. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  6870. (
  6871. (
  6872. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  6873. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6874. ) or (
  6875. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6876. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  6877. )
  6878. )
  6879. ) or (
  6880. MatchInstruction(hp2, A_LEA,[]) and
  6881. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  6882. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  6883. (
  6884. (
  6885. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  6886. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6887. ) or (
  6888. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6889. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  6890. )
  6891. ) and (
  6892. (
  6893. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6894. ) or (
  6895. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  6896. )
  6897. )
  6898. )
  6899. )
  6900. ) and (
  6901. GetNextInstruction(hp2, hp3) and
  6902. MatchInstruction(hp3, A_SHR,[]) and
  6903. (taicpu(hp3).opsize = S_Q) and
  6904. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  6905. (taicpu(hp3).oper[0]^.val = 1) and
  6906. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  6907. ) then
  6908. begin
  6909. { Change movl x, reg1d movl x, reg1d
  6910. movl y, reg2d movl y, reg2d
  6911. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  6912. shrq $1, reg1q shrq $1, reg1q
  6913. ( reg1d and reg2d can be switched around in the first two instructions )
  6914. To movl x, reg1d
  6915. addl y, reg1d
  6916. rcrl $1, reg1d
  6917. This corresponds to the common expression (x + y) shr 1, where
  6918. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  6919. smaller code, but won't account for x + y causing an overflow). [Kit]
  6920. }
  6921. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  6922. { Change first MOV command to have the same register as the final output }
  6923. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  6924. else
  6925. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  6926. { Change second MOV command to an ADD command. This is easier than
  6927. converting the existing command because it means we don't have to
  6928. touch 'y', which might be a complicated reference, and also the
  6929. fact that the third command might either be ADD or LEA. [Kit] }
  6930. taicpu(hp1).opcode := A_ADD;
  6931. { Delete old ADD/LEA instruction }
  6932. RemoveInstruction(hp2);
  6933. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  6934. taicpu(hp3).opcode := A_RCR;
  6935. taicpu(hp3).changeopsize(S_L);
  6936. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  6937. {$endif x86_64}
  6938. end;
  6939. end;
  6940. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  6941. var
  6942. ThisReg: TRegister;
  6943. MinSize, MaxSize, TrySmaller, TargetSize: TOpSize;
  6944. TargetSubReg: TSubRegister;
  6945. hp1, hp2: tai;
  6946. RegInUse, RegChanged, p_removed: Boolean;
  6947. { Store list of found instructions so we don't have to call
  6948. GetNextInstructionUsingReg multiple times }
  6949. InstrList: array of taicpu;
  6950. InstrMax, Index: Integer;
  6951. UpperLimit, TrySmallerLimit: TCgInt;
  6952. PreMessage: string;
  6953. { Data flow analysis }
  6954. TestValMin, TestValMax: TCgInt;
  6955. SmallerOverflow: Boolean;
  6956. begin
  6957. Result := False;
  6958. p_removed := False;
  6959. { This is anything but quick! }
  6960. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  6961. Exit;
  6962. SetLength(InstrList, 0);
  6963. InstrMax := -1;
  6964. ThisReg := taicpu(p).oper[1]^.reg;
  6965. case taicpu(p).opsize of
  6966. S_BW, S_BL:
  6967. begin
  6968. {$if defined(i386) or defined(i8086)}
  6969. { If the target size is 8-bit, make sure we can actually encode it }
  6970. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  6971. Exit;
  6972. {$endif i386 or i8086}
  6973. UpperLimit := $FF;
  6974. MinSize := S_B;
  6975. if taicpu(p).opsize = S_BW then
  6976. MaxSize := S_W
  6977. else
  6978. MaxSize := S_L;
  6979. end;
  6980. S_WL:
  6981. begin
  6982. UpperLimit := $FFFF;
  6983. MinSize := S_W;
  6984. MaxSize := S_L;
  6985. end
  6986. else
  6987. InternalError(2020112301);
  6988. end;
  6989. TestValMin := 0;
  6990. TestValMax := UpperLimit;
  6991. TrySmallerLimit := UpperLimit;
  6992. TrySmaller := S_NO;
  6993. SmallerOverflow := False;
  6994. RegChanged := False;
  6995. hp1 := p;
  6996. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  6997. (hp1.typ = ait_instruction) and
  6998. (
  6999. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7000. instruction that doesn't actually contain ThisReg }
  7001. (cs_opt_level3 in current_settings.optimizerswitches) or
  7002. RegInInstruction(ThisReg, hp1)
  7003. ) do
  7004. begin
  7005. case taicpu(hp1).opcode of
  7006. A_INC,A_DEC:
  7007. begin
  7008. { Has to be an exact match on the register }
  7009. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  7010. Break;
  7011. if taicpu(hp1).opcode = A_INC then
  7012. begin
  7013. Inc(TestValMin);
  7014. Inc(TestValMax);
  7015. end
  7016. else
  7017. begin
  7018. Dec(TestValMin);
  7019. Dec(TestValMax);
  7020. end;
  7021. end;
  7022. A_CMP:
  7023. begin
  7024. if (taicpu(hp1).oper[1]^.typ <> top_reg) or
  7025. { Has to be an exact match on the register }
  7026. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  7027. (taicpu(hp1).oper[0]^.typ <> top_const) or
  7028. { Make sure the comparison value is not smaller than the
  7029. smallest allowed signed value for the minimum size (e.g.
  7030. -128 for 8-bit) }
  7031. not (
  7032. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  7033. { Is it in the negative range? }
  7034. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  7035. ) then
  7036. Break;
  7037. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  7038. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  7039. if (TestValMin < TrySmallerLimit) or (TestValMax < TrySmallerLimit) or
  7040. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  7041. { Overflow }
  7042. Break;
  7043. { Check to see if the active register is used afterwards }
  7044. TransferUsedRegs(TmpUsedRegs);
  7045. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  7046. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7047. begin
  7048. case MinSize of
  7049. S_B:
  7050. TargetSubReg := R_SUBL;
  7051. S_W:
  7052. TargetSubReg := R_SUBW;
  7053. else
  7054. InternalError(2021051002);
  7055. end;
  7056. { Update the register to its new size }
  7057. setsubreg(ThisReg, TargetSubReg);
  7058. taicpu(hp1).oper[1]^.reg := ThisReg;
  7059. taicpu(hp1).opsize := MinSize;
  7060. { Convert the input MOVZX to a MOV }
  7061. if (taicpu(p).oper[0]^.typ = top_reg) and
  7062. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7063. begin
  7064. { Or remove it completely! }
  7065. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  7066. RemoveCurrentP(p);
  7067. p_removed := True;
  7068. end
  7069. else
  7070. begin
  7071. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  7072. taicpu(p).opcode := A_MOV;
  7073. taicpu(p).oper[1]^.reg := ThisReg;
  7074. taicpu(p).opsize := MinSize;
  7075. end;
  7076. if (InstrMax >= 0) then
  7077. begin
  7078. for Index := 0 to InstrMax do
  7079. begin
  7080. { If p_removed is true, then the original MOV/Z was removed
  7081. and removing the AND instruction may not be safe if it
  7082. appears first }
  7083. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  7084. InternalError(2020112311);
  7085. if InstrList[Index].oper[0]^.typ = top_reg then
  7086. InstrList[Index].oper[0]^.reg := ThisReg;
  7087. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  7088. InstrList[Index].opsize := MinSize;
  7089. end;
  7090. end;
  7091. Result := True;
  7092. Exit;
  7093. end;
  7094. end;
  7095. { OR and XOR are not included because they can too easily fool
  7096. the data flow analysis (they can cause non-linear behaviour) }
  7097. A_ADD,A_SUB,A_AND,A_SHL,A_SHR:
  7098. begin
  7099. if
  7100. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  7101. { Has to be an exact match on the register }
  7102. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  7103. (
  7104. (
  7105. (taicpu(hp1).oper[0]^.typ = top_const) and
  7106. (
  7107. (
  7108. (taicpu(hp1).opcode = A_SHL) and
  7109. (
  7110. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  7111. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  7112. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  7113. )
  7114. ) or (
  7115. (taicpu(hp1).opcode <> A_SHL) and
  7116. (
  7117. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  7118. { Is it in the negative range? }
  7119. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  7120. )
  7121. )
  7122. )
  7123. ) or (
  7124. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  7125. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  7126. )
  7127. ) then
  7128. Break;
  7129. case taicpu(hp1).opcode of
  7130. A_ADD:
  7131. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7132. begin
  7133. TestValMin := TestValMin * 2;
  7134. TestValMax := TestValMax * 2;
  7135. end
  7136. else
  7137. begin
  7138. TestValMin := TestValMin + taicpu(hp1).oper[0]^.val;
  7139. TestValMax := TestValMax + taicpu(hp1).oper[0]^.val;
  7140. end;
  7141. A_SUB:
  7142. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7143. begin
  7144. TestValMin := 0;
  7145. TestValMax := 0;
  7146. end
  7147. else
  7148. begin
  7149. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  7150. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  7151. end;
  7152. A_AND:
  7153. if (taicpu(hp1).oper[0]^.typ = top_const) then
  7154. begin
  7155. { we might be able to go smaller if AND appears first }
  7156. if InstrMax = -1 then
  7157. case MinSize of
  7158. S_B:
  7159. ;
  7160. S_W:
  7161. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  7162. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  7163. begin
  7164. TrySmaller := S_B;
  7165. TrySmallerLimit := $FF;
  7166. end;
  7167. S_L:
  7168. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  7169. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  7170. begin
  7171. TrySmaller := S_B;
  7172. TrySmallerLimit := $FF;
  7173. end
  7174. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  7175. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  7176. begin
  7177. TrySmaller := S_W;
  7178. TrySmallerLimit := $FFFF;
  7179. end;
  7180. else
  7181. InternalError(2020112320);
  7182. end;
  7183. TestValMin := TestValMin and taicpu(hp1).oper[0]^.val;
  7184. TestValMax := TestValMax and taicpu(hp1).oper[0]^.val;
  7185. end;
  7186. A_SHL:
  7187. begin
  7188. TestValMin := TestValMin shl taicpu(hp1).oper[0]^.val;
  7189. TestValMax := TestValMax shl taicpu(hp1).oper[0]^.val;
  7190. end;
  7191. A_SHR:
  7192. begin
  7193. { we might be able to go smaller if SHR appears first }
  7194. if InstrMax = -1 then
  7195. case MinSize of
  7196. S_B:
  7197. ;
  7198. S_W:
  7199. if (taicpu(hp1).oper[0]^.val >= 8) then
  7200. begin
  7201. TrySmaller := S_B;
  7202. TrySmallerLimit := $FF;
  7203. end;
  7204. S_L:
  7205. if (taicpu(hp1).oper[0]^.val >= 24) then
  7206. begin
  7207. TrySmaller := S_B;
  7208. TrySmallerLimit := $FF;
  7209. end
  7210. else if (taicpu(hp1).oper[0]^.val >= 16) then
  7211. begin
  7212. TrySmaller := S_W;
  7213. TrySmallerLimit := $FFFF;
  7214. end;
  7215. else
  7216. InternalError(2020112321);
  7217. end;
  7218. TestValMin := TestValMin shr taicpu(hp1).oper[0]^.val;
  7219. TestValMax := TestValMax shr taicpu(hp1).oper[0]^.val;
  7220. end;
  7221. else
  7222. InternalError(2020112303);
  7223. end;
  7224. end;
  7225. (*
  7226. A_IMUL:
  7227. case taicpu(hp1).ops of
  7228. 2:
  7229. begin
  7230. if not MatchOpType(hp1, top_reg, top_reg) or
  7231. { Has to be an exact match on the register }
  7232. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  7233. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  7234. Break;
  7235. TestValMin := TestValMin * TestValMin;
  7236. TestValMax := TestValMax * TestValMax;
  7237. end;
  7238. 3:
  7239. begin
  7240. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  7241. { Has to be an exact match on the register }
  7242. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  7243. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  7244. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  7245. { Is it in the negative range? }
  7246. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  7247. Break;
  7248. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  7249. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  7250. end;
  7251. else
  7252. Break;
  7253. end;
  7254. A_IDIV:
  7255. case taicpu(hp1).ops of
  7256. 3:
  7257. begin
  7258. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  7259. { Has to be an exact match on the register }
  7260. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  7261. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  7262. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  7263. { Is it in the negative range? }
  7264. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  7265. Break;
  7266. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  7267. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  7268. end;
  7269. else
  7270. Break;
  7271. end;
  7272. *)
  7273. A_MOVZX:
  7274. begin
  7275. if not MatchOpType(taicpu(hp1), top_reg, top_reg) then
  7276. Break;
  7277. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  7278. begin
  7279. { Because hp1 was obtained via GetNextInstructionUsingReg
  7280. and ThisReg doesn't appear in the first operand, it
  7281. must appear in the second operand and hence gets
  7282. overwritten }
  7283. if (InstrMax = -1) and
  7284. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7285. begin
  7286. { The two MOVZX instructions are adjacent, so remove the first one }
  7287. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  7288. RemoveCurrentP(p);
  7289. Result := True;
  7290. Exit;
  7291. end;
  7292. Break;
  7293. end;
  7294. { The objective here is to try to find a combination that
  7295. removes one of the MOV/Z instructions. }
  7296. case taicpu(hp1).opsize of
  7297. S_WL:
  7298. if (MinSize in [S_B, S_W]) then
  7299. begin
  7300. TargetSize := S_L;
  7301. TargetSubReg := R_SUBD;
  7302. end
  7303. else if ((TrySmaller in [S_B, S_W]) and not SmallerOverflow) then
  7304. begin
  7305. TargetSize := TrySmaller;
  7306. if TrySmaller = S_B then
  7307. TargetSubReg := R_SUBL
  7308. else
  7309. TargetSubReg := R_SUBW;
  7310. end
  7311. else
  7312. Break;
  7313. S_BW:
  7314. if (MinSize in [S_B, S_W]) then
  7315. begin
  7316. TargetSize := S_W;
  7317. TargetSubReg := R_SUBW;
  7318. end
  7319. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  7320. begin
  7321. TargetSize := S_B;
  7322. TargetSubReg := R_SUBL;
  7323. end
  7324. else
  7325. Break;
  7326. S_BL:
  7327. if (MinSize in [S_B, S_W]) then
  7328. begin
  7329. TargetSize := S_L;
  7330. TargetSubReg := R_SUBD;
  7331. end
  7332. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  7333. begin
  7334. TargetSize := S_B;
  7335. TargetSubReg := R_SUBL;
  7336. end
  7337. else
  7338. Break;
  7339. else
  7340. InternalError(2020112302);
  7341. end;
  7342. { Update the register to its new size }
  7343. setsubreg(ThisReg, TargetSubReg);
  7344. if TargetSize = MinSize then
  7345. begin
  7346. { Convert the input MOVZX to a MOV }
  7347. if (taicpu(p).oper[0]^.typ = top_reg) and
  7348. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7349. begin
  7350. { Or remove it completely! }
  7351. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7352. RemoveCurrentP(p);
  7353. p_removed := True;
  7354. end
  7355. else
  7356. begin
  7357. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7358. taicpu(p).opcode := A_MOV;
  7359. taicpu(p).oper[1]^.reg := ThisReg;
  7360. taicpu(p).opsize := TargetSize;
  7361. end;
  7362. Result := True;
  7363. end
  7364. else if TargetSize <> MaxSize then
  7365. begin
  7366. case MaxSize of
  7367. S_L:
  7368. if TargetSize = S_W then
  7369. begin
  7370. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7371. taicpu(p).opsize := S_BW;
  7372. taicpu(p).oper[1]^.reg := ThisReg;
  7373. Result := True;
  7374. end
  7375. else
  7376. InternalError(2020112341);
  7377. S_W:
  7378. if TargetSize = S_L then
  7379. begin
  7380. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7381. taicpu(p).opsize := S_BL;
  7382. taicpu(p).oper[1]^.reg := ThisReg;
  7383. Result := True;
  7384. end
  7385. else
  7386. InternalError(2020112342);
  7387. else
  7388. ;
  7389. end;
  7390. end;
  7391. if (MaxSize = TargetSize) or
  7392. ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7393. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7394. begin
  7395. { Convert the output MOVZX to a MOV }
  7396. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7397. begin
  7398. { Or remove it completely! }
  7399. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7400. { Be careful; if p = hp1 and p was also removed, p
  7401. will become a dangling pointer }
  7402. if p = hp1 then
  7403. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  7404. else
  7405. RemoveInstruction(hp1);
  7406. end
  7407. else
  7408. begin
  7409. taicpu(hp1).opcode := A_MOV;
  7410. taicpu(hp1).oper[0]^.reg := ThisReg;
  7411. taicpu(hp1).opsize := TargetSize;
  7412. { Check to see if the active register is used afterwards;
  7413. if not, we can change it and make a saving. }
  7414. RegInUse := False;
  7415. TransferUsedRegs(TmpUsedRegs);
  7416. { The target register may be marked as in use to cross
  7417. a jump to a distant label, so exclude it }
  7418. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7419. hp2 := p;
  7420. repeat
  7421. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7422. { Explicitly check for the excluded register (don't include the first
  7423. instruction as it may be reading from here }
  7424. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7425. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7426. begin
  7427. RegInUse := True;
  7428. Break;
  7429. end;
  7430. if not GetNextInstruction(hp2, hp2) then
  7431. InternalError(2020112340);
  7432. until (hp2 = hp1);
  7433. if not RegInUse and not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7434. begin
  7435. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  7436. ThisReg := taicpu(hp1).oper[1]^.reg;
  7437. RegChanged := True;
  7438. TransferUsedRegs(TmpUsedRegs);
  7439. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  7440. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  7441. if p = hp1 then
  7442. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  7443. else
  7444. RemoveInstruction(hp1);
  7445. { Instruction will become "mov %reg,%reg" }
  7446. if not p_removed and (taicpu(p).opcode = A_MOV) and
  7447. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  7448. begin
  7449. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  7450. RemoveCurrentP(p);
  7451. p_removed := True;
  7452. end
  7453. else
  7454. taicpu(p).oper[1]^.reg := ThisReg;
  7455. Result := True;
  7456. end
  7457. else
  7458. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7459. end;
  7460. end
  7461. else
  7462. InternalError(2020112330);
  7463. { Now go through every instruction we found and change the
  7464. size. If TargetSize = MaxSize, then almost no changes are
  7465. needed and Result can remain False if it hasn't been set
  7466. yet.
  7467. If RegChanged is True, then the register requires changing
  7468. and so the point about TargetSize = MaxSize doesn't apply. }
  7469. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  7470. begin
  7471. for Index := 0 to InstrMax do
  7472. begin
  7473. { If p_removed is true, then the original MOV/Z was removed
  7474. and removing the AND instruction may not be safe if it
  7475. appears first }
  7476. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  7477. InternalError(2020112310);
  7478. if InstrList[Index].oper[0]^.typ = top_reg then
  7479. InstrList[Index].oper[0]^.reg := ThisReg;
  7480. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  7481. InstrList[Index].opsize := TargetSize;
  7482. end;
  7483. Result := True;
  7484. end;
  7485. Exit;
  7486. end;
  7487. else
  7488. { This includes ADC, SBB, IDIV and SAR }
  7489. Break;
  7490. end;
  7491. if (TestValMin < 0) or (TestValMax < 0) or
  7492. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  7493. { Overflow }
  7494. Break
  7495. else if not SmallerOverflow and (TrySmaller <> S_NO) and
  7496. ((TestValMin > TrySmallerLimit) or (TestValMax > TrySmallerLimit)) then
  7497. SmallerOverflow := True;
  7498. { Contains highest index (so instruction count - 1) }
  7499. Inc(InstrMax);
  7500. if InstrMax > High(InstrList) then
  7501. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  7502. InstrList[InstrMax] := taicpu(hp1);
  7503. end;
  7504. end;
  7505. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  7506. var
  7507. hp1 : tai;
  7508. begin
  7509. Result:=false;
  7510. if (taicpu(p).ops >= 2) and
  7511. ((taicpu(p).oper[0]^.typ = top_const) or
  7512. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  7513. (taicpu(p).oper[1]^.typ = top_reg) and
  7514. ((taicpu(p).ops = 2) or
  7515. ((taicpu(p).oper[2]^.typ = top_reg) and
  7516. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  7517. GetLastInstruction(p,hp1) and
  7518. MatchInstruction(hp1,A_MOV,[]) and
  7519. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7520. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7521. begin
  7522. TransferUsedRegs(TmpUsedRegs);
  7523. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  7524. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  7525. { change
  7526. mov reg1,reg2
  7527. imul y,reg2 to imul y,reg1,reg2 }
  7528. begin
  7529. taicpu(p).ops := 3;
  7530. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  7531. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7532. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  7533. RemoveInstruction(hp1);
  7534. result:=true;
  7535. end;
  7536. end;
  7537. end;
  7538. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  7539. var
  7540. ThisLabel: TAsmLabel;
  7541. begin
  7542. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  7543. ThisLabel.decrefs;
  7544. taicpu(p).opcode := A_RET;
  7545. taicpu(p).is_jmp := false;
  7546. taicpu(p).ops := taicpu(ret_p).ops;
  7547. case taicpu(ret_p).ops of
  7548. 0:
  7549. taicpu(p).clearop(0);
  7550. 1:
  7551. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  7552. else
  7553. internalerror(2016041301);
  7554. end;
  7555. { If the original label is now dead, it might turn out that the label
  7556. immediately follows p. As a result, everything beyond it, which will
  7557. be just some final register configuration and a RET instruction, is
  7558. now dead code. [Kit] }
  7559. { NOTE: This is much faster than introducing a OptPass2RET routine and
  7560. running RemoveDeadCodeAfterJump for each RET instruction, because
  7561. this optimisation rarely happens and most RETs appear at the end of
  7562. routines where there is nothing that can be stripped. [Kit] }
  7563. if not ThisLabel.is_used then
  7564. RemoveDeadCodeAfterJump(p);
  7565. end;
  7566. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  7567. var
  7568. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  7569. Unconditional, PotentialModified: Boolean;
  7570. OperPtr: POper;
  7571. NewRef: TReference;
  7572. InstrList: array of taicpu;
  7573. InstrMax, Index: Integer;
  7574. const
  7575. {$ifdef DEBUG_AOPTCPU}
  7576. SNoFlags: shortstring = ' so the flags aren''t modified';
  7577. {$else DEBUG_AOPTCPU}
  7578. SNoFlags = '';
  7579. {$endif DEBUG_AOPTCPU}
  7580. begin
  7581. Result:=false;
  7582. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  7583. begin
  7584. if MatchInstruction(hp1, A_TEST, [S_B]) and
  7585. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7586. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  7587. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  7588. GetNextInstruction(hp1, hp2) and
  7589. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  7590. { Change from: To:
  7591. set(C) %reg j(~C) label
  7592. test %reg,%reg/cmp $0,%reg
  7593. je label
  7594. set(C) %reg j(C) label
  7595. test %reg,%reg/cmp $0,%reg
  7596. jne label
  7597. (Also do something similar with sete/setne instead of je/jne)
  7598. }
  7599. begin
  7600. { Before we do anything else, we need to check the instructions
  7601. in between SETcc and TEST to make sure they don't modify the
  7602. FLAGS register - if -O2 or under, there won't be any
  7603. instructions between SET and TEST }
  7604. TransferUsedRegs(TmpUsedRegs);
  7605. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7606. if (cs_opt_level3 in current_settings.optimizerswitches) then
  7607. begin
  7608. next := p;
  7609. SetLength(InstrList, 0);
  7610. InstrMax := -1;
  7611. PotentialModified := False;
  7612. { Make a note of every instruction that modifies the FLAGS
  7613. register }
  7614. while GetNextInstruction(next, next) and (next <> hp1) do
  7615. begin
  7616. if next.typ <> ait_instruction then
  7617. { GetNextInstructionUsingReg should have returned False }
  7618. InternalError(2021051701);
  7619. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  7620. begin
  7621. case taicpu(next).opcode of
  7622. A_SETcc,
  7623. A_CMOVcc,
  7624. A_Jcc:
  7625. begin
  7626. if PotentialModified then
  7627. { Not safe because the flags were modified earlier }
  7628. Exit
  7629. else
  7630. { Condition is the same as the initial SETcc, so this is safe
  7631. (don't add to instruction list though) }
  7632. Continue;
  7633. end;
  7634. A_ADD:
  7635. begin
  7636. if (taicpu(next).opsize = S_B) or
  7637. { LEA doesn't support 8-bit operands }
  7638. (taicpu(next).oper[1]^.typ <> top_reg) or
  7639. { Must write to a register }
  7640. (taicpu(next).oper[0]^.typ = top_ref) then
  7641. { Require a constant or a register }
  7642. Exit;
  7643. PotentialModified := True;
  7644. end;
  7645. A_SUB:
  7646. begin
  7647. if (taicpu(next).opsize = S_B) or
  7648. { LEA doesn't support 8-bit operands }
  7649. (taicpu(next).oper[1]^.typ <> top_reg) or
  7650. { Must write to a register }
  7651. (taicpu(next).oper[0]^.typ <> top_const) or
  7652. (taicpu(next).oper[0]^.val = $80000000) then
  7653. { Can't subtract a register with LEA - also
  7654. check that the value isn't -2^31, as this
  7655. can't be negated }
  7656. Exit;
  7657. PotentialModified := True;
  7658. end;
  7659. A_SAL,
  7660. A_SHL:
  7661. begin
  7662. if (taicpu(next).opsize = S_B) or
  7663. { LEA doesn't support 8-bit operands }
  7664. (taicpu(next).oper[1]^.typ <> top_reg) or
  7665. { Must write to a register }
  7666. (taicpu(next).oper[0]^.typ <> top_const) or
  7667. (taicpu(next).oper[0]^.val < 0) or
  7668. (taicpu(next).oper[0]^.val > 3) then
  7669. Exit;
  7670. PotentialModified := True;
  7671. end;
  7672. A_IMUL:
  7673. begin
  7674. if (taicpu(next).ops <> 3) or
  7675. (taicpu(next).oper[1]^.typ <> top_reg) or
  7676. { Must write to a register }
  7677. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  7678. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  7679. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  7680. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  7681. Exit
  7682. else
  7683. PotentialModified := True;
  7684. end;
  7685. else
  7686. { Don't know how to change this, so abort }
  7687. Exit;
  7688. end;
  7689. { Contains highest index (so instruction count - 1) }
  7690. Inc(InstrMax);
  7691. if InstrMax > High(InstrList) then
  7692. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  7693. InstrList[InstrMax] := taicpu(next);
  7694. end;
  7695. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  7696. end;
  7697. if not Assigned(next) or (next <> hp1) then
  7698. { It should be equal to hp1 }
  7699. InternalError(2021051702);
  7700. { Cycle through each instruction and check to see if we can
  7701. change them to versions that don't modify the flags }
  7702. if (InstrMax >= 0) then
  7703. begin
  7704. for Index := 0 to InstrMax do
  7705. case InstrList[Index].opcode of
  7706. A_ADD:
  7707. begin
  7708. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  7709. InstrList[Index].opcode := A_LEA;
  7710. reference_reset(NewRef, 1, []);
  7711. NewRef.base := InstrList[Index].oper[1]^.reg;
  7712. if InstrList[Index].oper[0]^.typ = top_reg then
  7713. begin
  7714. NewRef.index := InstrList[Index].oper[0]^.reg;
  7715. NewRef.scalefactor := 1;
  7716. end
  7717. else
  7718. NewRef.offset := InstrList[Index].oper[0]^.val;
  7719. InstrList[Index].loadref(0, NewRef);
  7720. end;
  7721. A_SUB:
  7722. begin
  7723. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  7724. InstrList[Index].opcode := A_LEA;
  7725. reference_reset(NewRef, 1, []);
  7726. NewRef.base := InstrList[Index].oper[1]^.reg;
  7727. NewRef.offset := -InstrList[Index].oper[0]^.val;
  7728. InstrList[Index].loadref(0, NewRef);
  7729. end;
  7730. A_SHL,
  7731. A_SAL:
  7732. begin
  7733. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  7734. InstrList[Index].opcode := A_LEA;
  7735. reference_reset(NewRef, 1, []);
  7736. NewRef.index := InstrList[Index].oper[1]^.reg;
  7737. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  7738. InstrList[Index].loadref(0, NewRef);
  7739. end;
  7740. A_IMUL:
  7741. begin
  7742. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  7743. InstrList[Index].opcode := A_LEA;
  7744. reference_reset(NewRef, 1, []);
  7745. NewRef.index := InstrList[Index].oper[1]^.reg;
  7746. case InstrList[Index].oper[0]^.val of
  7747. 2, 4, 8:
  7748. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  7749. else {3, 5 and 9}
  7750. begin
  7751. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  7752. NewRef.base := InstrList[Index].oper[1]^.reg;
  7753. end;
  7754. end;
  7755. InstrList[Index].loadref(0, NewRef);
  7756. end;
  7757. else
  7758. InternalError(2021051710);
  7759. end;
  7760. end;
  7761. { Mark the FLAGS register as used across this whole block }
  7762. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  7763. end;
  7764. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  7765. JumpC := taicpu(hp2).condition;
  7766. Unconditional := False;
  7767. if conditions_equal(JumpC, C_E) then
  7768. SetC := inverse_cond(taicpu(p).condition)
  7769. else if conditions_equal(JumpC, C_NE) then
  7770. SetC := taicpu(p).condition
  7771. else
  7772. { We've got something weird here (and inefficent) }
  7773. begin
  7774. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  7775. SetC := C_NONE;
  7776. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  7777. if condition_in(C_AE, JumpC) then
  7778. Unconditional := True
  7779. else
  7780. { Not sure what to do with this jump - drop out }
  7781. Exit;
  7782. end;
  7783. RemoveInstruction(hp1);
  7784. if Unconditional then
  7785. MakeUnconditional(taicpu(hp2))
  7786. else
  7787. begin
  7788. if SetC = C_NONE then
  7789. InternalError(2018061402);
  7790. taicpu(hp2).SetCondition(SetC);
  7791. end;
  7792. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  7793. TmpUsedRegs }
  7794. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  7795. begin
  7796. RemoveCurrentp(p, hp2);
  7797. if taicpu(hp2).opcode = A_SETcc then
  7798. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  7799. else
  7800. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  7801. end
  7802. else
  7803. if taicpu(hp2).opcode = A_SETcc then
  7804. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  7805. else
  7806. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  7807. Result := True;
  7808. end
  7809. else if
  7810. { Make sure the instructions are adjacent }
  7811. (
  7812. not (cs_opt_level3 in current_settings.optimizerswitches) or
  7813. GetNextInstruction(p, hp1)
  7814. ) and
  7815. MatchInstruction(hp1, A_MOV, [S_B]) and
  7816. { Writing to memory is allowed }
  7817. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  7818. begin
  7819. {
  7820. Watch out for sequences such as:
  7821. set(c)b %regb
  7822. movb %regb,(ref)
  7823. movb $0,1(ref)
  7824. movb $0,2(ref)
  7825. movb $0,3(ref)
  7826. Much more efficient to turn it into:
  7827. movl $0,%regl
  7828. set(c)b %regb
  7829. movl %regl,(ref)
  7830. Or:
  7831. set(c)b %regb
  7832. movzbl %regb,%regl
  7833. movl %regl,(ref)
  7834. }
  7835. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  7836. GetNextInstruction(hp1, hp2) and
  7837. MatchInstruction(hp2, A_MOV, [S_B]) and
  7838. (taicpu(hp2).oper[1]^.typ = top_ref) and
  7839. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  7840. begin
  7841. { Don't do anything else except set Result to True }
  7842. end
  7843. else
  7844. begin
  7845. if taicpu(p).oper[0]^.typ = top_reg then
  7846. begin
  7847. TransferUsedRegs(TmpUsedRegs);
  7848. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7849. end;
  7850. { If it's not a register, it's a memory address }
  7851. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  7852. begin
  7853. { Even if the register is still in use, we can minimise the
  7854. pipeline stall by changing the MOV into another SETcc. }
  7855. taicpu(hp1).opcode := A_SETcc;
  7856. taicpu(hp1).condition := taicpu(p).condition;
  7857. if taicpu(hp1).oper[1]^.typ = top_ref then
  7858. begin
  7859. { Swapping the operand pointers like this is probably a
  7860. bit naughty, but it is far faster than using loadoper
  7861. to transfer the reference from oper[1] to oper[0] if
  7862. you take into account the extra procedure calls and
  7863. the memory allocation and deallocation required }
  7864. OperPtr := taicpu(hp1).oper[1];
  7865. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  7866. taicpu(hp1).oper[0] := OperPtr;
  7867. end
  7868. else
  7869. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  7870. taicpu(hp1).clearop(1);
  7871. taicpu(hp1).ops := 1;
  7872. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  7873. end
  7874. else
  7875. begin
  7876. if taicpu(hp1).oper[1]^.typ = top_reg then
  7877. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  7878. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7879. RemoveInstruction(hp1);
  7880. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  7881. end
  7882. end;
  7883. Result := True;
  7884. end;
  7885. end;
  7886. end;
  7887. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  7888. var
  7889. hp1: tai;
  7890. Count: Integer;
  7891. OrigLabel: TAsmLabel;
  7892. begin
  7893. result := False;
  7894. { Sometimes, the optimisations below can permit this }
  7895. RemoveDeadCodeAfterJump(p);
  7896. 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
  7897. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  7898. begin
  7899. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7900. { Also a side-effect of optimisations }
  7901. if CollapseZeroDistJump(p, OrigLabel) then
  7902. begin
  7903. Result := True;
  7904. Exit;
  7905. end;
  7906. hp1 := GetLabelWithSym(OrigLabel);
  7907. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  7908. begin
  7909. case taicpu(hp1).opcode of
  7910. A_RET:
  7911. {
  7912. change
  7913. jmp .L1
  7914. ...
  7915. .L1:
  7916. ret
  7917. into
  7918. ret
  7919. }
  7920. begin
  7921. ConvertJumpToRET(p, hp1);
  7922. result:=true;
  7923. end;
  7924. { Check any kind of direct assignment instruction }
  7925. A_MOV,
  7926. A_MOVD,
  7927. A_MOVQ,
  7928. A_MOVSX,
  7929. {$ifdef x86_64}
  7930. A_MOVSXD,
  7931. {$endif x86_64}
  7932. A_MOVZX,
  7933. A_MOVAPS,
  7934. A_MOVUPS,
  7935. A_MOVSD,
  7936. A_MOVAPD,
  7937. A_MOVUPD,
  7938. A_MOVDQA,
  7939. A_MOVDQU,
  7940. A_VMOVSS,
  7941. A_VMOVAPS,
  7942. A_VMOVUPS,
  7943. A_VMOVSD,
  7944. A_VMOVAPD,
  7945. A_VMOVUPD,
  7946. A_VMOVDQA,
  7947. A_VMOVDQU:
  7948. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  7949. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  7950. begin
  7951. Result := True;
  7952. Exit;
  7953. end;
  7954. else
  7955. ;
  7956. end;
  7957. end;
  7958. end;
  7959. end;
  7960. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  7961. begin
  7962. CanBeCMOV:=assigned(p) and
  7963. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  7964. { we can't use cmov ref,reg because
  7965. ref could be nil and cmov still throws an exception
  7966. if ref=nil but the mov isn't done (FK)
  7967. or ((taicpu(p).oper[0]^.typ = top_ref) and
  7968. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  7969. }
  7970. (taicpu(p).oper[1]^.typ = top_reg) and
  7971. (
  7972. (taicpu(p).oper[0]^.typ = top_reg) or
  7973. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  7974. it is not expected that this can cause a seg. violation }
  7975. (
  7976. (taicpu(p).oper[0]^.typ = top_ref) and
  7977. IsRefSafe(taicpu(p).oper[0]^.ref)
  7978. )
  7979. );
  7980. end;
  7981. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  7982. var
  7983. hp1,hp2: tai;
  7984. {$ifndef i8086}
  7985. hp3,hp4,hpmov2, hp5: tai;
  7986. l : Longint;
  7987. condition : TAsmCond;
  7988. {$endif i8086}
  7989. carryadd_opcode : TAsmOp;
  7990. symbol: TAsmSymbol;
  7991. reg: tsuperregister;
  7992. increg, tmpreg: TRegister;
  7993. begin
  7994. result:=false;
  7995. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  7996. begin
  7997. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7998. if (
  7999. (
  8000. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  8001. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  8002. (Taicpu(hp1).oper[0]^.val=1)
  8003. ) or
  8004. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  8005. ) and
  8006. GetNextInstruction(hp1,hp2) and
  8007. SkipAligns(hp2, hp2) and
  8008. (hp2.typ = ait_label) and
  8009. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  8010. { jb @@1 cmc
  8011. inc/dec operand --> adc/sbb operand,0
  8012. @@1:
  8013. ... and ...
  8014. jnb @@1
  8015. inc/dec operand --> adc/sbb operand,0
  8016. @@1: }
  8017. begin
  8018. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  8019. begin
  8020. case taicpu(hp1).opcode of
  8021. A_INC,
  8022. A_ADD:
  8023. carryadd_opcode:=A_ADC;
  8024. A_DEC,
  8025. A_SUB:
  8026. carryadd_opcode:=A_SBB;
  8027. else
  8028. InternalError(2021011001);
  8029. end;
  8030. Taicpu(p).clearop(0);
  8031. Taicpu(p).ops:=0;
  8032. Taicpu(p).is_jmp:=false;
  8033. Taicpu(p).opcode:=A_CMC;
  8034. Taicpu(p).condition:=C_NONE;
  8035. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  8036. Taicpu(hp1).ops:=2;
  8037. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8038. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8039. else
  8040. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8041. Taicpu(hp1).loadconst(0,0);
  8042. Taicpu(hp1).opcode:=carryadd_opcode;
  8043. result:=true;
  8044. exit;
  8045. end
  8046. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  8047. begin
  8048. case taicpu(hp1).opcode of
  8049. A_INC,
  8050. A_ADD:
  8051. carryadd_opcode:=A_ADC;
  8052. A_DEC,
  8053. A_SUB:
  8054. carryadd_opcode:=A_SBB;
  8055. else
  8056. InternalError(2021011002);
  8057. end;
  8058. Taicpu(hp1).ops:=2;
  8059. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  8060. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8061. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8062. else
  8063. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8064. Taicpu(hp1).loadconst(0,0);
  8065. Taicpu(hp1).opcode:=carryadd_opcode;
  8066. RemoveCurrentP(p, hp1);
  8067. result:=true;
  8068. exit;
  8069. end
  8070. {
  8071. jcc @@1 setcc tmpreg
  8072. inc/dec/add/sub operand -> (movzx tmpreg)
  8073. @@1: add/sub tmpreg,operand
  8074. While this increases code size slightly, it makes the code much faster if the
  8075. jump is unpredictable
  8076. }
  8077. else if not(cs_opt_size in current_settings.optimizerswitches) then
  8078. begin
  8079. { search for an available register which is volatile }
  8080. for reg in tcpuregisterset do
  8081. begin
  8082. if
  8083. {$if defined(i386) or defined(i8086)}
  8084. { Only use registers whose lowest 8-bits can Be accessed }
  8085. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  8086. {$endif i386 or i8086}
  8087. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  8088. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  8089. { We don't need to check if tmpreg is in hp1 or not, because
  8090. it will be marked as in use at p (if not, this is
  8091. indictive of a compiler bug). }
  8092. then
  8093. begin
  8094. TAsmLabel(symbol).decrefs;
  8095. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  8096. Taicpu(p).clearop(0);
  8097. Taicpu(p).ops:=1;
  8098. Taicpu(p).is_jmp:=false;
  8099. Taicpu(p).opcode:=A_SETcc;
  8100. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  8101. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  8102. Taicpu(p).loadreg(0,increg);
  8103. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  8104. begin
  8105. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  8106. R_SUBW:
  8107. begin
  8108. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  8109. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  8110. end;
  8111. R_SUBD:
  8112. begin
  8113. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  8114. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  8115. end;
  8116. {$ifdef x86_64}
  8117. R_SUBQ:
  8118. begin
  8119. { MOVZX doesn't have a 64-bit variant, because
  8120. the 32-bit version implicitly zeroes the
  8121. upper 32-bits of the destination register }
  8122. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  8123. newreg(R_INTREGISTER,reg,R_SUBD));
  8124. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  8125. end;
  8126. {$endif x86_64}
  8127. else
  8128. Internalerror(2020030601);
  8129. end;
  8130. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  8131. asml.InsertAfter(hp2,p);
  8132. end
  8133. else
  8134. tmpreg := increg;
  8135. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  8136. begin
  8137. Taicpu(hp1).ops:=2;
  8138. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  8139. end;
  8140. Taicpu(hp1).loadreg(0,tmpreg);
  8141. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  8142. Result := True;
  8143. { p is no longer a Jcc instruction, so exit }
  8144. Exit;
  8145. end;
  8146. end;
  8147. end;
  8148. end;
  8149. { Detect the following:
  8150. jmp<cond> @Lbl1
  8151. jmp @Lbl2
  8152. ...
  8153. @Lbl1:
  8154. ret
  8155. Change to:
  8156. jmp<inv_cond> @Lbl2
  8157. ret
  8158. }
  8159. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  8160. begin
  8161. hp2:=getlabelwithsym(TAsmLabel(symbol));
  8162. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  8163. MatchInstruction(hp2,A_RET,[S_NO]) then
  8164. begin
  8165. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8166. { Change label address to that of the unconditional jump }
  8167. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  8168. TAsmLabel(symbol).DecRefs;
  8169. taicpu(hp1).opcode := A_RET;
  8170. taicpu(hp1).is_jmp := false;
  8171. taicpu(hp1).ops := taicpu(hp2).ops;
  8172. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  8173. case taicpu(hp2).ops of
  8174. 0:
  8175. taicpu(hp1).clearop(0);
  8176. 1:
  8177. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  8178. else
  8179. internalerror(2016041302);
  8180. end;
  8181. end;
  8182. {$ifndef i8086}
  8183. end
  8184. {
  8185. convert
  8186. j<c> .L1
  8187. mov 1,reg
  8188. jmp .L2
  8189. .L1
  8190. mov 0,reg
  8191. .L2
  8192. into
  8193. mov 0,reg
  8194. set<not(c)> reg
  8195. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8196. would destroy the flag contents
  8197. }
  8198. else if MatchInstruction(hp1,A_MOV,[]) and
  8199. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8200. {$ifdef i386}
  8201. (
  8202. { Under i386, ESI, EDI, EBP and ESP
  8203. don't have an 8-bit representation }
  8204. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8205. ) and
  8206. {$endif i386}
  8207. (taicpu(hp1).oper[0]^.val=1) and
  8208. GetNextInstruction(hp1,hp2) and
  8209. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8210. GetNextInstruction(hp2,hp3) and
  8211. { skip align }
  8212. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  8213. (hp3.typ=ait_label) and
  8214. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  8215. (tai_label(hp3).labsym.getrefs=1) and
  8216. GetNextInstruction(hp3,hp4) and
  8217. MatchInstruction(hp4,A_MOV,[]) and
  8218. MatchOpType(taicpu(hp4),top_const,top_reg) and
  8219. (taicpu(hp4).oper[0]^.val=0) and
  8220. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8221. GetNextInstruction(hp4,hp5) and
  8222. (hp5.typ=ait_label) and
  8223. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  8224. (tai_label(hp5).labsym.getrefs=1) then
  8225. begin
  8226. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  8227. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  8228. { remove last label }
  8229. RemoveInstruction(hp5);
  8230. { remove second label }
  8231. RemoveInstruction(hp3);
  8232. { if align is present remove it }
  8233. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  8234. RemoveInstruction(hp3);
  8235. { remove jmp }
  8236. RemoveInstruction(hp2);
  8237. if taicpu(hp1).opsize=S_B then
  8238. RemoveInstruction(hp1)
  8239. else
  8240. taicpu(hp1).loadconst(0,0);
  8241. taicpu(hp4).opcode:=A_SETcc;
  8242. taicpu(hp4).opsize:=S_B;
  8243. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  8244. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  8245. taicpu(hp4).opercnt:=1;
  8246. taicpu(hp4).ops:=1;
  8247. taicpu(hp4).freeop(1);
  8248. RemoveCurrentP(p);
  8249. Result:=true;
  8250. exit;
  8251. end
  8252. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  8253. begin
  8254. { check for
  8255. jCC xxx
  8256. <several movs>
  8257. xxx:
  8258. }
  8259. l:=0;
  8260. while assigned(hp1) and
  8261. CanBeCMOV(hp1) and
  8262. { stop on labels }
  8263. not(hp1.typ=ait_label) do
  8264. begin
  8265. inc(l);
  8266. GetNextInstruction(hp1,hp1);
  8267. end;
  8268. if assigned(hp1) then
  8269. begin
  8270. if FindLabel(tasmlabel(symbol),hp1) then
  8271. begin
  8272. if (l<=4) and (l>0) then
  8273. begin
  8274. condition:=inverse_cond(taicpu(p).condition);
  8275. UpdateUsedRegs(tai(p.next));
  8276. GetNextInstruction(p,hp1);
  8277. repeat
  8278. if not Assigned(hp1) then
  8279. InternalError(2018062900);
  8280. taicpu(hp1).opcode:=A_CMOVcc;
  8281. taicpu(hp1).condition:=condition;
  8282. UpdateUsedRegs(tai(hp1.next));
  8283. GetNextInstruction(hp1,hp1);
  8284. until not(CanBeCMOV(hp1));
  8285. { Remember what hp1 is in case there's multiple aligns to get rid of }
  8286. hp2 := hp1;
  8287. repeat
  8288. if not Assigned(hp2) then
  8289. InternalError(2018062910);
  8290. case hp2.typ of
  8291. ait_label:
  8292. { What we expected - break out of the loop (it won't be a dead label at the top of
  8293. a cluster because that was optimised at an earlier stage) }
  8294. Break;
  8295. ait_align:
  8296. { Go to the next entry until a label is found (may be multiple aligns before it) }
  8297. begin
  8298. hp2 := tai(hp2.Next);
  8299. Continue;
  8300. end;
  8301. else
  8302. begin
  8303. { Might be a comment or temporary allocation entry }
  8304. if not (hp2.typ in SkipInstr) then
  8305. InternalError(2018062911);
  8306. hp2 := tai(hp2.Next);
  8307. Continue;
  8308. end;
  8309. end;
  8310. until False;
  8311. { Now we can safely decrement the reference count }
  8312. tasmlabel(symbol).decrefs;
  8313. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  8314. { Remove the original jump }
  8315. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  8316. UpdateUsedRegs(tai(hp2.next));
  8317. GetNextInstruction(hp2, p); { Instruction after the label }
  8318. { Remove the label if this is its final reference }
  8319. if (tasmlabel(symbol).getrefs=0) then
  8320. StripLabelFast(hp1);
  8321. if Assigned(p) then
  8322. result:=true;
  8323. exit;
  8324. end;
  8325. end
  8326. else
  8327. begin
  8328. { check further for
  8329. jCC xxx
  8330. <several movs 1>
  8331. jmp yyy
  8332. xxx:
  8333. <several movs 2>
  8334. yyy:
  8335. }
  8336. { hp2 points to jmp yyy }
  8337. hp2:=hp1;
  8338. { skip hp1 to xxx (or an align right before it) }
  8339. GetNextInstruction(hp1, hp1);
  8340. if assigned(hp2) and
  8341. assigned(hp1) and
  8342. (l<=3) and
  8343. (hp2.typ=ait_instruction) and
  8344. (taicpu(hp2).is_jmp) and
  8345. (taicpu(hp2).condition=C_None) and
  8346. { real label and jump, no further references to the
  8347. label are allowed }
  8348. (tasmlabel(symbol).getrefs=1) and
  8349. FindLabel(tasmlabel(symbol),hp1) then
  8350. begin
  8351. l:=0;
  8352. { skip hp1 to <several moves 2> }
  8353. if (hp1.typ = ait_align) then
  8354. GetNextInstruction(hp1, hp1);
  8355. GetNextInstruction(hp1, hpmov2);
  8356. hp1 := hpmov2;
  8357. while assigned(hp1) and
  8358. CanBeCMOV(hp1) do
  8359. begin
  8360. inc(l);
  8361. GetNextInstruction(hp1, hp1);
  8362. end;
  8363. { hp1 points to yyy (or an align right before it) }
  8364. hp3 := hp1;
  8365. if assigned(hp1) and
  8366. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  8367. begin
  8368. condition:=inverse_cond(taicpu(p).condition);
  8369. UpdateUsedRegs(tai(p.next));
  8370. GetNextInstruction(p,hp1);
  8371. repeat
  8372. taicpu(hp1).opcode:=A_CMOVcc;
  8373. taicpu(hp1).condition:=condition;
  8374. UpdateUsedRegs(tai(hp1.next));
  8375. GetNextInstruction(hp1,hp1);
  8376. until not(assigned(hp1)) or
  8377. not(CanBeCMOV(hp1));
  8378. condition:=inverse_cond(condition);
  8379. if GetLastInstruction(hpmov2,hp1) then
  8380. UpdateUsedRegs(tai(hp1.next));
  8381. hp1 := hpmov2;
  8382. { hp1 is now at <several movs 2> }
  8383. while Assigned(hp1) and CanBeCMOV(hp1) do
  8384. begin
  8385. taicpu(hp1).opcode:=A_CMOVcc;
  8386. taicpu(hp1).condition:=condition;
  8387. UpdateUsedRegs(tai(hp1.next));
  8388. GetNextInstruction(hp1,hp1);
  8389. end;
  8390. hp1 := p;
  8391. { Get first instruction after label }
  8392. UpdateUsedRegs(tai(hp3.next));
  8393. GetNextInstruction(hp3, p);
  8394. if assigned(p) and (hp3.typ = ait_align) then
  8395. GetNextInstruction(p, p);
  8396. { Don't dereference yet, as doing so will cause
  8397. GetNextInstruction to skip the label and
  8398. optional align marker. [Kit] }
  8399. GetNextInstruction(hp2, hp4);
  8400. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  8401. { remove jCC }
  8402. RemoveInstruction(hp1);
  8403. { Now we can safely decrement it }
  8404. tasmlabel(symbol).decrefs;
  8405. { Remove label xxx (it will have a ref of zero due to the initial check }
  8406. StripLabelFast(hp4);
  8407. { remove jmp }
  8408. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  8409. RemoveInstruction(hp2);
  8410. { As before, now we can safely decrement it }
  8411. tasmlabel(symbol).decrefs;
  8412. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  8413. if tasmlabel(symbol).getrefs = 0 then
  8414. StripLabelFast(hp3);
  8415. if Assigned(p) then
  8416. result:=true;
  8417. exit;
  8418. end;
  8419. end;
  8420. end;
  8421. end;
  8422. {$endif i8086}
  8423. end;
  8424. end;
  8425. end;
  8426. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  8427. var
  8428. hp1,hp2: tai;
  8429. reg_and_hp1_is_instr: Boolean;
  8430. begin
  8431. result:=false;
  8432. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  8433. GetNextInstruction(p,hp1) and
  8434. (hp1.typ = ait_instruction);
  8435. if reg_and_hp1_is_instr and
  8436. (
  8437. (taicpu(hp1).opcode <> A_LEA) or
  8438. { If the LEA instruction can be converted into an arithmetic instruction,
  8439. it may be possible to then fold it. }
  8440. (
  8441. { If the flags register is in use, don't change the instruction
  8442. to an ADD otherwise this will scramble the flags. [Kit] }
  8443. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  8444. ConvertLEA(taicpu(hp1))
  8445. )
  8446. ) and
  8447. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  8448. GetNextInstruction(hp1,hp2) and
  8449. MatchInstruction(hp2,A_MOV,[]) and
  8450. (taicpu(hp2).oper[0]^.typ = top_reg) and
  8451. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  8452. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  8453. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  8454. {$ifdef i386}
  8455. { not all registers have byte size sub registers on i386 }
  8456. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  8457. {$endif i386}
  8458. (((taicpu(hp1).ops=2) and
  8459. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8460. ((taicpu(hp1).ops=1) and
  8461. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  8462. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  8463. begin
  8464. { change movsX/movzX reg/ref, reg2
  8465. add/sub/or/... reg3/$const, reg2
  8466. mov reg2 reg/ref
  8467. to add/sub/or/... reg3/$const, reg/ref }
  8468. { by example:
  8469. movswl %si,%eax movswl %si,%eax p
  8470. decl %eax addl %edx,%eax hp1
  8471. movw %ax,%si movw %ax,%si hp2
  8472. ->
  8473. movswl %si,%eax movswl %si,%eax p
  8474. decw %eax addw %edx,%eax hp1
  8475. movw %ax,%si movw %ax,%si hp2
  8476. }
  8477. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  8478. {
  8479. ->
  8480. movswl %si,%eax movswl %si,%eax p
  8481. decw %si addw %dx,%si hp1
  8482. movw %ax,%si movw %ax,%si hp2
  8483. }
  8484. case taicpu(hp1).ops of
  8485. 1:
  8486. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  8487. 2:
  8488. begin
  8489. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  8490. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8491. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  8492. end;
  8493. else
  8494. internalerror(2008042702);
  8495. end;
  8496. {
  8497. ->
  8498. decw %si addw %dx,%si p
  8499. }
  8500. DebugMsg(SPeepholeOptimization + 'var3',p);
  8501. RemoveCurrentP(p, hp1);
  8502. RemoveInstruction(hp2);
  8503. end
  8504. else if reg_and_hp1_is_instr and
  8505. (taicpu(hp1).opcode = A_MOV) and
  8506. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8507. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  8508. {$ifdef x86_64}
  8509. { check for implicit extension to 64 bit }
  8510. or
  8511. ((taicpu(p).opsize in [S_BL,S_WL]) and
  8512. (taicpu(hp1).opsize=S_Q) and
  8513. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  8514. )
  8515. {$endif x86_64}
  8516. )
  8517. then
  8518. begin
  8519. { change
  8520. movx %reg1,%reg2
  8521. mov %reg2,%reg3
  8522. dealloc %reg2
  8523. into
  8524. movx %reg,%reg3
  8525. }
  8526. TransferUsedRegs(TmpUsedRegs);
  8527. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8528. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8529. begin
  8530. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  8531. {$ifdef x86_64}
  8532. if (taicpu(p).opsize in [S_BL,S_WL]) and
  8533. (taicpu(hp1).opsize=S_Q) then
  8534. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  8535. else
  8536. {$endif x86_64}
  8537. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8538. RemoveInstruction(hp1);
  8539. end;
  8540. end
  8541. else if reg_and_hp1_is_instr and
  8542. ((taicpu(hp1).opcode=A_MOV) or
  8543. (taicpu(hp1).opcode=A_ADD) or
  8544. (taicpu(hp1).opcode=A_SUB) or
  8545. (taicpu(hp1).opcode=A_CMP) or
  8546. (taicpu(hp1).opcode=A_OR) or
  8547. (taicpu(hp1).opcode=A_XOR) or
  8548. (taicpu(hp1).opcode=A_AND)
  8549. ) and
  8550. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8551. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  8552. (taicpu(hp1).opsize=S_B)) or
  8553. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  8554. (taicpu(hp1).opsize=S_W))
  8555. {$ifdef x86_64}
  8556. or ((taicpu(p).opsize=S_LQ) and
  8557. (taicpu(hp1).opsize=S_L))
  8558. {$endif x86_64}
  8559. ) and
  8560. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  8561. begin
  8562. { change
  8563. movx %reg1,%reg2
  8564. mov %reg2,%reg3
  8565. dealloc %reg2
  8566. into
  8567. mov %reg1,%reg3
  8568. if the second mov accesses only the bits stored in reg1
  8569. }
  8570. TransferUsedRegs(TmpUsedRegs);
  8571. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8572. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8573. begin
  8574. DebugMsg(SPeepholeOptimization + 'MovxOp2Op',p);
  8575. if taicpu(p).oper[0]^.typ=top_reg then
  8576. begin
  8577. case taicpu(hp1).opsize of
  8578. S_B:
  8579. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  8580. S_W:
  8581. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  8582. S_L:
  8583. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  8584. else
  8585. Internalerror(2020102301);
  8586. end;
  8587. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  8588. end
  8589. else
  8590. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  8591. RemoveCurrentP(p);
  8592. result:=true;
  8593. exit;
  8594. end;
  8595. end
  8596. else if reg_and_hp1_is_instr and
  8597. (taicpu(p).oper[0]^.typ = top_reg) and
  8598. (
  8599. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  8600. ) and
  8601. (taicpu(hp1).oper[0]^.typ = top_const) and
  8602. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8603. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8604. { Minimum shift value allowed is the bit difference between the sizes }
  8605. (taicpu(hp1).oper[0]^.val >=
  8606. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  8607. 8 * (
  8608. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  8609. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  8610. )
  8611. ) then
  8612. begin
  8613. { For:
  8614. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  8615. shl/sal ##, %reg1
  8616. Remove the movsx/movzx instruction if the shift overwrites the
  8617. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  8618. }
  8619. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  8620. RemoveCurrentP(p, hp1);
  8621. Result := True;
  8622. Exit;
  8623. end
  8624. else if reg_and_hp1_is_instr and
  8625. (taicpu(p).oper[0]^.typ = top_reg) and
  8626. (
  8627. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  8628. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  8629. ) and
  8630. (taicpu(hp1).oper[0]^.typ = top_const) and
  8631. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8632. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8633. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  8634. (taicpu(hp1).oper[0]^.val <
  8635. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  8636. 8 * (
  8637. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  8638. )
  8639. ) then
  8640. begin
  8641. { For:
  8642. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  8643. sar ##, %reg1 shr ##, %reg1
  8644. Move the shift to before the movx instruction if the shift value
  8645. is not too large.
  8646. }
  8647. asml.Remove(hp1);
  8648. asml.InsertBefore(hp1, p);
  8649. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  8650. case taicpu(p).opsize of
  8651. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  8652. taicpu(hp1).opsize := S_B;
  8653. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  8654. taicpu(hp1).opsize := S_W;
  8655. {$ifdef x86_64}
  8656. S_LQ:
  8657. taicpu(hp1).opsize := S_L;
  8658. {$endif}
  8659. else
  8660. InternalError(2020112401);
  8661. end;
  8662. if (taicpu(hp1).opcode = A_SHR) then
  8663. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  8664. else
  8665. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  8666. Result := True;
  8667. end
  8668. else if taicpu(p).opcode=A_MOVZX then
  8669. begin
  8670. { removes superfluous And's after movzx's }
  8671. if reg_and_hp1_is_instr and
  8672. (taicpu(hp1).opcode = A_AND) and
  8673. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8674. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  8675. {$ifdef x86_64}
  8676. { check for implicit extension to 64 bit }
  8677. or
  8678. ((taicpu(p).opsize in [S_BL,S_WL]) and
  8679. (taicpu(hp1).opsize=S_Q) and
  8680. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  8681. )
  8682. {$endif x86_64}
  8683. )
  8684. then
  8685. begin
  8686. case taicpu(p).opsize Of
  8687. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8688. if (taicpu(hp1).oper[0]^.val = $ff) then
  8689. begin
  8690. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  8691. RemoveInstruction(hp1);
  8692. Result:=true;
  8693. exit;
  8694. end;
  8695. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8696. if (taicpu(hp1).oper[0]^.val = $ffff) then
  8697. begin
  8698. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  8699. RemoveInstruction(hp1);
  8700. Result:=true;
  8701. exit;
  8702. end;
  8703. {$ifdef x86_64}
  8704. S_LQ:
  8705. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  8706. begin
  8707. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  8708. RemoveInstruction(hp1);
  8709. Result:=true;
  8710. exit;
  8711. end;
  8712. {$endif x86_64}
  8713. else
  8714. ;
  8715. end;
  8716. { we cannot get rid of the and, but can we get rid of the movz ?}
  8717. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  8718. begin
  8719. case taicpu(p).opsize Of
  8720. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8721. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  8722. begin
  8723. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  8724. RemoveCurrentP(p,hp1);
  8725. Result:=true;
  8726. exit;
  8727. end;
  8728. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8729. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  8730. begin
  8731. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  8732. RemoveCurrentP(p,hp1);
  8733. Result:=true;
  8734. exit;
  8735. end;
  8736. {$ifdef x86_64}
  8737. S_LQ:
  8738. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  8739. begin
  8740. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  8741. RemoveCurrentP(p,hp1);
  8742. Result:=true;
  8743. exit;
  8744. end;
  8745. {$endif x86_64}
  8746. else
  8747. ;
  8748. end;
  8749. end;
  8750. end;
  8751. { changes some movzx constructs to faster synonyms (all examples
  8752. are given with eax/ax, but are also valid for other registers)}
  8753. if MatchOpType(taicpu(p),top_reg,top_reg) then
  8754. begin
  8755. case taicpu(p).opsize of
  8756. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  8757. (the machine code is equivalent to movzbl %al,%eax), but the
  8758. code generator still generates that assembler instruction and
  8759. it is silently converted. This should probably be checked.
  8760. [Kit] }
  8761. S_BW:
  8762. begin
  8763. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8764. (
  8765. not IsMOVZXAcceptable
  8766. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  8767. or (
  8768. (cs_opt_size in current_settings.optimizerswitches) and
  8769. (taicpu(p).oper[1]^.reg = NR_AX)
  8770. )
  8771. ) then
  8772. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  8773. begin
  8774. DebugMsg(SPeepholeOptimization + 'var7',p);
  8775. taicpu(p).opcode := A_AND;
  8776. taicpu(p).changeopsize(S_W);
  8777. taicpu(p).loadConst(0,$ff);
  8778. Result := True;
  8779. end
  8780. else if not IsMOVZXAcceptable and
  8781. GetNextInstruction(p, hp1) and
  8782. (tai(hp1).typ = ait_instruction) and
  8783. (taicpu(hp1).opcode = A_AND) and
  8784. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8785. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8786. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  8787. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  8788. begin
  8789. DebugMsg(SPeepholeOptimization + 'var8',p);
  8790. taicpu(p).opcode := A_MOV;
  8791. taicpu(p).changeopsize(S_W);
  8792. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  8793. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8794. Result := True;
  8795. end;
  8796. end;
  8797. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  8798. S_BL:
  8799. begin
  8800. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8801. (
  8802. not IsMOVZXAcceptable
  8803. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  8804. or (
  8805. (cs_opt_size in current_settings.optimizerswitches) and
  8806. (taicpu(p).oper[1]^.reg = NR_EAX)
  8807. )
  8808. ) then
  8809. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  8810. begin
  8811. DebugMsg(SPeepholeOptimization + 'var9',p);
  8812. taicpu(p).opcode := A_AND;
  8813. taicpu(p).changeopsize(S_L);
  8814. taicpu(p).loadConst(0,$ff);
  8815. Result := True;
  8816. end
  8817. else if not IsMOVZXAcceptable and
  8818. GetNextInstruction(p, hp1) and
  8819. (tai(hp1).typ = ait_instruction) and
  8820. (taicpu(hp1).opcode = A_AND) and
  8821. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8822. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8823. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  8824. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  8825. begin
  8826. DebugMsg(SPeepholeOptimization + 'var10',p);
  8827. taicpu(p).opcode := A_MOV;
  8828. taicpu(p).changeopsize(S_L);
  8829. { do not use R_SUBWHOLE
  8830. as movl %rdx,%eax
  8831. is invalid in assembler PM }
  8832. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8833. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8834. Result := True;
  8835. end;
  8836. end;
  8837. {$endif i8086}
  8838. S_WL:
  8839. if not IsMOVZXAcceptable then
  8840. begin
  8841. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  8842. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  8843. begin
  8844. DebugMsg(SPeepholeOptimization + 'var11',p);
  8845. taicpu(p).opcode := A_AND;
  8846. taicpu(p).changeopsize(S_L);
  8847. taicpu(p).loadConst(0,$ffff);
  8848. Result := True;
  8849. end
  8850. else if GetNextInstruction(p, hp1) and
  8851. (tai(hp1).typ = ait_instruction) and
  8852. (taicpu(hp1).opcode = A_AND) and
  8853. (taicpu(hp1).oper[0]^.typ = top_const) and
  8854. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8855. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8856. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  8857. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  8858. begin
  8859. DebugMsg(SPeepholeOptimization + 'var12',p);
  8860. taicpu(p).opcode := A_MOV;
  8861. taicpu(p).changeopsize(S_L);
  8862. { do not use R_SUBWHOLE
  8863. as movl %rdx,%eax
  8864. is invalid in assembler PM }
  8865. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8866. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  8867. Result := True;
  8868. end;
  8869. end;
  8870. else
  8871. InternalError(2017050705);
  8872. end;
  8873. end
  8874. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  8875. begin
  8876. if GetNextInstruction(p, hp1) and
  8877. (tai(hp1).typ = ait_instruction) and
  8878. (taicpu(hp1).opcode = A_AND) and
  8879. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8880. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8881. begin
  8882. //taicpu(p).opcode := A_MOV;
  8883. case taicpu(p).opsize Of
  8884. S_BL:
  8885. begin
  8886. DebugMsg(SPeepholeOptimization + 'var13',p);
  8887. taicpu(hp1).changeopsize(S_L);
  8888. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8889. end;
  8890. S_WL:
  8891. begin
  8892. DebugMsg(SPeepholeOptimization + 'var14',p);
  8893. taicpu(hp1).changeopsize(S_L);
  8894. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  8895. end;
  8896. S_BW:
  8897. begin
  8898. DebugMsg(SPeepholeOptimization + 'var15',p);
  8899. taicpu(hp1).changeopsize(S_W);
  8900. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8901. end;
  8902. else
  8903. Internalerror(2017050704)
  8904. end;
  8905. Result := True;
  8906. end;
  8907. end;
  8908. end;
  8909. end;
  8910. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  8911. var
  8912. hp1, hp2 : tai;
  8913. MaskLength : Cardinal;
  8914. MaskedBits : TCgInt;
  8915. begin
  8916. Result:=false;
  8917. { There are no optimisations for reference targets }
  8918. if (taicpu(p).oper[1]^.typ <> top_reg) then
  8919. Exit;
  8920. while GetNextInstruction(p, hp1) and
  8921. (hp1.typ = ait_instruction) do
  8922. begin
  8923. if (taicpu(p).oper[0]^.typ = top_const) then
  8924. begin
  8925. case taicpu(hp1).opcode of
  8926. A_AND:
  8927. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8928. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8929. { the second register must contain the first one, so compare their subreg types }
  8930. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  8931. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  8932. { change
  8933. and const1, reg
  8934. and const2, reg
  8935. to
  8936. and (const1 and const2), reg
  8937. }
  8938. begin
  8939. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  8940. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  8941. RemoveCurrentP(p, hp1);
  8942. Result:=true;
  8943. exit;
  8944. end;
  8945. A_CMP:
  8946. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  8947. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  8948. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8949. { Just check that the condition on the next instruction is compatible }
  8950. GetNextInstruction(hp1, hp2) and
  8951. (hp2.typ = ait_instruction) and
  8952. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  8953. then
  8954. { change
  8955. and 2^n, reg
  8956. cmp 2^n, reg
  8957. j(c) / set(c) / cmov(c) (c is equal or not equal)
  8958. to
  8959. and 2^n, reg
  8960. test reg, reg
  8961. j(~c) / set(~c) / cmov(~c)
  8962. }
  8963. begin
  8964. { Keep TEST instruction in, rather than remove it, because
  8965. it may trigger other optimisations such as MovAndTest2Test }
  8966. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  8967. taicpu(hp1).opcode := A_TEST;
  8968. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  8969. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  8970. Result := True;
  8971. Exit;
  8972. end;
  8973. A_MOVZX:
  8974. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8975. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  8976. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8977. (
  8978. (
  8979. (taicpu(p).opsize=S_W) and
  8980. (taicpu(hp1).opsize=S_BW)
  8981. ) or
  8982. (
  8983. (taicpu(p).opsize=S_L) and
  8984. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  8985. )
  8986. {$ifdef x86_64}
  8987. or
  8988. (
  8989. (taicpu(p).opsize=S_Q) and
  8990. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  8991. )
  8992. {$endif x86_64}
  8993. ) then
  8994. begin
  8995. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  8996. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  8997. ) or
  8998. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  8999. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  9000. then
  9001. begin
  9002. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  9003. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  9004. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  9005. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  9006. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  9007. }
  9008. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  9009. RemoveInstruction(hp1);
  9010. { See if there are other optimisations possible }
  9011. Continue;
  9012. end;
  9013. end;
  9014. A_SHL:
  9015. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  9016. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9017. begin
  9018. {$ifopt R+}
  9019. {$define RANGE_WAS_ON}
  9020. {$R-}
  9021. {$endif}
  9022. { get length of potential and mask }
  9023. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  9024. { really a mask? }
  9025. {$ifdef RANGE_WAS_ON}
  9026. {$R+}
  9027. {$endif}
  9028. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  9029. { unmasked part shifted out? }
  9030. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  9031. begin
  9032. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  9033. RemoveCurrentP(p, hp1);
  9034. Result:=true;
  9035. exit;
  9036. end;
  9037. end;
  9038. A_SHR:
  9039. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  9040. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9041. (taicpu(hp1).oper[0]^.val <= 63) then
  9042. begin
  9043. { Does SHR combined with the AND cover all the bits?
  9044. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  9045. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  9046. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  9047. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  9048. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  9049. begin
  9050. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  9051. RemoveCurrentP(p, hp1);
  9052. Result := True;
  9053. Exit;
  9054. end;
  9055. end;
  9056. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9057. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9058. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  9059. begin
  9060. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  9061. (
  9062. (
  9063. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  9064. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  9065. ) or (
  9066. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  9067. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  9068. {$ifdef x86_64}
  9069. ) or (
  9070. (taicpu(hp1).opsize = S_LQ) and
  9071. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  9072. {$endif x86_64}
  9073. )
  9074. ) then
  9075. begin
  9076. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  9077. begin
  9078. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  9079. RemoveInstruction(hp1);
  9080. { See if there are other optimisations possible }
  9081. Continue;
  9082. end;
  9083. { The super-registers are the same though.
  9084. Note that this change by itself doesn't improve
  9085. code speed, but it opens up other optimisations. }
  9086. {$ifdef x86_64}
  9087. { Convert 64-bit register to 32-bit }
  9088. case taicpu(hp1).opsize of
  9089. S_BQ:
  9090. begin
  9091. taicpu(hp1).opsize := S_BL;
  9092. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  9093. end;
  9094. S_WQ:
  9095. begin
  9096. taicpu(hp1).opsize := S_WL;
  9097. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  9098. end
  9099. else
  9100. ;
  9101. end;
  9102. {$endif x86_64}
  9103. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  9104. taicpu(hp1).opcode := A_MOVZX;
  9105. { See if there are other optimisations possible }
  9106. Continue;
  9107. end;
  9108. end;
  9109. else
  9110. ;
  9111. end;
  9112. end;
  9113. if (taicpu(hp1).is_jmp) and
  9114. (taicpu(hp1).opcode<>A_JMP) and
  9115. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  9116. begin
  9117. { change
  9118. and x, reg
  9119. jxx
  9120. to
  9121. test x, reg
  9122. jxx
  9123. if reg is deallocated before the
  9124. jump, but only if it's a conditional jump (PFV)
  9125. }
  9126. taicpu(p).opcode := A_TEST;
  9127. Exit;
  9128. end;
  9129. Break;
  9130. end;
  9131. { Lone AND tests }
  9132. if (taicpu(p).oper[0]^.typ = top_const) then
  9133. begin
  9134. {
  9135. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  9136. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  9137. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  9138. }
  9139. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  9140. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  9141. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  9142. begin
  9143. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  9144. if taicpu(p).opsize = S_L then
  9145. begin
  9146. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  9147. Result := True;
  9148. end;
  9149. end;
  9150. end;
  9151. { Backward check to determine necessity of and %reg,%reg }
  9152. if (taicpu(p).oper[0]^.typ = top_reg) and
  9153. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  9154. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9155. GetLastInstruction(p, hp2) and
  9156. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  9157. { Check size of adjacent instruction to determine if the AND is
  9158. effectively a null operation }
  9159. (
  9160. (taicpu(p).opsize = taicpu(hp2).opsize) or
  9161. { Note: Don't include S_Q }
  9162. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  9163. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  9164. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  9165. ) then
  9166. begin
  9167. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  9168. { If GetNextInstruction returned False, hp1 will be nil }
  9169. RemoveCurrentP(p, hp1);
  9170. Result := True;
  9171. Exit;
  9172. end;
  9173. end;
  9174. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  9175. var
  9176. hp1: tai; NewRef: TReference;
  9177. { This entire nested function is used in an if-statement below, but we
  9178. want to avoid all the used reg transfers and GetNextInstruction calls
  9179. until we really have to check }
  9180. function MemRegisterNotUsedLater: Boolean; inline;
  9181. var
  9182. hp2: tai;
  9183. begin
  9184. TransferUsedRegs(TmpUsedRegs);
  9185. hp2 := p;
  9186. repeat
  9187. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9188. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9189. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  9190. end;
  9191. begin
  9192. Result := False;
  9193. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  9194. Exit;
  9195. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  9196. begin
  9197. { Change:
  9198. add %reg2,%reg1
  9199. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  9200. To:
  9201. mov/s/z #(%reg1,%reg2),%reg1
  9202. }
  9203. if MatchOpType(taicpu(p), top_reg, top_reg) and
  9204. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  9205. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  9206. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  9207. (
  9208. (
  9209. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  9210. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  9211. { r/esp cannot be an index }
  9212. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  9213. ) or (
  9214. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  9215. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  9216. )
  9217. ) and (
  9218. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  9219. (
  9220. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  9221. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  9222. MemRegisterNotUsedLater
  9223. )
  9224. ) then
  9225. begin
  9226. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  9227. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  9228. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  9229. RemoveCurrentp(p, hp1);
  9230. Result := True;
  9231. Exit;
  9232. end;
  9233. { Change:
  9234. addl/q $x,%reg1
  9235. movl/q %reg1,%reg2
  9236. To:
  9237. leal/q $x(%reg1),%reg2
  9238. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  9239. Breaks the dependency chain.
  9240. }
  9241. if MatchOpType(taicpu(p),top_const,top_reg) and
  9242. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  9243. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9244. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  9245. (
  9246. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  9247. not (cs_opt_size in current_settings.optimizerswitches) or
  9248. (
  9249. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  9250. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  9251. )
  9252. ) then
  9253. begin
  9254. { Change the MOV instruction to a LEA instruction, and update the
  9255. first operand }
  9256. reference_reset(NewRef, 1, []);
  9257. NewRef.base := taicpu(p).oper[1]^.reg;
  9258. NewRef.scalefactor := 1;
  9259. NewRef.offset := taicpu(p).oper[0]^.val;
  9260. taicpu(hp1).opcode := A_LEA;
  9261. taicpu(hp1).loadref(0, NewRef);
  9262. TransferUsedRegs(TmpUsedRegs);
  9263. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9264. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  9265. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  9266. begin
  9267. { Move what is now the LEA instruction to before the SUB instruction }
  9268. Asml.Remove(hp1);
  9269. Asml.InsertBefore(hp1, p);
  9270. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  9271. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  9272. p := hp1;
  9273. end
  9274. else
  9275. begin
  9276. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  9277. RemoveCurrentP(p, hp1);
  9278. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  9279. end;
  9280. Result := True;
  9281. end;
  9282. end;
  9283. end;
  9284. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  9285. var
  9286. SubReg: TSubRegister;
  9287. begin
  9288. Result:=false;
  9289. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  9290. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  9291. with taicpu(p).oper[0]^.ref^ do
  9292. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  9293. begin
  9294. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  9295. begin
  9296. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  9297. taicpu(p).opcode := A_ADD;
  9298. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  9299. Result := True;
  9300. end
  9301. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  9302. begin
  9303. if (base <> NR_NO) then
  9304. begin
  9305. if (scalefactor <= 1) then
  9306. begin
  9307. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  9308. taicpu(p).opcode := A_ADD;
  9309. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  9310. Result := True;
  9311. end;
  9312. end
  9313. else
  9314. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  9315. if (scalefactor in [2, 4, 8]) then
  9316. begin
  9317. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  9318. taicpu(p).loadconst(0, BsrByte(scalefactor));
  9319. taicpu(p).opcode := A_SHL;
  9320. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  9321. Result := True;
  9322. end;
  9323. end;
  9324. end;
  9325. end;
  9326. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  9327. var
  9328. hp1: tai; NewRef: TReference;
  9329. begin
  9330. { Change:
  9331. subl/q $x,%reg1
  9332. movl/q %reg1,%reg2
  9333. To:
  9334. leal/q $-x(%reg1),%reg2
  9335. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  9336. Breaks the dependency chain and potentially permits the removal of
  9337. a CMP instruction if one follows.
  9338. }
  9339. Result := False;
  9340. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9341. MatchOpType(taicpu(p),top_const,top_reg) and
  9342. GetNextInstruction(p, hp1) and
  9343. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  9344. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9345. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  9346. (
  9347. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  9348. not (cs_opt_size in current_settings.optimizerswitches) or
  9349. (
  9350. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  9351. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  9352. )
  9353. ) then
  9354. begin
  9355. { Change the MOV instruction to a LEA instruction, and update the
  9356. first operand }
  9357. reference_reset(NewRef, 1, []);
  9358. NewRef.base := taicpu(p).oper[1]^.reg;
  9359. NewRef.scalefactor := 1;
  9360. NewRef.offset := -taicpu(p).oper[0]^.val;
  9361. taicpu(hp1).opcode := A_LEA;
  9362. taicpu(hp1).loadref(0, NewRef);
  9363. TransferUsedRegs(TmpUsedRegs);
  9364. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9365. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  9366. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  9367. begin
  9368. { Move what is now the LEA instruction to before the SUB instruction }
  9369. Asml.Remove(hp1);
  9370. Asml.InsertBefore(hp1, p);
  9371. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  9372. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  9373. p := hp1;
  9374. end
  9375. else
  9376. begin
  9377. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  9378. RemoveCurrentP(p, hp1);
  9379. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  9380. end;
  9381. Result := True;
  9382. end;
  9383. end;
  9384. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  9385. begin
  9386. { we can skip all instructions not messing with the stack pointer }
  9387. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  9388. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  9389. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  9390. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  9391. ({(taicpu(hp1).ops=0) or }
  9392. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  9393. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  9394. ) and }
  9395. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  9396. )
  9397. ) do
  9398. GetNextInstruction(hp1,hp1);
  9399. Result:=assigned(hp1);
  9400. end;
  9401. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  9402. var
  9403. hp1, hp2, hp3, hp4, hp5: tai;
  9404. begin
  9405. Result:=false;
  9406. hp5:=nil;
  9407. { replace
  9408. leal(q) x(<stackpointer>),<stackpointer>
  9409. call procname
  9410. leal(q) -x(<stackpointer>),<stackpointer>
  9411. ret
  9412. by
  9413. jmp procname
  9414. but do it only on level 4 because it destroys stack back traces
  9415. }
  9416. if (cs_opt_level4 in current_settings.optimizerswitches) and
  9417. MatchOpType(taicpu(p),top_ref,top_reg) and
  9418. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  9419. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  9420. { the -8 or -24 are not required, but bail out early if possible,
  9421. higher values are unlikely }
  9422. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  9423. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  9424. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  9425. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  9426. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  9427. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  9428. GetNextInstruction(p, hp1) and
  9429. { Take a copy of hp1 }
  9430. SetAndTest(hp1, hp4) and
  9431. { trick to skip label }
  9432. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  9433. SkipSimpleInstructions(hp1) and
  9434. MatchInstruction(hp1,A_CALL,[S_NO]) and
  9435. GetNextInstruction(hp1, hp2) and
  9436. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  9437. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  9438. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  9439. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  9440. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  9441. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  9442. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  9443. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  9444. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  9445. GetNextInstruction(hp2, hp3) and
  9446. { trick to skip label }
  9447. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  9448. (MatchInstruction(hp3,A_RET,[S_NO]) or
  9449. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  9450. SetAndTest(hp3,hp5) and
  9451. GetNextInstruction(hp3,hp3) and
  9452. MatchInstruction(hp3,A_RET,[S_NO])
  9453. )
  9454. ) and
  9455. (taicpu(hp3).ops=0) then
  9456. begin
  9457. taicpu(hp1).opcode := A_JMP;
  9458. taicpu(hp1).is_jmp := true;
  9459. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  9460. RemoveCurrentP(p, hp4);
  9461. RemoveInstruction(hp2);
  9462. RemoveInstruction(hp3);
  9463. if Assigned(hp5) then
  9464. begin
  9465. AsmL.Remove(hp5);
  9466. ASmL.InsertBefore(hp5,hp1)
  9467. end;
  9468. Result:=true;
  9469. end;
  9470. end;
  9471. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  9472. {$ifdef x86_64}
  9473. var
  9474. hp1, hp2, hp3, hp4, hp5: tai;
  9475. {$endif x86_64}
  9476. begin
  9477. Result:=false;
  9478. {$ifdef x86_64}
  9479. hp5:=nil;
  9480. { replace
  9481. push %rax
  9482. call procname
  9483. pop %rcx
  9484. ret
  9485. by
  9486. jmp procname
  9487. but do it only on level 4 because it destroys stack back traces
  9488. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  9489. for all supported calling conventions
  9490. }
  9491. if (cs_opt_level4 in current_settings.optimizerswitches) and
  9492. MatchOpType(taicpu(p),top_reg) and
  9493. (taicpu(p).oper[0]^.reg=NR_RAX) and
  9494. GetNextInstruction(p, hp1) and
  9495. { Take a copy of hp1 }
  9496. SetAndTest(hp1, hp4) and
  9497. { trick to skip label }
  9498. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  9499. SkipSimpleInstructions(hp1) and
  9500. MatchInstruction(hp1,A_CALL,[S_NO]) and
  9501. GetNextInstruction(hp1, hp2) and
  9502. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  9503. MatchOpType(taicpu(hp2),top_reg) and
  9504. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  9505. GetNextInstruction(hp2, hp3) and
  9506. { trick to skip label }
  9507. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  9508. (MatchInstruction(hp3,A_RET,[S_NO]) or
  9509. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  9510. SetAndTest(hp3,hp5) and
  9511. GetNextInstruction(hp3,hp3) and
  9512. MatchInstruction(hp3,A_RET,[S_NO])
  9513. )
  9514. ) and
  9515. (taicpu(hp3).ops=0) then
  9516. begin
  9517. taicpu(hp1).opcode := A_JMP;
  9518. taicpu(hp1).is_jmp := true;
  9519. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  9520. RemoveCurrentP(p, hp4);
  9521. RemoveInstruction(hp2);
  9522. RemoveInstruction(hp3);
  9523. if Assigned(hp5) then
  9524. begin
  9525. AsmL.Remove(hp5);
  9526. ASmL.InsertBefore(hp5,hp1)
  9527. end;
  9528. Result:=true;
  9529. end;
  9530. {$endif x86_64}
  9531. end;
  9532. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  9533. var
  9534. Value, RegName: string;
  9535. begin
  9536. Result:=false;
  9537. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  9538. begin
  9539. case taicpu(p).oper[0]^.val of
  9540. 0:
  9541. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  9542. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  9543. begin
  9544. { change "mov $0,%reg" into "xor %reg,%reg" }
  9545. taicpu(p).opcode := A_XOR;
  9546. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  9547. Result := True;
  9548. {$ifdef x86_64}
  9549. end
  9550. else if (taicpu(p).opsize = S_Q) then
  9551. begin
  9552. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  9553. { The actual optimization }
  9554. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9555. taicpu(p).changeopsize(S_L);
  9556. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  9557. Result := True;
  9558. end;
  9559. $1..$FFFFFFFF:
  9560. begin
  9561. { Code size reduction by J. Gareth "Kit" Moreton }
  9562. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  9563. case taicpu(p).opsize of
  9564. S_Q:
  9565. begin
  9566. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  9567. Value := debug_tostr(taicpu(p).oper[0]^.val);
  9568. { The actual optimization }
  9569. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9570. taicpu(p).changeopsize(S_L);
  9571. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  9572. Result := True;
  9573. end;
  9574. else
  9575. { Do nothing };
  9576. end;
  9577. {$endif x86_64}
  9578. end;
  9579. -1:
  9580. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  9581. if (cs_opt_size in current_settings.optimizerswitches) and
  9582. (taicpu(p).opsize <> S_B) and
  9583. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  9584. begin
  9585. { change "mov $-1,%reg" into "or $-1,%reg" }
  9586. { NOTES:
  9587. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  9588. - This operation creates a false dependency on the register, so only do it when optimising for size
  9589. - 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
  9590. }
  9591. taicpu(p).opcode := A_OR;
  9592. Result := True;
  9593. end;
  9594. else
  9595. { Do nothing };
  9596. end;
  9597. end;
  9598. end;
  9599. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  9600. var
  9601. hp1: tai;
  9602. begin
  9603. { Detect:
  9604. andw x, %ax (0 <= x < $8000)
  9605. ...
  9606. movzwl %ax,%eax
  9607. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  9608. }
  9609. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  9610. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  9611. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  9612. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  9613. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  9614. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  9615. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  9616. begin
  9617. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  9618. taicpu(hp1).opcode := A_CWDE;
  9619. taicpu(hp1).clearop(0);
  9620. taicpu(hp1).clearop(1);
  9621. taicpu(hp1).ops := 0;
  9622. { A change was made, but not with p, so move forward 1 }
  9623. p := tai(p.Next);
  9624. Result := True;
  9625. end;
  9626. end;
  9627. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  9628. begin
  9629. Result := False;
  9630. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  9631. Exit;
  9632. { Convert:
  9633. movswl %ax,%eax -> cwtl
  9634. movslq %eax,%rax -> cdqe
  9635. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  9636. refer to the same opcode and depends only on the assembler's
  9637. current operand-size attribute. [Kit]
  9638. }
  9639. with taicpu(p) do
  9640. case opsize of
  9641. S_WL:
  9642. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  9643. begin
  9644. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  9645. opcode := A_CWDE;
  9646. clearop(0);
  9647. clearop(1);
  9648. ops := 0;
  9649. Result := True;
  9650. end;
  9651. {$ifdef x86_64}
  9652. S_LQ:
  9653. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  9654. begin
  9655. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  9656. opcode := A_CDQE;
  9657. clearop(0);
  9658. clearop(1);
  9659. ops := 0;
  9660. Result := True;
  9661. end;
  9662. {$endif x86_64}
  9663. else
  9664. ;
  9665. end;
  9666. end;
  9667. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  9668. var
  9669. hp1: tai;
  9670. begin
  9671. { Detect:
  9672. shr x, %ax (x > 0)
  9673. ...
  9674. movzwl %ax,%eax
  9675. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  9676. }
  9677. Result := False;
  9678. if MatchOpType(taicpu(p), top_const, top_reg) and
  9679. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  9680. (taicpu(p).oper[0]^.val > 0) and
  9681. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  9682. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  9683. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  9684. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  9685. begin
  9686. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  9687. taicpu(hp1).opcode := A_CWDE;
  9688. taicpu(hp1).clearop(0);
  9689. taicpu(hp1).clearop(1);
  9690. taicpu(hp1).ops := 0;
  9691. { A change was made, but not with p, so move forward 1 }
  9692. p := tai(p.Next);
  9693. Result := True;
  9694. end;
  9695. end;
  9696. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  9697. var
  9698. hp1, hp2: tai;
  9699. Opposite: TAsmOp;
  9700. NewCond: TAsmCond;
  9701. begin
  9702. Result := False;
  9703. { Change:
  9704. add/sub 128,(dest)
  9705. To:
  9706. sub/add -128,(dest)
  9707. This generaally takes fewer bytes to encode because -128 can be stored
  9708. in a signed byte, whereas +128 cannot.
  9709. }
  9710. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  9711. begin
  9712. if taicpu(p).opcode = A_ADD then
  9713. Opposite := A_SUB
  9714. else
  9715. Opposite := A_ADD;
  9716. { Be careful if the flags are in use, because the CF flag inverts
  9717. when changing from ADD to SUB and vice versa }
  9718. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9719. GetNextInstruction(p, hp1) then
  9720. begin
  9721. TransferUsedRegs(TmpUsedRegs);
  9722. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  9723. hp2 := hp1;
  9724. { Scan ahead to check if everything's safe }
  9725. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  9726. begin
  9727. if (hp1.typ <> ait_instruction) then
  9728. { Probably unsafe since the flags are still in use }
  9729. Exit;
  9730. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  9731. { Stop searching at an unconditional jump }
  9732. Break;
  9733. if (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  9734. { Instruction depends on FLAGS; break out }
  9735. Exit;
  9736. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9737. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  9738. { Move to the next instruction }
  9739. GetNextInstruction(hp1, hp1);
  9740. end;
  9741. while Assigned(hp2) and (hp2 <> hp1) do
  9742. begin
  9743. NewCond := C_None;
  9744. case taicpu(hp2).condition of
  9745. C_A, C_NBE:
  9746. NewCond := C_BE;
  9747. C_B, C_C, C_NAE:
  9748. NewCond := C_AE;
  9749. C_AE, C_NB, C_NC:
  9750. NewCond := C_B;
  9751. C_BE, C_NA:
  9752. NewCond := C_A;
  9753. else
  9754. { No change needed };
  9755. end;
  9756. if NewCond <> C_None then
  9757. begin
  9758. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  9759. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  9760. taicpu(hp2).condition := NewCond;
  9761. end;
  9762. { Move to the next instruction }
  9763. GetNextInstruction(hp2, hp2);
  9764. end;
  9765. if (hp2 <> hp1) then
  9766. InternalError(2021111501);
  9767. end;
  9768. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + ' 128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  9769. debug_op2str(opposite) + ' -128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  9770. taicpu(p).opcode := Opposite;
  9771. taicpu(p).oper[0]^.val := -128;
  9772. { No further optimisations can be made on this instruction, so move
  9773. onto the next one to save time }
  9774. p := tai(p.Next);
  9775. UpdateUsedRegs(p);
  9776. Result := True;
  9777. Exit;
  9778. end;
  9779. { Detect:
  9780. add/sub %reg2,(dest)
  9781. add/sub x, (dest)
  9782. (dest can be a register or a reference)
  9783. Swap the instructions to minimise a pipeline stall. This reverses the
  9784. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  9785. optimisations could be made.
  9786. }
  9787. if (taicpu(p).oper[0]^.typ = top_reg) and
  9788. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  9789. (
  9790. (
  9791. (taicpu(p).oper[1]^.typ = top_reg) and
  9792. { We can try searching further ahead if we're writing to a register }
  9793. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  9794. ) or
  9795. (
  9796. (taicpu(p).oper[1]^.typ = top_ref) and
  9797. GetNextInstruction(p, hp1)
  9798. )
  9799. ) and
  9800. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  9801. (taicpu(hp1).oper[0]^.typ = top_const) and
  9802. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  9803. begin
  9804. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  9805. TransferUsedRegs(TmpUsedRegs);
  9806. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9807. hp2 := p;
  9808. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  9809. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  9810. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9811. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  9812. begin
  9813. asml.remove(hp1);
  9814. asml.InsertBefore(hp1, p);
  9815. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  9816. Result := True;
  9817. end;
  9818. end;
  9819. end;
  9820. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  9821. begin
  9822. Result:=false;
  9823. { change "cmp $0, %reg" to "test %reg, %reg" }
  9824. if MatchOpType(taicpu(p),top_const,top_reg) and
  9825. (taicpu(p).oper[0]^.val = 0) then
  9826. begin
  9827. taicpu(p).opcode := A_TEST;
  9828. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  9829. Result:=true;
  9830. end;
  9831. end;
  9832. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  9833. var
  9834. IsTestConstX : Boolean;
  9835. hp1,hp2 : tai;
  9836. begin
  9837. Result:=false;
  9838. { removes the line marked with (x) from the sequence
  9839. and/or/xor/add/sub/... $x, %y
  9840. test/or %y, %y | test $-1, %y (x)
  9841. j(n)z _Label
  9842. as the first instruction already adjusts the ZF
  9843. %y operand may also be a reference }
  9844. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  9845. MatchOperand(taicpu(p).oper[0]^,-1);
  9846. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  9847. GetLastInstruction(p, hp1) and
  9848. (tai(hp1).typ = ait_instruction) and
  9849. GetNextInstruction(p,hp2) and
  9850. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  9851. case taicpu(hp1).opcode Of
  9852. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  9853. begin
  9854. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  9855. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9856. { and in case of carry for A(E)/B(E)/C/NC }
  9857. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  9858. ((taicpu(hp1).opcode <> A_ADD) and
  9859. (taicpu(hp1).opcode <> A_SUB))) then
  9860. begin
  9861. RemoveCurrentP(p, hp2);
  9862. Result:=true;
  9863. Exit;
  9864. end;
  9865. end;
  9866. A_SHL, A_SAL, A_SHR, A_SAR:
  9867. begin
  9868. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  9869. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  9870. { therefore, it's only safe to do this optimization for }
  9871. { shifts by a (nonzero) constant }
  9872. (taicpu(hp1).oper[0]^.typ = top_const) and
  9873. (taicpu(hp1).oper[0]^.val <> 0) and
  9874. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9875. { and in case of carry for A(E)/B(E)/C/NC }
  9876. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  9877. begin
  9878. RemoveCurrentP(p, hp2);
  9879. Result:=true;
  9880. Exit;
  9881. end;
  9882. end;
  9883. A_DEC, A_INC, A_NEG:
  9884. begin
  9885. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  9886. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9887. { and in case of carry for A(E)/B(E)/C/NC }
  9888. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  9889. begin
  9890. RemoveCurrentP(p, hp2);
  9891. Result:=true;
  9892. Exit;
  9893. end;
  9894. end
  9895. else
  9896. ;
  9897. end; { case }
  9898. { change "test $-1,%reg" into "test %reg,%reg" }
  9899. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  9900. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  9901. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  9902. if MatchInstruction(p, A_OR, []) and
  9903. { Can only match if they're both registers }
  9904. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  9905. begin
  9906. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  9907. taicpu(p).opcode := A_TEST;
  9908. { No need to set Result to True, as we've done all the optimisations we can }
  9909. end;
  9910. end;
  9911. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  9912. var
  9913. hp1,hp3 : tai;
  9914. {$ifndef x86_64}
  9915. hp2 : taicpu;
  9916. {$endif x86_64}
  9917. begin
  9918. Result:=false;
  9919. hp3:=nil;
  9920. {$ifndef x86_64}
  9921. { don't do this on modern CPUs, this really hurts them due to
  9922. broken call/ret pairing }
  9923. if (current_settings.optimizecputype < cpu_Pentium2) and
  9924. not(cs_create_pic in current_settings.moduleswitches) and
  9925. GetNextInstruction(p, hp1) and
  9926. MatchInstruction(hp1,A_JMP,[S_NO]) and
  9927. MatchOpType(taicpu(hp1),top_ref) and
  9928. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9929. begin
  9930. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  9931. InsertLLItem(p.previous, p, hp2);
  9932. taicpu(p).opcode := A_JMP;
  9933. taicpu(p).is_jmp := true;
  9934. RemoveInstruction(hp1);
  9935. Result:=true;
  9936. end
  9937. else
  9938. {$endif x86_64}
  9939. { replace
  9940. call procname
  9941. ret
  9942. by
  9943. jmp procname
  9944. but do it only on level 4 because it destroys stack back traces
  9945. else if the subroutine is marked as no return, remove the ret
  9946. }
  9947. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  9948. (po_noreturn in current_procinfo.procdef.procoptions)) and
  9949. GetNextInstruction(p, hp1) and
  9950. (MatchInstruction(hp1,A_RET,[S_NO]) or
  9951. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  9952. SetAndTest(hp1,hp3) and
  9953. GetNextInstruction(hp1,hp1) and
  9954. MatchInstruction(hp1,A_RET,[S_NO])
  9955. )
  9956. ) and
  9957. (taicpu(hp1).ops=0) then
  9958. begin
  9959. if (cs_opt_level4 in current_settings.optimizerswitches) and
  9960. { we might destroy stack alignment here if we do not do a call }
  9961. (target_info.stackalign<=sizeof(SizeUInt)) then
  9962. begin
  9963. taicpu(p).opcode := A_JMP;
  9964. taicpu(p).is_jmp := true;
  9965. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  9966. end
  9967. else
  9968. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  9969. RemoveInstruction(hp1);
  9970. if Assigned(hp3) then
  9971. begin
  9972. AsmL.Remove(hp3);
  9973. AsmL.InsertBefore(hp3,p)
  9974. end;
  9975. Result:=true;
  9976. end;
  9977. end;
  9978. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  9979. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  9980. begin
  9981. case OpSize of
  9982. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9983. Result := (Val <= $FF) and (Val >= -128);
  9984. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9985. Result := (Val <= $FFFF) and (Val >= -32768);
  9986. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  9987. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  9988. else
  9989. Result := True;
  9990. end;
  9991. end;
  9992. var
  9993. hp1, hp2 : tai;
  9994. SizeChange: Boolean;
  9995. PreMessage: string;
  9996. begin
  9997. Result := False;
  9998. if (taicpu(p).oper[0]^.typ = top_reg) and
  9999. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10000. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  10001. begin
  10002. { Change (using movzbl %al,%eax as an example):
  10003. movzbl %al, %eax movzbl %al, %eax
  10004. cmpl x, %eax testl %eax,%eax
  10005. To:
  10006. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  10007. movzbl %al, %eax movzbl %al, %eax
  10008. Smaller instruction and minimises pipeline stall as the CPU
  10009. doesn't have to wait for the register to get zero-extended. [Kit]
  10010. Also allow if the smaller of the two registers is being checked,
  10011. as this still removes the false dependency.
  10012. }
  10013. if
  10014. (
  10015. (
  10016. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  10017. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  10018. ) or (
  10019. { If MatchOperand returns True, they must both be registers }
  10020. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  10021. )
  10022. ) and
  10023. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  10024. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  10025. begin
  10026. 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);
  10027. asml.Remove(hp1);
  10028. asml.InsertBefore(hp1, p);
  10029. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  10030. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  10031. begin
  10032. taicpu(hp1).opcode := A_TEST;
  10033. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  10034. end;
  10035. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10036. case taicpu(p).opsize of
  10037. S_BW, S_BL:
  10038. begin
  10039. SizeChange := taicpu(hp1).opsize <> S_B;
  10040. taicpu(hp1).changeopsize(S_B);
  10041. end;
  10042. S_WL:
  10043. begin
  10044. SizeChange := taicpu(hp1).opsize <> S_W;
  10045. taicpu(hp1).changeopsize(S_W);
  10046. end
  10047. else
  10048. InternalError(2020112701);
  10049. end;
  10050. UpdateUsedRegs(tai(p.Next));
  10051. { Check if the register is used aferwards - if not, we can
  10052. remove the movzx instruction completely }
  10053. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  10054. begin
  10055. { Hp1 is a better position than p for debugging purposes }
  10056. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  10057. RemoveCurrentp(p, hp1);
  10058. Result := True;
  10059. end;
  10060. if SizeChange then
  10061. DebugMsg(SPeepholeOptimization + PreMessage +
  10062. 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)
  10063. else
  10064. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  10065. Exit;
  10066. end;
  10067. { Change (using movzwl %ax,%eax as an example):
  10068. movzwl %ax, %eax
  10069. movb %al, (dest) (Register is smaller than read register in movz)
  10070. To:
  10071. movb %al, (dest) (Move one back to avoid a false dependency)
  10072. movzwl %ax, %eax
  10073. }
  10074. if (taicpu(hp1).opcode = A_MOV) and
  10075. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10076. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  10077. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  10078. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  10079. begin
  10080. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  10081. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  10082. asml.Remove(hp1);
  10083. asml.InsertBefore(hp1, p);
  10084. if taicpu(hp1).oper[1]^.typ = top_reg then
  10085. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  10086. { Check if the register is used aferwards - if not, we can
  10087. remove the movzx instruction completely }
  10088. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  10089. begin
  10090. { Hp1 is a better position than p for debugging purposes }
  10091. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  10092. RemoveCurrentp(p, hp1);
  10093. Result := True;
  10094. end;
  10095. Exit;
  10096. end;
  10097. end;
  10098. end;
  10099. {$ifdef x86_64}
  10100. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  10101. var
  10102. PreMessage, RegName: string;
  10103. begin
  10104. { Code size reduction by J. Gareth "Kit" Moreton }
  10105. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  10106. as this removes the REX prefix }
  10107. Result := False;
  10108. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  10109. Exit;
  10110. if taicpu(p).oper[0]^.typ <> top_reg then
  10111. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  10112. InternalError(2018011500);
  10113. case taicpu(p).opsize of
  10114. S_Q:
  10115. begin
  10116. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  10117. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  10118. { The actual optimization }
  10119. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10120. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  10121. taicpu(p).changeopsize(S_L);
  10122. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  10123. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  10124. end;
  10125. else
  10126. ;
  10127. end;
  10128. end;
  10129. {$endif}
  10130. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  10131. var
  10132. XReg: TRegister;
  10133. begin
  10134. Result := False;
  10135. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  10136. Smaller encoding and slightly faster on some platforms (also works for
  10137. ZMM-sized registers) }
  10138. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  10139. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  10140. begin
  10141. XReg := taicpu(p).oper[0]^.reg;
  10142. if (taicpu(p).oper[1]^.reg = XReg) then
  10143. begin
  10144. taicpu(p).changeopsize(S_XMM);
  10145. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  10146. if (cs_opt_size in current_settings.optimizerswitches) then
  10147. begin
  10148. { Change input registers to %xmm0 to reduce size. Note that
  10149. there's a risk of a false dependency doing this, so only
  10150. optimise for size here }
  10151. XReg := NR_XMM0;
  10152. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  10153. end
  10154. else
  10155. begin
  10156. setsubreg(XReg, R_SUBMMX);
  10157. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  10158. end;
  10159. taicpu(p).oper[0]^.reg := XReg;
  10160. taicpu(p).oper[1]^.reg := XReg;
  10161. Result := True;
  10162. end;
  10163. end;
  10164. end;
  10165. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  10166. var
  10167. OperIdx: Integer;
  10168. begin
  10169. for OperIdx := 0 to p.ops - 1 do
  10170. if p.oper[OperIdx]^.typ = top_ref then
  10171. optimize_ref(p.oper[OperIdx]^.ref^, False);
  10172. end;
  10173. end.